PTA数据结构与算法题目集(中文): 7-46 新浪微博热门话题 (30分)
新浪微博可以在发言中嵌入“话题”,即将发言中的话题文字写在一对“#”之间,就可以生成话题链接,点击链接可以看到有多少人在跟自己讨论相同或者相似的话题。新浪微博还会随时更新热门话题列表,并将最热门的话题放在醒目的位置推荐大家关注。
本题目要求实现一个简化的热门话题推荐功能,从大量英文(因为中文分词处理比较麻烦)微博中解析出话题,找出被最多条微博提到的话题。
输入格式:
输入说明:输入首先给出一个正整数N(≤105),随后N行,每行给出一条英文微博,其长度不超过140个字符。任何包含在一对最近的#
中的内容均被认为是一个话题,输入保证#
成对出现。
输出格式:
第一行输出被最多条微博提到的话题,第二行输出其被提到的微博条数。如果这样的话题不唯一,则输出按字母序最小的话题,并在第三行输出And k more ...
,其中k
是另外几条热门话题的条数。输入保证至少存在一条话题。
注意:两条话题被认为是相同的,如果在去掉所有非英文字母和数字的符号、并忽略大小写区别后,它们是相同的字符串;同时它们有完全相同的分词。输出时除首字母大写外,只保留小写英文字母和数字,并用一个空格分隔原文中的单词。
输入样例:
1 2 3 4 5
| 4 This is a #test of topic#. Another #Test of topic.# This is a #Hot# #Hot# topic Another #hot!# #Hot# topic
|
输出样例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #include <bits/stdc++.h> using namespace std; struct node { int cnt; string topic; }; bool cmp(node &a, node &b) { return a.cnt != b.cnt ? a.cnt > b.cnt : a.topic < b.topic; } string parse(string s, string &outputTopic) { string ans, it; for (int i = 0; i < s.length(); i++) { if (isalnum(s[i])) it += s[i]; if (!isalnum(s[i]) || i == s.length() - 1) { if (it != "") { for (int j = 0; j < it.length(); j++) { ans += tolower(it[j]); outputTopic += tolower(it[j]); } outputTopic += ' '; it = ""; } } } outputTopic[0] = toupper(outputTopic[0]); outputTopic.erase(outputTopic.end() - 1); return ans; } int main() { int n, k = 0; string s; scanf("%d", &n); unordered_map<string, int> cnt; getchar(); for (int i = 0; i < n; i++) { getline(cin, s); unordered_map<string, bool> exist; bool flag = false; int start = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '#') { if (flag) { string originalTopic = s.substr(start, i - start), outputTopic; string lowerTopic = parse(originalTopic, outputTopic); if (!exist[lowerTopic]) { exist[lowerTopic] = true; cnt[outputTopic]++; } flag = false; continue; } start = i + 1; flag = true; } } } vector<node> ans; for (auto it : cnt) ans.push_back({it.second, it.first}); sort(ans.begin(), ans.end(), cmp); printf("%s\n%d\n", ans[0].topic.c_str(), ans[0].cnt); for (int i = 1; i < ans.size(); i++) { if (ans[i].cnt != ans[0].cnt) break; k++; } if (k != 0) printf("And %d more ...", k); return 0; }
|