1. 程式人生 > >杭電oj--1034(糖果分配)

杭電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;
}