POJ 3630 Phone List | Trie 树

题目:

给定 n 个长度不超过 10 的数字串,问其中是否存在两个数字串 S, T ,使得 S 是 T 的前
缀。多组数据,数据组数不超过 40.


题解:

前缀问题一般都用Trie树解决:

所以跑一个Tire树,记录一下每个节点是不是结尾就好

#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 100010
#define Z 10
using namespace std;
int T,n,tot;
struct node
{
    int trans[Z],bo;
    void clear()
	{
	    memset(trans,0,sizeof(trans));
	    bo=0;
	}
}tr[N];
char s[20];
int insert(char *s)
{
    int len=strlen(s),u=1,flag=0;
    for (int i=0;i<len;i++)
    {
	if (!tr[u].trans[s[i]-'0'])
	    tr[tr[u].trans[s[i]-'0']=++tot].clear();
	else if (i==len-1)
	    flag=1;
	u=tr[u].trans[s[i]-'0'];
	if (tr[u].bo) flag=1;
    }
    tr[u].bo=1;
    return flag;
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
	scanf("%d",&n);
	tr[tot=1].clear();
	int ans=0;
	for (int i=1;i<=n;i++)
	{
	    scanf("%s",s);
	    if (insert(s)) ans=1;
	}
	if (!ans) puts("YES");
	else puts("NO");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/mrsheep/p/7977107.html