HDU-1251 统计难题(我就是不用字典树)

统计难题

?戳这里可以前往原题

Problem Description

Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).

Input

输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.

Output

对于每个提问,给出以该字符串为前缀的单词的数量.

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0

分析

这道题用字典树很简单,如果需要字典树的AC代码可以随便去网上找字典树模版,然后稍作修改即可得到答案。
而这道题由于数据量不大(2610~2710其实也蛮大的)所以我就尝试了一下把所有的前缀保存下来,用map解决。然后还真的AC了

既然提到了map,我想也不用过多解释了,直接上代码就行了

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
#include <map>

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);
    
    map<string,int> m;
    string s;
    getline(cin, s);//注意这里不能直接cin,cin会跳过空行,所以就不能进行下面的检测了
    while (s!="")
    {
        string add;
        for (int i=0; i<s.size(); i++)
        {
            add+=s[i];//这里不断的生成前缀,然后加入到map中
            m[add]++;
        }
        getline(cin, s);
    }
    while (cin>>s)
    {
        if (m.count(s)==0)
        {
            cout<<0<<endl;
        }
        else
        {
            cout<<m[s]<<endl;
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/mauve-hkq/p/12173159.html