您的位置:首页 > 其它

Trie树 hiho一下第2周

2017-10-17 21:14 309 查看
**题意:**trie树的实现题。

思路:实现 trie 树就好。

代码:

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;

const int sigma_size = 30;
const int maxnode = 1000010;

int ch[maxnode][sigma_size];
int val[maxnode];
int cnt[maxnode];
int sz;
int N, M;

void Init()
{
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(cnt, 0, sizeof(cnt));
}

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

void Insert(char *s)
{
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];
cnt[u]++;
}
val[u] = 1;
}

int Find(char *s)
{
int u = 0, n = strlen(s);
for(int i=0; i<n; i++){
int c = idx(s[i]);
if(!ch[u][c]){
return 0;
}
u = ch[u][c];
}
return cnt[u];
}

int main()
{
//freopen("in.txt", "r", stdin);
Init();
scanf("%d", &N);
char c[15];
for(int i=0; i<N; i++){
scanf("%s", c);
Insert(c);
}

scanf("%d", &M);
for(int i=0; i<M; i++){
scanf("%s", c);
int ans = Find(c);
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  trie acm