C/C++ Programming Learning-Week 8 ⑤ Drinking

Topic link

Title description

Wang Dading likes to drink, and when the inventory is all drunk, he goes downstairs to buy it. The store just downstairs has launched a special offer in response to the school’s ACM competition: all the beer bought in this store will be 3 empty bottles after drinking. You can change a bottle, 4 bottle caps can also change a bottle of wine.

Wang Dading thought it was too cost-effective and decided to buy more. Now he can buy N bottles of wine with the money in his hand, but he can't figure it out. How many bottles can he drink in total through exchange activities? He is sad. Can you help him calculate the amount of alcohol he can drink?

Input format:

The first line of input is a positive integer T, which represents the number of test samples, 0<T≤100.

Next, there are T rows. Each row enters an integer N, which represents the quantity of beer purchased at the beginning, 0≤N<1000000.

Output format:

Corresponding to each set of data, output a result, that is, the total number of beer that can be drunk after exchange through the activity.

Sample Input

3
1
2
10

Sample Output

1
2
22

Ideas

A very interesting question, 3 empty bottles can be exchanged for a bottle of wine, 4 bottle caps can also be exchanged for a bottle of wine, we can define two cnt variables to count the number of empty bottles and the number of bottle caps, using while Cycle to simulate the process of drinking and exchanging wine, the specific operation can be seen in the code. Of course, you can also calculate the formula by hand, and the time complexity will be greatly reduced.

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int t, n, sum, cnt1, cnt2;
	while(cin >> t)
	{
    
    
		while(t--)
		{
    
    
			cin >> n;
			sum = n;
			cnt1 = n;
			cnt2 = n;
			while(cnt1 >= 3 || cnt2 >= 4)
			{
    
    
				if(cnt1 >= 3)
				{
    
    
					sum += cnt1 / 3;
					cnt2 += cnt1 / 3;
					cnt1 = cnt1 / 3 + cnt1 % 3;
				}
				if(cnt2 >= 4)
				{
    
    
					sum += cnt2 / 4;
					cnt1 += cnt2 / 4;
					cnt2 = cnt2 / 4 + cnt2 % 4;
				}
			}
			cout << sum << endl;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/113079901