POJ 3630 Phone List

题目链接:http://poj.org/problem?id=3630


题意:给一些字符串,问这些字符串是否存在一个字符串是另一个字符串前缀的情况。


思路:trie树解决字符串前缀问题。
我们把每个单词x加入trie树的时候考虑两种情况:
(1) 是否存在已加进去的单词y是x的前缀。
(2) 是否存在已加进去的单词y,x是y的前缀。
我们对每个单词的结尾字母节点进行标记。

对于(1),我们每次到达一个字母节点,去看看这个节点有没有被标记过。

对于(2),我们在当前单词的最后一个字母节点处,先看这个节点之前有没有被访问过,再对这个节点进行操作。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>


using namespace std;

#define rep(i,j,k) for(int i = j; i <= k; i++ )
#define Rrep(i,j,k) for(int i = j; i >= k; i-- )
#define Clean(x,y) memset(x,y,sizeof(x))

const int maxn = 10;


struct trie
{
    int next[100009][maxn];
    bool end[100009];
    int len;
    int root;
    bool insert(char s[])
    {
        int len = strlen(s);
        int now = root;
        rep(i,0,len-1)
        {
            int index = s[i] - '0';
            if ( i == len-1 && next[now][index] ) return false;
            if ( !next[now][index] )
            {
                next[now][index] = newnode();
            }
            now = next[now][index];
            if ( end[now] ) return false;
        }
        return end[now] = true;
    }

    int newnode()
    {
        return len++;
    }
    void clear()
    {
        len = 0;
        root = newnode();
        Clean(next,0);
        Clean(end,false);
    }
}a;

char str[10009][12];
int T,n;

int main()
{
    cin>>T;
    while(T--)
    {
        a.clear();
        cin>>n;
        getchar();
        bool can = true;
        rep(i,1,n)
        {
            gets(str[i]);
            if ( can )
            {
                can = a.insert( str[i] );
            }
        }
        puts(can?"YES":"NO");
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值