HDU - 1251 - 统计难题(字典树)

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1251

题解:

字典树

AC代码:

#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxnode = 500000;
const int sigma   = 26;
int ch[maxnode][sigma],v[maxnode],sz;
int u;
struct trie
{
    trie()
    {
        sz=1;
        memset(v,0,sizeof v);
        memset(ch[0],0,sizeof ch[0]);
    }
    int idx(char c)
    {
        return c-'a';
    }
    void insert(char* s)
    {
        int l =strlen(s);
        u=0;
        for(int i=0;iint c = idx(s[i]);
            if(!ch[u][c])
            {
                memset(ch[sz],0,sizeof ch[sz]);
                ch[u][c] = sz++;
                //cout << ch[u][c] <
            }
            u = ch[u][c];
            v[u] ++;
        }
    }
    int query(char *s)
    {
        int l=strlen(s);
        u=0;
        int ans = 0;
        for(int i=0;iint c = idx(s[i]);
            if(!ch[u][c])
                return 0;
            u = ch[u][c];
            if(i == l - 1)
                ans = v[u];
        }
        return ans;
    }
}T;

int n,m;
char c[15];

int main()
{
    gets(c);
    while(c[0] != '\0')
    {
        T.insert(c);
        gets(c);
    }
    while(scanf("%s",c) != EOF)
    {
        printf("%d\n" , T.query(c));
    }
    return 0;
}

你可能感兴趣的:(ACM之路,字符串算法:字典树,kmp,manacher)