OJ_糖果分享游戏

题干

OJ_糖果分享游戏_第1张图片
OJ_糖果分享游戏_第2张图片

c++实现

#define _CRT_SECURE_NO_WARNINGS
#include
#include
using namespace std;

void ShareCandy(vector<int>& student) {
	int size = student.size();
	vector<int> share(size); //保存每个同学交换前,糖果数量的一半
	for (int i = 0; i < size; i++) {
		share[i] = student[i] / 2;
	}
	for (int i = 0; i < size; i++)
	{
		student[i] -= share[i];
		student[(i + 1) % size] += share[i];
	}
	for (int i = 0; i < size; i++)
	{
		if (student[i] % 2 == 1) {
			++student[i];
		}
	}
}

bool CheckCandy(vector<int>& student) {
	int first = student[0];
	for (int i = 1; i < student.size(); ++i) {
		if (first != student[i]) {
			return false;
		}
	}
	return true;
}

int main() {
	int N;
	while (scanf("%d", &N) != EOF) {
		if (N == 0) {
			break;
		}

		vector<int> student(N);
		for (int i = 0; i < N; i++) {
			scanf("%d", &student[i]);
		}

		int turn = 0;
		while (CheckCandy(student) == false) {
			ShareCandy(student);
			++turn;
		}
		printf("%d %d\n", turn, student[0]);
	}
	return 0;
}

你可能感兴趣的:(算法,c语言)