Sunday, November 1, 2009

10420: List of Conquests

For this problem, a C++ standard map could be used where the country is used as the key and the number of women Don Giovanni loved in the corresponding country is used as the value. The C++ standard library map automatically sorts its key and value pairs in ascending order according to the keys. In effect, a straightforward iteration on the map yields an alphabetical traversal on the countries accumulated.

Here's a sample implementation:

000 #include <stdio.h>
001 #include <map>
002 #include <iostream>
003 #include <string>
004
005 using namespace std;
006
007 int main() {
008 char line[100], ctmp[100];
009 int n, i, j;
010 map<string, int> countries;
011 map<string, int>::iterator iter;
012
013 fgets(line, 100, stdin);
014 sscanf(line, "%d", &n);
015
016 for (i = 0; i < n; i += 1) {
017 fgets(line, 100, stdin);
018
019 for (j = 0; 1; j += 1) {
020 if (line[j] == ' ') {
021 break;
022 }
023 ctmp[j] = line[j];
024 }
025 ctmp[j] = 0;
026
027 countries[ctmp] += 1;
028 }
029
030 for (iter = countries.begin(); iter != countries.end(); ++iter) {
031 cout << iter->first << " " << iter->second << endl;
032 }
033
034 return 0;
035 }

No comments:

Post a Comment