trie树

题:http://hihocoder.com/problemset/problem/1014

#include
using namespace std;
#define pb push_back
typedef long long ll;
const int M=1e6+5;
int g[M][30],sz[M];
char s[M];
void dfs(int u){
    for(int i=0;i<26;i++)
        if(g[u][i]){
            dfs(g[u][i]);
            sz[u]+=sz[g[u][i]];
        }
}
int main(){
    int n;
    scanf("%d",&n);
    int tot=1;
    for(int i=1;i<=n;i++){
        scanf("%s",s);
        int len=strlen(s);
        int fir=1;
        for(int j=0;j){
            if(!g[fir][s[j]-'a'])
                g[fir][s[j]-'a']=++tot;
            fir=g[fir][s[j]-'a'];        
        }
        sz[fir]++;
    }
    dfs(1);
    int m;
    scanf("%d",&m);
    while(m--){
        scanf("%s",&s);
        int fir=1;
        int len=strlen(s);
        int ans=0;
        for(int j=0;j){
            if(!g[fir][s[j]-'a']){
                ans=0;
                break;
            }    
            fir=g[fir][s[j]-'a'];
            ans=sz[fir];
        }
        
        printf("%d\n",ans);
    }
    return 0;
}
View Code

 

你可能感兴趣的:(trie树)