木棒

Problem Description
Anthony has collected a large amount of sticks for manufacturing chopsticks. In order to simplify his job, he wants to fetch two equal-length sticks for machining at a time. After checking it over, Anthony finds that it is always possible that only one stick is left at last, because of the odd number of sticks and some other unknown reasons. For example, Anthony may have three sticks with length 1, 2, and 1 respectively. He fetches the first and the third for machining, and leaves the second one at last. You task is to report the length of the last stick.
Input
The input file will consist of several cases.
Each case will be presented by an integer n (1<=n<=100, and n is odd) at first. Following that, n positive integers will be given, one in a line. These numbers indicate the length of the sticks collected by Anthony.
The input is ended by n=0.
Output
For each case, output an integer in a line, which is the length of the last stick.
Sample Input
3
1
2
1
0
Sample Output

2

/*
map容器是映射容器,提供一对一的映射
*/
#include<iostream>
#include<map>
using namespace std;
int main()
{
	//freopen("b.txt","r",stdin);
	int n,x;
	while(scanf("%d",&n)==1&&n)
	{
		map<int,int>mp;//map容器的声明,
		map<int,int>::iterator it;//map容器迭代器的声明
		while(n--)
		{
			scanf("%d",&x);
			mp[x]++;
		}
		//while循环完后,mp[1]=2,mp[2]=1;
		for(it=mp.begin();it!=mp.end();it++)//用迭代器对mp的所以元素遍历
		{
			if(it->second%2==1)//如果某元素对应的值为级数,如在此题中,mp[2]=1
			{
				printf("%d\n",it->first);//输出该元素,在此题中输出2
				break;
			}
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"粉粹木棒"(Crush the Stick)是一个经典的编程练习,通常用于教学或演示递归算法在C++中的应用。这个练习中,你需要编写一个函数,计算一根木棒在一系列压力作用下最终断裂成零段的最小次数。木棒每受到一定的压力就会断成两段,直到无法再断为止。 以下是一个简单的C++代码示例,使用递归实现这个功能: ```cpp #include <iostream> using namespace std; int crushTheStick(int pressure, int currentLength) { // 基线条件:如果木棒长度为0,说明已经断成零段,返回0 if (currentLength == 0) { return 0; } // 递归条件:如果当前长度大于压力,表示木棒还能断,需要继续递归 else if (currentLength > pressure) { // 断一次,木棒长度减半,需要断裂次数加一 return 1 + crushTheStick(pressure, currentLength / 2); } // 如果木棒长度正好等于压力,意味着不需要进一步断裂 else { return crushTheStick(pressure, 0); // 木棒断裂后直接返回0 } } int main() { int pressure; // 输入压力值 cout << "Enter the pressure: "; cin >> pressure; int initialLength = 1000; // 或者其他初始木棒长度 int minBreaks = crushTheStick(pressure, initialLength); cout << "Minimum number of breaks needed to crush the stick: " << minBreaks << endl; return 0; } ``` 在这个代码中,`crushTheStick`函数接受压力值和当前木棒长度作为参数,然后根据规则进行递归。用户可以在`main`函数中输入压力值,并调用该函数获取结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值