# 分糖果 #### 问题描述 有n个小朋友围坐成一圈。老师给每个小朋友随机发偶数个糖果,然后进行下面的游戏: 每个小朋友都把自己的糖果分一半给左手边的孩子。 一轮分糖后,拥有奇数颗糖的孩子由老师补给1个糖果,从而变成偶数。 反复进行这个游戏,直到所有小朋友的糖果数都相同为止。 你的任务是预测在已知的初始糖果情形下,老师一共需要补发多少个糖果。 #### 输入格式 程序首先读入一个整数N(2 using namespace std; ``` ### after ```cpp ``` ## 答案 ```cpp int main() { int n; cin >> n; int *Candy = new int[n]; for (int i = 0; i < n; i++) { cin >> Candy[i]; } int total = 0; while (1) { bool flag = true; for (int i = 1; i < n; i++) { if (Candy[0] != Candy[i]) { flag = false; break; } } if (flag == true) break; int temp = Candy[n - 1]; for (int i = n - 1; i >= 0; i--) { if (i == 0) { Candy[0] = Candy[0] / 2 + temp / 2; } else Candy[i] = Candy[i] / 2 + Candy[i - 1] / 2; if (Candy[i] % 2 != 0) { Candy[i] += 1; total += 1; } } } cout << total << endl; } ``` ## 选项 ### A ```cpp int main() { int n; cin >> n; int *Candy = new int[n]; for (int i = 0; i < n; i++) { cin >> Candy[i]; } int total = 0; while (1) { bool flag = true; for (int i = 1; i < n; i++) { if (Candy[0] != Candy[i]) { flag = false; break; } } if (flag == true) break; int temp = Candy[n - 1]; for (int i = n; i >= 0; i--) { if (i == 0) { Candy[0] = Candy[0] / 2 + temp / 2; } else Candy[i] = Candy[i] / 2 + Candy[i - 1] / 2; if (Candy[i] % 2 != 0) { Candy[i] += 1; total += 1; } } } cout << total << endl; } ``` ### B ```cpp int main() { int n; cin >> n; int *Candy = new int[n]; for (int i = 0; i < n; i++) { cin >> Candy[i]; } int total = 0; while (1) { bool flag = true; for (int i = 1; i < n; i++) { if (Candy[0] != Candy[i]) { flag = false; break; } } if (flag == true) break; int temp = Candy[n - 1]; for (int i = n; i >= 0; i--) { if (i == 0) { Candy[0] = Candy[0] / 2 + temp / 2; } else Candy[i] = Candy[i] / 2 + Candy[i - 1] / 2; if (Candy[i] % 2 == 0) { Candy[i] += 1; total += 1; } } } cout << total << endl; } ``` ### C ```cpp int main() { int n; cin >> n; int *Candy = new int[n]; for (int i = 0; i < n; i++) { cin >> Candy[i]; } int total = 0; while (1) { bool flag = true; for (int i = 1; i < n; i++) { if (Candy[0] != Candy[i]) { flag = false; break; } } if (flag == true) break; int temp = Candy[n - 1]; for (int i = n - 1; i >= 0; i--) { if (i == 0) { Candy[0] = Candy[0] / 2 + temp / 2; } else Candy[i] = Candy[i] / 2 + Candy[i - 1] / 2; if (Candy[i] % 2 == 0) { Candy[i] += 1; total += 1; } } } cout << total << endl; } ```