POJ 3630 Trie

链接:

http://poj.org/problem?id=3630

题意:

给你n个字符串,判断有没有字符串是其他字符串的前缀

题解:

建一个字典树,在插入的过程中,如果没有新建一个结点,那这个字符串肯定是其他字符串的前缀,

如果新建结点的时候发现,有的字符串以这个字符结尾,那肯定有字符串是这个字符串的前缀

代码:

31 int pi = 1;
32 int fg;
33 
34 struct Node {
35     int next[10];
36     bool end;
37 }tree[MAXN];
38 
39 void insert(string keyword) {
40     int index, p, i;
41     int flag = 0;
42     for (i = p = 0; keyword[i]; i++) {
43         index = keyword[i] - '0';
44         if (tree[p].next[index] == 0) {
45             tree[p].next[index] = pi++;
46             flag = 1;
47             if (tree[p].end) fg = 0;
48         }
49         p = tree[p].next[index];
50     }
51     if (!flag) fg = 0;
52     tree[p].end = 1;
53 }
54 
55 int main() {
56     int T;
57     cin >> T;
58     while (T--) {
59         pi = 1;
60         fg = 1;
61         memset(tree, 0, sizeof(tree));
62         int n;
63         cin >> n;
64         while (n--) {
65             string s;
66             cin >> s;
67             insert(s);
68         }
69         if (fg) cout << "YES" << endl;
70         else cout << "NO" << endl;
71     }
72     return 0;
73 }

 

转载于:https://www.cnblogs.com/baocong/p/6790314.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值