USACO Section 3.1: Contact

算法简单,写起来遇到些小问题

 1 /*

 2 ID: yingzho1

 3 LANG: C++

 4 TASK: contact

 5 */

 6 #include <iostream>

 7 #include <fstream>

 8 #include <string>

 9 #include <map>

10 #include <vector>

11 #include <set>

12 #include <algorithm>

13 #include <stdio.h>

14 #include <queue>

15 #include <cstring>

16 #include <cmath>

17 #include <list>

18 

19 using namespace std;

20 

21 ifstream fin("contact.in");

22 ofstream fout("contact.out");

23 

24 int A, B, N;

25 string input;

26 

27 struct fre {

28     int frequency;

29     string content;

30 };

31 

32 //bool cmp(const int &a, const int &b) {return a > b;}

33 bool cmp(const fre &a, const fre &b) {

34     if (a.frequency == b.frequency) {

35         if (a.content.size() == b.content.size()) return a.content < b.content;

36         else return a.content.size() < b.content.size();

37     }

38     else return a.frequency > b.frequency;

39 }

40 

41 int main()

42 {

43     fin >> A >> B >> N;

44     while (!fin.eof()) {

45         string frag;

46         getline(fin, frag);

47         if (!input.size()) input = frag;

48         else input = input + frag;

49     }

50     map<string, int> rec;

51     for (int len = A; len <= B; len++) {

52         for (int cur = 0; cur + len <= input.size(); cur++) {

53             rec[input.substr(cur, len)]++;

54         }

55     }

56     vector<fre> res;

57     for (map<string, int>::iterator it = rec.begin(); it != rec.end(); it++) {

58         fre tmp;

59         tmp.frequency = it->second;

60         tmp.content = it->first;

61         res.push_back(tmp);

62     }

63     sort(res.begin(), res.end(), cmp);

64     int step = 0;

65     int cur = 0;

66     int pre = 0;

67     while (step <= N && cur < res.size()) {

68         //cout << endl << "step: " << step << endl;

69         if (cur == 0 || res[cur].frequency != res[cur-1].frequency) {

70             pre = cur;

71             if (step == N) break;

72             if (cur) fout << endl;

73             fout << res[cur].frequency << endl;

74             fout << res[cur].content;

75             step++;

76         }

77         else {

78             if ((cur-pre) % 6 == 0) fout << endl << res[cur].content;

79             else fout << " " << res[cur].content;

80         }

81         cur++;

82     }

83     fout << endl;

84 

85     return 0;

86 }

 

你可能感兴趣的:(USACO)