AtCoder 2373 Cookie Exchanges

Problem Statement
Takahashi, Aoki and Snuke love cookies. They have A, B and C cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.
This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action? Note that the answer may not be finite.

Constraints
1≤A,B,C≤109
Input
Input is given from Standard Input in the following format:

A B C
Output
Print the number of times the action will be performed by the three people, if this number is finite. If it is infinite, print -1 instead.

Sample Input 1
4 12 20
Sample Output 1
3
Initially, Takahashi, Aoki and Snuke have 4, 12 and 20 cookies. Then,

After the first action, they have 16, 12 and 8.
After the second action, they have 10, 12 and 14.
After the third action, they have 13, 12 and 11.
Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is 3.

Sample Input 2
14 14 14
Sample Output 2
-1
Sample Input 3
454 414 444
Sample Output 3
1

题目大意:三个人分饼干,每次把自己的饼干分成两部分给其他两个人,直到有人持有奇数个饼干为止,输出行动次数,如果无解则输出-1。

注意:每次分饼干要把自己原先的饼干全部分出去,再得到另外两人给的饼干;由题可知当三人持有饼干数相同时无解;可能存在有人一开始就持有奇数个饼干的情况,且输出优先级要高于无解,例如:1 1 1 ,应输出0而不是-1。

#include<cstdio>
using namespace std;
int main()
{
	int a,b,c,a1,b1,c1,num=0;
	scanf("%d%d%d",&a,&b,&c);
	if(a%2!=0||b%2!=0||c%2!=0)
	{
		printf("0\n");
		return 0;
	}
	if(a==b&&b==c)
	{
		printf("-1\n");
		return 0;
	}
	while(1)
	{
		a1=b/2+c/2;
		b1=a/2+c/2;
		c1=a/2+b/2;
		a=a1;
		b=b1;
		c=c1;
		num++;
		if(a%2!=0||b%2!=0||c%2!=0)
		{
			printf("%d\n",num);
			return 0;
		}
	}
	return 0;
}

总结:要结合题目样例思考可能会出现的特殊输入输出情况。

猜你喜欢

转载自blog.csdn.net/yuxiangmitu/article/details/81276290