1. 程式人生 > >HDOJ 1004 Let the Balloon Rise (字串+stl)

HDOJ 1004 Let the Balloon Rise (字串+stl)

題目: 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
題意:給出每個氣球的顏色 統計出現次數最多的顏色 思路:網上的程式碼大多數都是開兩個陣列來記錄 自己的方法是用stl中的map函式來做 用map計數然後排序 但是map並不是線性的 不能用sort 需要轉換
程式碼:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
int n;
string s;

void value(vector<pair<int,string>> & vec,map<string,int> & mp){
    for(map<string,int>::iterator it=mp.begin();it!=mp.end();it++){
        vec.push_back(make_pair(it->second,it->first));
    }
    sort(vec.begin(),vec.end());
}

int main(){
    while(~scanf("%d",&n)){
        if(n==0) break;
        vector<pair<int,string>> vec;
        map<string,int>mp;
        while(n--){
            cin>>s;
            mp[s]++;
        }
        value(vec,mp);
        vector<pair<int,string>>::iterator it=vec.end()-1;
        cout<<it->second.c_str()<<endl;
    }
    return 0;
}

題外話:關於排序

  sort演算法只能對線性的容器進行排序 例如vector list deque 但是map是一個集合容器 裡面儲存的元素是pair 內部是按序儲存的 比如紅黑樹 如此就不能用sort進行排序 為了解決這個問題 可以把map中的元素放入到vector 從而進行排序操作