- 原题
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.
理解&思路
计算一系列字符串中出现次数最多的字符串并输出。
通过建立另外一个数组来存放每一个字符串出现的次数,对数组内数据进行搜索,找到最大的数,即对应出现次数最多的字符串。AC代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
cin>>num;
while(num!=0)
{
string str;
vector<int> times;
vector<string> col;
for(int i=0;i<num;i++)
{
cin>>str;
col.push_back(str);
}
for(int j=0;j<col.size();j++)
times.push_back(1);
for(int i=0;i<col.size();i++)
for(int j=i+1;j<col.size();j++)
if (col[i]==col[j])
{
times[i]++;
times[j]++;
}
int max=0;
string most;
for(int i=0;i<times.size();i++)
{
if(times[i]>max)
{
max=times[i];
most=col[i];
}
}
cout<<most<<endl;
cin>>num;
}
return 0;
}
- 总结
可以优化:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num;
cin>>num;
while(num!=0)
{
string str;
vector<int> times;
vector<string> col;
for(int i=0;i<num;i++)
{
cin>>str;
col.push_back(str);
}
for(int j=0;j<col.size();j++)
times.push_back(1);
for(int i=0;i<col.size();i++)
for(int j=i+1;j<col.size();j++)
if (col[i]==col[j])
{
times[i]++;
}
int max=0;
string most;
for(int i=0;i<times.size();i++)
{
if(times[i]>max)
{
max=times[i];
most=col[i];
}
}
cout<<most<<endl;
cin>>num;
}
return 0;
}
少一步赋值,效率高一些。