Tang-Dreamoon's Blog

poj 3630

Trie树模板题目(包含正常模板)

  题目链接:poj 3630

  题意:给定若干字符串,判断是否存在一个字符串是另一个字符串的前缀。

  题解:水题直接上 Trie 树。

  我思故我在:记着清空数组!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
int love=0;
char ap[30];
int map[100100][11];
bool ac[100100];
bool work(int x)
{
int now=0;
for(int i=1;i<=x;i++)
{
int y=ap[i]-'0';
if(map[now][y]!=0)
{
if(ac[map[now][y]]) return true;
else now=map[now][y];
}
else
{
map[now][y]=++love;
now=map[now][y];
}
}
ac[now]=1;
for(int i=0;i<=10;i++)
{
if(map[now][i]!=0) return true;
}
return false;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
bool flag=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%s",ap+1);
if(work(strlen(ap+1))) flag=1;
}
if(flag) puts("NO");
else puts("YES");
memset(ac,0,sizeof(ac));
memset(map,0,sizeof(map));
love=0;
}
return 0;
}