您的位置:首页 > 其它

hdu 1251 统计难题 trie

2015-10-04 16:05 453 查看
[code]#include<bits/stdc++.h>
using namespace std;
int ch[500000][26],sz,val[500000];

int idx(char x)
{
    return x-'a';
}

void trie(char *s)
{
    int u=0,c,i,len=strlen(s);
    for(i=0;i<len;i++)
    {
        c=idx(s[i]);
        if(ch[u][c]==0)
        {
            ch[u][c]=sz;
            sz++;
        }
        u=ch[u][c];
        val[u]++;
    }
}

int main()
{
    char s[20];
    int ans,i,len,u,c;
    sz=1;
    memset(val,0,sizeof(val));
    memset(ch,0,sizeof(ch));
    while(gets(s))
    {
        if(strlen(s)==0) break;
        trie(s);
    }
    while(gets(s))
    {
        ans=0;
        len=strlen(s);
        u=0;
        for(i=0;i<len;i++)
        {
            c=idx(s[i]);
            if(ch[u][c]==0) break;
            u=ch[u][c];
        }
        if(i==len) ans=val[u];
        printf("%d\n",ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: