Let the Balloon Rise HDU 1004

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
题目

题目意思呢,就是给你n个字符串,让你找出这n个字符串中出现次数最多的那个串。

一开始直接暴力拿了个字符串数组写的,后来想起其他的STL,又整了个map,但其实好像什么都可以??

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#include <map>
#include <string>
using namespace std;
int n, t[10000], l, ans;
string  s[10000];

int main() {
    while (scanf("%d", &n) != EOF) {
        if (n == 0)
            break;
        for (int i = 1; i <= n; ++i)
            cin >> s[i];
        sort(s + 1, s + n + 1);
        l = 0;
        ans = 0;
        for (int i = 1; i <= n; ++i)
            t[i] = 0; //t[i]用来计数的,这里是初始化
        for (int i = 1; i <= n; ++i) {
            if (s[i] != s[i - 1])
                s[++l] = s[i], t[l]++;
            else
                t[l]++;
        }
        for (int i = 1; i <= l; ++i)
            if (t[ans] < t[i])
                ans = i;
        cout << s[ans] << endl;
    }
    return 0;
}
string写的

 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#include <map>
#include <string>
using namespace std;
int n;
map<string, int>t;
string ans, s;

int main() {
    while (scanf("%d", &n) != EOF) {
        if (n == 0)
            break;
        t.clear();//依旧是每次的初始化清空。
        ans = "";
        for (int i = 1; i <= n; ++i) {
            cin >> s;
            t[s]++;
            if (t[s] > t[ans])
                ans = s;
        }
        cout << ans << endl;
    }
    return 0;
}
map写的

 

posted @ 2021-01-15 10:36  月亮茶  阅读(41)  评论(0编辑  收藏  举报