Frequent Terms
Frequency Counting of Words / Top N words in a document.
Given N terms, your task is to find the k most frequent terms from given N terms.
Input format :
First line of input contains N, denoting the number of terms to add.
In each of the next N lines, each contains a term.
Next line contains k, most frequent terms.
Output format :
Print the k most frequent terms in descending order of their frequency. If two terms have same frequency print them in lexicographical order.
Sample input :
14
Fee
Fi
Fo
Fum
Fee
Fo
Fee
Fee
Fo
Fi
Fi
Fo
Fum
Fee
3
Sample output :
Fee
Fo
Fi
Constraint :
0 < N < 300000
0 < term length < 25.
比较函数不要引用。
1 #include <iostream> 2 #include <algorithm> 3 #include <string> 4 using namespace std; 5 6 struct Node 7 { 8 string name; 9 int count; 10 }; 11 12 string strs[300001]; 13 Node items[300001]; 14 int GetCounts(int &num) 15 { 16 if(num <= 0) return false; 17 sort(strs, strs+num); 18 string tempStr = strs[0]; 19 int counts = 0; 20 int i,j; 21 for(j = i = 0; i < num; ++i, ++counts) 22 { 23 if(strs[i] != tempStr) 24 { 25 items[j].count = counts; 26 items[j].name = tempStr; 27 tempStr = strs[i]; 28 counts = 0; 29 j++; 30 } 31 } 32 items[j].name = tempStr; 33 items[j].count = counts; 34 return j+1; 35 } 36 bool compareNode(const Node a, const Node b) 37 { 38 if(a.count == b.count) 39 return a.name <= b.name; 40 return a.count > b.count; 41 } 42 bool GetAnswer(int num) 43 { 44 int k; 45 cin >> k; 46 sort(items,items+num, compareNode); 47 for(int i = 0;i < k; i++) 48 cout << items[i].name << endl; 49 return true; 50 } 51 int main() 52 { 53 int num; 54 while(cin >> num) 55 { 56 for(int i = 0; i < num; ++i) 57 cin >> strs[i]; 58 int uniqueNum = GetCounts(num); 59 GetAnswer(uniqueNum); 60 } 61 return 0; 62 }