字段数模板 HDU1251 统计难题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

题意:先给你一连串字符串作为字典,然后再给你一些字符串,询问在字典中的以这些字符串为前缀的字符串数量有多少

分析:字典树很经典的模板题了,另外,字典树真的非常简单。。。

讲解博客:https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e6+10;
const int inf=0x3f3f3f3f;
typedef long long ll;
#define meminf(a) memset(a,0x3f,sizeof(a))
#define mem0(a) memset(a,0,sizeof(a));
char s[12];
int trie[maxn][26],sum[maxn];
int tot=1;
void insert(char *s,int rt){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';
        if(trie[rt][x]==0) trie[rt][x]=++tot;
        sum[trie[rt][x]]++;//前缀保存 
        rt=trie[rt][x];
    }
}
int search(char *s,int rt){
    for(int i=0;i<s[i];i++){
        int x=s[i]-'a';
        if(trie[rt][x]==0)return 0;
        rt=trie[rt][x];
    }
    return sum[rt]; 
}
int main(){
    int rt=1;//根节点为空,这里我们设根节点为1,也可设为0  
    while(gets(s)){
        if(s[0]=='\0')break;
        insert(s,rt);
    }
    //cout<<233<<endl;
    while(~scanf("%s",s)){
        printf("%d\n",search(s,rt)); 
    }
    return 0;
} 

猜你喜欢

转载自www.cnblogs.com/qingjiuling/p/11372509.html