热身题B——B - Candy Sharing Game

本文介绍了一个关于学生间传递和均分糖果的游戏模拟程序。游戏中,学生们围成一圈,每轮通过传递一半糖果给右边的同学,并由老师补充奇数糖果至偶数,直至所有学生的糖果数量相同。代码使用C++实现,包括内存分配、糖果传递逻辑及均分检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

能把热身赛的题做成我这种水平的菜鸡估计没几个了。。。

理工糙汉子没有太多的话想对你讲,直接上代码算了,反正有注释。。

题目:

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. 
代码:
#include <iostream>
#include <cstdlib>
using namespace std;

bool notequal(int *candys,int n);		//判断是否均分 

int main()
{
	int n;
	cin>>n;
	while(n){
		int *candys=(int *)malloc(n*sizeof(int));		//分配内存,我把new怎么用给忘了(手动黑脸)  
		for(int i=0;i<n;i++)
			cin>>candys[i];
		int cnt=0;
		while(notequal(candys,n)){			//判断是否均分 
			cnt++;							//吹哨次数加一 
			int half=candys[n-1]/=2;		//先将最后一个同学的糖果减半并放入half中存起来 
			for(int i=n-1;i>0;i--){			//从第n-1个同学开始向第1个同学遍历
				candys[i]+=candys[i-1]/=2;	//依次将前一个同学的糖果分一半给自己 
				if(candys[i]%2)				//若糖果数为奇数 
					candys[i]++;			//老师给一个 
			}
			candys[0]+=half;				//将第n-1个同学的糖果分给第0个同学 
			if(candys[0]%2)	candys[0]++;	//判断第0个同学是否是奇数 
		}									//重复操作直到每个同学糖果数相等 
		cout<<cnt<<' '<<candys[0]<<endl; 
		free(candys);
		cin>>n;
	}
	return 0;
}

bool notequal(int *candys,int n){
	for(int i=0;i<n-1;i++)
		if(candys[i]!=candys[i+1])
			return true;
	return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值