题目传送门: http://acm.hdu.edu.cn/showproblem.php?pid=1251
题意:先给出一堆字符串,然后又给出一堆字符串,问第二堆每个字符串是第一堆字符串中多少个字符串的前缀。
题解:trie树模板题。
代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
typedef struct trie{
trie *Next[30];
int v;
};
void create_tree(char s[],trie *q)
{
int n = strlen(s);
//cout << "n: " << n <<endl;
trie *p;
for(int i=0;i<n;i++){
int id = s[i] - 'a' + 1;
//cout << "id,v : " << id << ' ' << q -> v << endl;
if(q -> Next[id] == NULL){
p = new trie;
for(int i=0;i<30;i++)
p -> Next[i] = NULL;
p -> v = 1;
q -> Next[id] = p;
}
else (q -> Next[id] -> v)++;
q = q -> Next[id];
}
}
int query_tree(char s[],trie *p)
{
int n = strlen(s);
for(int i=0;i<n;i++){
int id = s[i] - 'a'+1;
if(p -> Next[id] != NULL){
//cout << "id,v : " << id << ' ' << p-> Next[id]-> v << endl;
if(i == n-1) return p -> Next[id] -> v;
p = p -> Next[id];
}
else return 0;
}
return 0;
}
void del_tree(trie *p)
{
for(int i=0;i<30;i++){
if(p -> Next[i] != NULL)
del_tree(p -> Next[i]);
}
delete p;
}
int main()
{
char x;
char temp[15];
trie *root;
root = new trie;
for(int i=0;i<30;i++)
root -> Next[i] = NULL;
root -> v = 0;
int cnt = 0;
for(;;){
x = getchar();
if(x != '\n')
temp[cnt++] = x;
else{
if(cnt == 0)
break;
temp[cnt] = 0;
//cout << " tmep:" <<temp <<endl;
create_tree(temp,root);
cnt = 0;
}
}
while(scanf("%s",temp) != EOF){
// cout << "temp : " << temp <<endl;
int cnt = query_tree(temp,root);
printf("%d\n",cnt);
}
del_tree(root);
return 0;
}