#2020.01.13训练题解#STL和并查集(A题)

题源HDU-1004

HDU-1004-Let the Balloon Rise

Description
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the judges’ favorite time is guessing the most popular problem. When the contest is over, they will count the balloons of each color and find the result.
This year, they decide to leave this lovely job to you.

Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) – the total number of balloons distributed. The next N lines contain one color each. The color of a balloon is a string of up to 15 lower-case letters.
A test case with N = 0 terminates the input and this test case is not to be processed.

Output
For each case, print the color of balloon for the most popular problem on a single line. It is guaranteed that there is a unique solution for each test case.

Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0

Sample Output
red
pink

题意

  • 输入N:代表有N个气球颜色待输入
  • 输入N行string:每个string是不超过15个字符的小写字母字符串,代表气球颜色
  • 输出哪种颜色的气球出现次数最多
  • 有多组输入,输入的N==0时,程序结束(终止输入)

题解

  • 这道题要记录每种string出现的int次数,所以比较快的方法是构建一个<string,int>型map
  • 当然如果构造一个结构体,输入后在结构体数组里面遍历找是哪一个的name值也可
  • 但显然结构体数组的遍历不如map来得方便快捷
  • 接着就是每次输入string的时候,以string键的map值++,相当于普通数组的下标变成了string
  • 然后每组N输入之后int一个max值为0,每次输入的时候记录变化过程中的max最大值
  • 最后构造一个map的迭代器it,当it->second(此时的值)==max的时候输出it->first(此时的键)
  • 每一组数据测试完毕后,一定一定要将用过的map数组清空!!!
  • 最后注意,循环输入的时候判断&&N!=0即可

涉及知识点

  • C++的STL容器中 map 的记录和输出
  • 对于map的用法-详见链接博客介绍map

AC代码

#include<stdio.h>
#include<iostream>
#include<string>
#include<map>
using namespace std; 
int main()
{
	int N;
	string color;
	map<string,int> num;
	while(cin>>N&&N!=0)
	{
		int i,max=0;
		for(i=0;i<N;i++)
		{
			cin>>color;
			num[color]++;//map数组的值若为int则初始为0 
			if(num[color]>max) max=num[color];
		}
		for(map<string,int>::iterator it=num.begin();it!=num.end();it++)
		{
			if(it->second==max)
			{
				cout<<it->first<<endl;
				break;
			}
		}
		num.clear();
	}
	return 0;
}
发布了22 篇原创文章 · 获赞 0 · 访问量 408

猜你喜欢

转载自blog.csdn.net/qq_46184427/article/details/104053835