杭电1004气球问题

题目:

求输入字符串里出现次数最多的字符串。

要求:从键盘输入N(气球颜色的个数)(0<=N<=1000)

后面接N行输入颜色的字符串(长度小于16)。如果N=0,则退出程序。

分析:

求取输入的字符串出现次数,可以使用STL的map容器,创造字符串(string)和int组合的容器,记录每个字符串的次数,利用迭代器iterator顺序遍历选取次数值最大的字符串输出,最后记得清空容器。

#include<stdio.h>
#include<map>
#include<iostream>
using namespace std;
int main()
{
	map<string,int> m;
	char str[50];
	string ans;
	int n,i,max;
	while(scanf("%d",&n)&&n){
		getchar();
		while(n--){
		gets(str);
		m[str]++;
	}
	map<string,int>::iterator ite;
		max = -1;
	for(ite = m.begin();ite!=m.end();ite++){
		if(max < ite->second){
			max = ite->second;
			ans = ite->first;
		}
	}
	cout<<ans<<endl;
	m.clear();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37807889/article/details/83095482