hdu 1251 统计难题 字典树

#include <stdio.h>
#include <string.h>
#define maxn 28
#define inf 500000
int sz;
int ch[inf][maxn],val[inf],sum[inf];
int idx(char c) 
{
    return c-'a';
}
void init() 
{
    sz = 1;
    memset(ch[0], 0, sizeof(ch[0]));
    memset(sum, 0, sizeof(sum));
}

void insert(char *s, int v) 
{
    int u = 0, n = strlen(s);
    for(int i = 0; i < n; i++) 
    {
        int c = idx(s[i]);
        if(!ch[u][c]) 
        {
            memset(ch[sz], 0, sizeof(ch[sz]));
            val[sz] = 0;
            ch[u][c] = sz++;
        }
        u = ch[u][c];
        sum[u]++;
    }
    val[u] = v;
}
int find_prefixes(char *s, int len) 
{
    int u = 0;
    for(int i = 0; i < len; i++) 
    {
        int c = idx(s[i]);
        if(ch[u][c])
            u = ch[u][c];
        else 
            return 0;
    }
    return sum[u];
}

int main()
{
    init();
    int i;
    char ob[15];
    while(1)
    {
        gets(ob);
        if(!strcmp(ob,"")) break;
        insert(ob,1);
    }
    while(scanf("%s",ob)!=EOF)
        printf("%d
",find_prefixes(ob,strlen(ob)));
    return 0;
}



 

原文地址:https://www.cnblogs.com/vermouth/p/3710170.html