ACM题目——杭电1004 Let the Balloon Rise

Problem 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

思路一:想法应该比较简单,就是设置一个记录字符出现次数的vector,然后通过查找vector最大元素,找到相应的字符

实现:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
 int num;
 cin>>num;
 while(num!=0)
 {
  string str;
  vector<int> times;
  vector<string> vecs;
  for(int i=0;i<num;i++)
  {
   cin>>str;
   vecs.push_back(str);
  }
  for(int j=0;j<vecs.size();j++)
   times.push_back(1);
  for(int i=0;i<vecs.size();i++)
   for(int j=i+1;j<vecs.size();j++)
    if (vecs[i]==vecs[j])
    {
     times[i]++;
     times[j]++;
    }
  int max=0;
//当如果设置max为1时,会出现当所有的颜色只出现一遍的时候系统会出现错误。
  string strMost;
  for(int i=0;i<times.size();i++)
  {
   if(times[i]>max)
   {
    max=times[i];
    strMost=vecs[i];
   }
  }
  cout<<strMost<<endl;
  cin>>num;
 }
 return 0;
}

注:如果只用C++中的数组来完成的话,其实大同小异:

#include<iostream>
#include<String>
using namespace std;
int main(){
	
	int n;
	int t;
	while(cin>>n&&n){
		string b[n];
		int v=n;
		while(n--){
			cin>>b[n];
		}
		int r[v];
		for(int i=0;i<v;i++){
			r[i]=0;
			for(int j=0;j<v;j++){
				if(b[i]==b[j]) r[i]++;
			}
		}
		int q=0;
		for(int e=0;e<v;e++){
			if(r[q]<=r[e]) q=e;
		}
		cout<<b[q]<<endl;
	}
	return 0;
}

思路二:可以用到STL标准库中的map<string,int>来保存,当map的first插入一个string的时候,map的second++,就可以统计出具体的string的个数了,然后遍历找到最大值就可以了

实现:

#include <iostream>
#include <map>
#include <string>
 
using namespace std;
 
 
 
int main(){
	map<string, int> balllen;
	int n;
	string str;
 
	while (cin>> n && n > 0)
	{
		balllen.clear();
		while (n--)
		{
			cin >> str;
			balllen[str]++;
 
		}
		int max = 0;
		string maxColor;
		map<string, int>::iterator iter;
		for (iter = balllen.begin(); iter != balllen.end(); iter++)
		{
			if (iter->second > max)
			{
				max = (*iter).second;
				maxColor = (*iter).first;
			}
		}
		cout << maxColor << endl;
 
	}
 
	return 0;
 
}

猜你喜欢

转载自blog.csdn.net/qq_38278799/article/details/81288149
今日推荐