1. 程式人生 > >水過杭電OJ hdu1004

水過杭電OJ hdu1004

Java程式碼

import java.util.*;
public class Main {
    public static void main(String[] args) {
        String color;
        Scanner scanner = new Scanner(System.in);
        HashMap<String, Integer> colorsMap = new HashMap<>();
        int N;
        while (scanner.hasNext()) {
            N = scanner.nextInt();
            if (0 == N) {
                break;
            }
            scanner.nextLine();
            while (N > 0) {
                N--;
                color = scanner.nextLine();
                if (colorsMap.containsKey(color)) {
                    //已存在
                    int oldValue = colorsMap.get(color);
                    colorsMap.replace(color, oldValue + 1);
                } else {
                    colorsMap.put(color, 1);
                }
            }
            ArrayList arrayList = new ArrayList<>(colorsMap.values());
            Collections.sort(arrayList);
            int maximum = (int) arrayList.get(arrayList.size() - 1);
            HashSet<String> colors = new HashSet<>(colorsMap.keySet());
            for (Object str : colors) {
                if (colorsMap.get(str) == maximum) {
                    System.out.println(str);
                    break;
                }
            }
            colorsMap.clear();
        }
    }
}

C++程式碼

程式碼參考http://blog.pureisle.net/archives/884.html

void hdu1004()
{
    freopen("inputdata.txt", "r", stdin);//輸入資料重定向
    //0<N<=1000
    int N = 0;
    string color;
    map<string, int> balloons;
    map<string, int>::iterator p, m;
    while (cin >> N)
    {
        if (0 == N) break;
        balloons.clear();
        for (int i = 0; i < N; ++i)
        {
            cin >> color;
            balloons[color]++;
        }
        p = m = balloons.begin();
        for (p; p != balloons.end(); p++)
        {
            cout << "p->first:" << p->first << endl;//first是key
            cout << "p->second:" << p->second << endl;//second是value
            
            if (p->second > m->second) m = p;
        }
        cout << m->first << endl;
    }

    fclose(stdin);//關閉
}