7-46 新浪微博热门话题 (30 分)
新浪微博可以在发言中嵌入“话题”,即将发言中的话题文字写在一对“#”之间,就可以生成话题链接,点击链接可以看到有多少人在跟自己讨论相同或者相似的话题。新浪微博还会随时更新热门话题列表,并将最热门的话题放在醒目的位置推荐大家关注。
本题目要求实现一个简化的热门话题推荐功能,从大量英文(因为中文分词处理比较麻烦)微博中解析出话题,找出被最多条微博提到的话题。
输入格式:
输入说明:输入首先给出一个正整数N(≤105),随后N行,每行给出一条英文微博,其长度不超过140个字符。任何包含在一对最近的#
中的内容均被认为是一个话题,输入保证#
成对出现。
输出格式:
第一行输出被最多条微博提到的话题,第二行输出其被提到的微博条数。如果这样的话题不唯一,则输出按字母序最小的话题,并在第三行输出And k more ...
,其中k
是另外几条热门话题的条数。输入保证至少存在一条话题。
注意:两条话题被认为是相同的,如果在去掉所有非英文字母和数字的符号、并忽略大小写区别后,它们是相同的字符串;同时它们有完全相同的分词。输出时除首字母大写外,只保留小写英文字母和数字,并用一个空格分隔原文中的单词。
输入样例:
4
This is a #test of topic#.
Another #Test of topic.#
This is a #Hot# #Hot# topic
Another #hot!# #Hot# topic
输出样例:
Hot
2
And 1 more ...
注意:
分隔(易误):"#a ! b#" 和"a@&b"的话题都为 "a b",思路是特殊符号替换为空格,多个空格进行合并
首尾不能有空格
#include<iostream>
#include<map>
#include<string>
using namespace std;
struct Topic {
int n; //话题出现次数
bool used = false; //判断是否在一条微博提到过这个话题
};
int main(){
int n, count = 0;
string str;
char ch;
pair<string, Topic> hot; //记录最热话题
map<string, Topic> result; //记录所有话题
cin >> n;
getchar();
for (int i = 0; i < n; ++i) {
while ((ch = getchar()) != '\n') {
if (ch == '#') {
str.clear();
while (true) {
ch = getchar();
if (ch == '#' || ch == '\n')
break;
else if (isdigit(ch) || isalpha(ch))
str.push_back(tolower(ch));
else if (!str.empty() && str.back() != ' ') //添加分隔符
str.push_back(' ');
}
if (str.back() == ' ')str.pop_back(); //去除尾部空格
str[0] = toupper(str[0]); //首字母大写
if (!result[str].used) { //话题计数
result[str].n++;
result[str].used = true;
if (result[str].n == hot.second.n) { //相同更新并列个数
count++;
if (str < hot.first) //根据字符字典序更新最热话题
hot.first = str;
}
else if (result[str].n > hot.second.n) { //更新最热话题
count = 0; //重置并列个数
hot = { str,result[str] };
}
}
}
}
for (auto& it : result) //重置
it.second.used = false;
}
cout << hot.first << endl << hot.second.n << endl;
if (count)
cout << "And " << count << " more ..." << endl;
return 0;
}