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
//没学map之前的代码,毕竟我们没有办法以string类型当成是数组的下标我们只能去遍历所有的节点
#include<stdio.h>
#include<string.h>
typedef struct node
{
char color[20];
int num;
}Node;
Node ballon[1100];
int main()
{
int n;
while(~scanf("%d",&n))
{ getchar();
if(n==0)
break;
int cnt=0;
memset(ballon,0,sizeof(ballon));
for(int i=0;i<n;i++)
{
char yanse[10];
scanf("%s",yanse);
getchar();
int flag=0;
for(int j=0;j<cnt;j++)
{
if(!strcmp(ballon[j].color,yanse))
{
flag=1;
ballon[j].num++;
}
}
if(!flag)
{
strcpy(ballon[cnt].color,yanse);
ballon[cnt++].num++;
}
}
int max=0;
char temp[20];
for(int i=0;i<cnt;i++)
{
//printf("**%s %d**\n",ballon[i].color,ballon[i].num);
if(ballon[i].num>max)
{
max=ballon[i].num;
strcpy(temp,ballon[i].color);
}
}
printf("%s\n",temp);
}
return 0;
}
自从用了map(),生活简单了很多
#include<cstdio>
#include<iostream>
#include<string>
#include<map>
//#include<bits\stdc++.h>
//这个库也是一个好东西,就不用麻烦的去记住这些什么库了
using namespace std;
//利用map就可以把string当成是下标可以直接mp[string]++,
//就是不用只是int型的当做下标这样的话,就是代码很简洁,很方便
int main()
{
map<string,int> mp;
int n;
while(~scanf("%d",&n))
{
if(n==0)
break;
mp.clear();//map本质上好像是一个二叉树,复杂度log(n),也需要清空
while(n--)
{
string tmp;
cin>>tmp;
mp[tmp]++;
//[]运算符可以直接用,本来就已经重载完成了,看成数组就好
}
int Max=-1;
string res;
for(auto it : mp)//定义迭代器,进行遍历,就是可以看成是一个指针
{
if(it.second>Max)
{
Max=it.second;
res=it.first;
}
}
cout<<res<<endl;
}
return 0;
}