题目链接
也是一道水题,曾经在做《java趣味编程100例》里面做过。
题目思维是挺简单的,但是要注意,传递是要simultaneously同时的,也就是假设3个人分别有糖果 2 4 6 那么他们传递一轮后应该是 4 3 5才对。
为此我为他们分别弄了两个临时变量temp和temp2来存储临时值。
具体请见代码:
#include <iostream> using namespace std; int a[1000]; int main() { int n,count,temp,temp2; //temp用语保存当前数组a[i]/2的值 while(cin>>n&&n) { for(int i=0;i<n;i++) cin>>a[i]; int flag=0; //用于判断是否全部元素一致 count=0; while(!flag) { count++; temp=a[n-1]/2; for(int i=0;i<n;i++) { temp2 = a[i]/2; a[i]=a[i]/2 + temp; //temp保留其上一个的值的1/2 temp = temp2; if(a[i]%2) a[i]++; } flag=1; //将flag置为1若下列循环存在不一样的数 即继续循环 flag=0 for(int i=0;i<n;i++) for(int j=i;j<n;j++) { if(a[i]!=a[j]) flag=0; } } cout<<count<<" "<<a[0]<<endl; } return 0; }