杭电oj--1034(糖果分配)

Problem Description:

         A number of students sit in a circle facing their teacher in the center. Each student initially has an even number of pieces of candy. When the teacher blows a whistle, each student simultaneously gives half of his or her candy to the neighbor on the right. Any student, who ends up with an odd number of pieces of candy, is given another piece by the teacher. The game ends when all students have the same number of pieces of candy.
         Write a program which determines the number of times the teacher blows the whistle and the final number of pieces of candy for each student from the amount of candy each child starts with. 

Input:

        The input may describe more than one game. For each game, the input begins with the number N of students, followed by N (even) candy counts for the children counter-clockwise around the circle. The input ends with a student count of 0. Each input number is on a line by itself.

Output:

For each game, output the number of rounds of the game followed by the amount of candy each child ends up with, both on one line.

要点分析:1.每个学生最初都有偶数块糖

                  2.每个学生同时把一半的糖果送给右边的邻居

                  3.如果学生有奇数,老师就给他一块糖果

                  4.游戏结束时,所有学生都有同样数量的糖果

程序要点:需要注意第n-1位学生 给第0位学生的糖果,可以先用一个变量储存第n-1位学生一半的糖果,然后再加上第0位学生的糖果。                   假设有6位学生,先储存s[5],再由s[4]->s[5]  s[3]->s[4]  s[2]->s[3]  s[1]->s[2]  s[0]->s[1]  最后才是1操作s[5]->s[0],这样才能不互相影响。

                 

#include<iostream>
using namespace std;
int main(){
	int s[100],n,n1,m,count,flag=0,i=0;
	while(cin>>n){
		if(n==0) break;
		count=0;
		flag=0;
		for( i=0;i<n;i++)
			cin>>s[i];
		n1=n;
		while(1){//
			n1=n;
			m=s[n-1]/2;
			while(n1--){//分糖操作
				if(n1==0)
					break;
				s[n1]/=2;
				s[n1]+=s[n1-1]/2;
			}
			s[0]/=2;
			s[0]+=m;//分糖
			for(i=0;i<n;i++)
				if(s[i]%2==1)
					s[i]++;//老师平衡
			count++;
			flag=0;
			for(i=0;i<n-1;i++)
				if(s[i]==s[i+1])//判断是否所有的学生有相同数量的糖果
					flag++;
			if(flag==n-1){
				cout<<count<<" "<<s[0]<<endl;
				break;
			}
			
		}
	}
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41048982/article/details/84333539