10420 - List of Conquests

题意:
输入一组字符串, 每行的第一个单词表示国家名, 统计各个国家名出现次数, 然后按国家名的字母序由小到大进行输出.

思路:
<国家名, 出现次数> 对存放在 map 里, 每读入一行, 就取到国家名, 然后在 map 里递增一下; 最后把国家名进行排序, 按从小到大进行输出.

要点:
使用  sort(countries.begin(), countries.end(), less<string>()); 进行从小到大排序.

题目:
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=1361

代码:

# include <iostream>
# include <string>
# include <cstdio>
# include <cstring>
# include <vector>
# include <algorithm>
# include <cctype>
# include <iterator>
# include <assert.h>
# include <map>
using namespace std;

// 使用 sort 排序

int main(int argc, char const *argv[])
{
  #ifndef ONLINE_JUDGE
    freopen("10420_i.txt", "r", stdin);  
    freopen("10420_o.txt", "w", stdout); 
  #endif
  
  int numLine;
  cin >> numLine;
  cin.ignore();   // cin 之后接 getline 一定要记得这一步

  string line;
  map<string, int> women;

  // 输入
  while (numLine--) {
    getline(cin, line);

    for (int i=0; i<line.size(); i++) {
      if ( !isalpha(line[i]) ) {
        string country = line.substr(0, i);
        women[country] = women[country] + 1;
        break;
      }
    }
  }

  // 对国家名进行排序
  vector<string> countries;
  for (map<string, int>::iterator it = women.begin(); it != women.end(); it++) {
    countries.push_back(it->first);
  }
  sort(countries.begin(), countries.end(), less<string>());

  // 输出
  for (int i=0; i<countries.size(); i++) {
    string country = countries[i];
    cout << country << " " << women[country] << endl;
  }

  return 0;
}


环境: C++ 4.5.3 - GNU C++ Compiler with options: -lm -lcrypt -O2 -pipe -DONLINE_JUDGE

UPDATE: 10420 - List of Conquests(UPDATE)

你可能感兴趣的:(list,uva,of,10420,Conquests)