第二周HDU-1004题解

问题链接:HDU-1004

问题简述

第一行输入一个整数n,表示热气球的个数,接下来n行每行输入一个颜色单词(长度小于15个字母),找出出现次数最多的颜色,并输出这个颜色。

思路

运用map,对每个颜色出现的次数计数,最后再输出次数最多的颜色。(我打的程序有个bug……在第二次输入时有,会循环两次,所以在30行的if里面加了个if条件语句,将这个bug避免掉)

AC通过的C++语言程序如下:

#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
int main()
{
	int n;
	while (cin >> n)
	{
		string a, y; vector<string> b; map<string, int> c; int x = 1;
		if (n == 0) break;
		for (int i = 0; i < n; i++)
		{
			cin >> a;
			if (i == 0) { b.push_back(a); c[a] = 1; y = a; }
			else
				for (int j = 0; j < b.size(); j++)
				{
					if (a == b[j])
					{
						c[a]++;
						if (c[a] > x)
						{
							x = c[a];
							y = a;
						}
						break;
					}
					if (j == b.size() - 1) { b.push_back(a); c[a] = 1; if (b.size() == 2) break; }
				}
		}
		cout << y << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43970556/article/details/84994514