杭电1251(统计难题)

给出n个单词,然后无数个询问,每次输入一行字符串,求以该字符串为前缀的单词的数量.

#include<algorithm>
#include<iostream>
#include<limits.h>
#include<stdlib.h>
#include<string.h>
#include<cstring>
#include<stdio.h>
#include<bitset>
#include<cctype>
#include<math.h>
#include<string>
#include<time.h>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>

#define LL long long
#define mod 1e9 + 7

using namespace std;

const double PI = acos(-1.0);
const int M = 500005;

struct node
{
    int next[26];
    int cnt;
}tree[M];

int le;

void insert(char *s)
{
    int i = 0, p = 0;
    while(s[i])
    {
        int x = s[i] - 'a';
        if(tree[p].next[x] == -1)
        {
            tree[p].cnt = 0;
            tree[p].next[x] = le++;
        }
        p = tree[p].next[x];
        tree[p].cnt++;
        i++;
    }
}

int query(char *s)
{
    int i = 0, p = 0;
    while(s[i])
    {
        int x = s[i] - 'a';
        if(tree[p].next[x] == -1)
            return 0;
        p = tree[p].next[x];
        i++;
    }
    return tree[p].cnt;
}

int main()
{
    char str[20];
    le = 1;
    memset(tree,-1,sizeof(tree));
    while(gets(str) && strlen(str))
        insert(str);
    while(gets(str))
        cout << query(str) << endl;
    return 0;
}
View Code

 

posted on 2015-03-11 22:32  Unico  阅读(147)  评论(0)    收藏  举报