悬赏 2 关注请教一下 Trie 树为什么 0 分
查看原帖
悬赏 2 关注请教一下 Trie 树为什么 0 分
536439
YONIC楼主2022/10/14 16:48
#include<bits/stdc++.h>
using namespace std;
int t,n,q,tot,trie[(int)(3e6+3)][63],cnt[(int)(3e6+3)],id,g[128];
void insert(string x){
    int u=1;
    for(int i=0;i<x.length();++i){
        if(!trie[u][g[x[i]]]) trie[u][g[x[i]]]=++tot;
        u=trie[u][g[x[i]]];
        ++cnt[u];
    }
}
int find(string x){
    int u=1;
    for(int i=0;i<x.length();++i){
        if(!trie[u][g[x[i]]]) return 0;
        u=trie[u][g[x[i]]];
    }
    return cnt[u];
}
int main(){
    scanf("%d",&t);
    for(int i=48;i<=122;++i) if(isalpha(i)||isdigit(i)) g[i]=id++;
    while(t--){
        scanf("%d%d",&n,&q);
        tot=0;
        memset(trie,0,sizeof(trie));
        memset(cnt,0,sizeof(cnt));
        for(int i=1;i<=n;++i){
            string x;
            cin>>x;
            insert(x);
        }
        for(int i=1;i<=q;++i){
            string x;
            cin>>x;
            printf("%d\n",find(x));
        }
    }
    return 0;
}
2022/10/14 16:48
加载中...