当前位置:网站首页>C language: detailed explanation of soda bottle

C language: detailed explanation of soda bottle

2022-08-09 07:45:00 Gaoyou Wu Shao

题目链接:汽水瓶

在这里插入图片描述
在这里插入图片描述

#include<stdio.h>
int main()
{
    
	//多组输入
	int n = 0;
	while ((scanf("%d", &n) != EOF))
	{
    
		if (n == 0)
		{
    
			return 0;
		}
		else {
    
			int count = 0;//计数器
			int dh = 0;//Redeem for soda
			while (((n + 1) / 3) != 0)//(n+1)/3!=0Instructions can also be exchanged
			{
    
				if (n != 2)//Not borrowed1bottle change
				{
    
					dh = n / 3;
					//If the number of empty bottlesn正好是3的倍数,No need to borrow it
					//If the bottle is emptyn差1个是3的倍数,可以借一个
					n = dh + n % 3;//Leftover soda before redemption+Redeem for soda=The number of new empty bottles
					count += dh;
					dh = 0;
				}
				else//最后剩下2个空瓶,Borrow one for another,Finally returned the empty bottle
				{
    
					count++;
					break;
				}
			}
			printf("%d\n", count);
		}
	}
	return 0;
}

There is a misunderstanding in this question,就是“借一瓶”Borrowing a bottle of this is not always available.
比如你现在29空瓶,Although the title of it is that you can borrow an empty bottle,好像就30An empty bottle,Then you redeem at once10个.

其实不是这样的.It is required that you use it first29个空瓶换9个,然后剩余2+9个空瓶,And then exchange to get3瓶.
3The bottle is finished,剩余2+3个空瓶,And then exchange to get1瓶.
1The bottle is finished,剩余2+1个空瓶,And then exchange to get1瓶.
1Borrow the bottle again1The bottle is also not enough to redeem,循环结束.示意图如下:
在这里插入图片描述

This borrowing a bottle for redemption happens at the end of your leftovers2The case of an empty bottle,
你借1Get an empty bottle3空瓶,Then just change1个,Return the empty bottle after drinking.

其他情况,Borrowing is not allowed,This is also where this topic is more pitted,容易被绕进去.

原网站

版权声明
本文为[Gaoyou Wu Shao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090727029905.html