天天看點

PTA 7-18 新浪微網誌熱門話題

新浪微網誌可以在發言中嵌入“話題”,即将發言中的話題文字寫在一對“#”之間,就可以生成話題連結,點選連結可以看到有多少人在跟自己讨論相同或者相似的話題。新浪微網誌還會随時更新熱門話題清單,并将最熱門的話題放在醒目的位置推薦大家關注。

本題目要求實作一個簡化的熱門話題推薦功能,從大量英文(因為中文分詞處理比較麻煩)微網誌中解析出話題,找出被最多條微網誌提到的話題。

MAP瞎暴

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
map<string, int> vis;
map<string, int> cnt;
map<string, int>::iterator it;
bool judge(char c) {
    if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || '0' <= c && c <= '9' || c == ' ') return true;
    return false;
}
int main() {
    int n; scanf("%d", &n); getchar();
    char str[1000];
    string s;
    for (int i = 1; i <= n; i++) {
        gets(str);
        bool flag = false;
        vis.clear();
        for (int i = 0; str[i]; i++) {
            if (str[i] == '#' && flag == false) {
                s.clear(); flag = true;
            }
            else if (str[i] != '#' && flag == true) {
                if (!judge(str[i])) str[i] = ' ';
                if ('A' <= str[i] && str[i] <= 'Z') str[i] += 32;
                int len = s.size();
                if (len > 0 && str[i] == ' ' && s[len - 1] == ' ') continue;
                s.push_back(str[i]);
            }
            else if (str[i] == '#' && flag == true) {
                string ss;
                if (s[0] == ' ') for (int i = 1; i < s.size(); i++) ss.push_back(s[i]);
                else if (s[s.size() - 1] == ' ') for (int i = 0; i < s.size() - 1; i++) ss.push_back(s[i]);
                else ss = s;
                //cout << ss << endl;
                if (!vis[ss]) {
                    vis[ss] = 1;
                    cnt[ss]++;
                }
                flag = false;
            }
        }
    }
    int num = 0;
    int res = 0;
    string ans;
    for (it = cnt.begin(); it != cnt.end(); it++) {
        string x = it->first; int y = it->second;
        if (y > res) {
            num = 0;
            res = y;
            ans = x;
        }
        else if (y == res) num++;
    }
    ans[0] -= 32;
    cout << ans << endl << res << endl;
    if (num) cout << "And " << num << " more ..." << endl;
}