首页 > 代码库 > POJ 3630 Phone List

POJ 3630 Phone List

Trie树。


题意是问某个数字可不可能是其他数字的前缀。

就是裸的字典树。排序然后插进去就好了。


#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<stack>
#include<iostream>
#include<list>
#include<set>
#include<cmath>
#define INF 0x7fffffff
#define eps 1e-6
#define LL long long
using namespace std;
struct Trie
{
    int word[100001][10];
    int sz,cot;
    int ex[1000010];
    void intTrie()
    {
        sz=1;
        cot=1;
        memset(word[0],0,sizeof(word[0]));
        ex[0]=0;
    }
    int insert(char *s)
    {
        int u=0,c,len=strlen(s);
        int ans=0;
        for(int i=0; i<len; i++)
        {
            c=s[i]-'0';
            if(!word[u][c])
            {
                memset(word[sz],0,sizeof(word[sz]));
                ex[sz]=0;
                word[u][c]=sz++;
            }
            u=word[u][c];
            ans+=ex[u];
        }
        if(ex[u]==0)ex[u]=1;
        return ans;
    }
}wo;
struct lx
{
    char str[11];
}l[10001];
bool cmp(lx a,lx b)
{
    return strcmp(a.str,b.str)<0;
}
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        wo.intTrie();
        scanf("%d",&n);
        bool flag=0;
        for(int i=0;i<n;i++)
            scanf("%s",l[i].str);
        sort(l,l+n,cmp);
        for(int i=0;i<n;i++)
        {
            int ans=wo.insert(l[i].str);
            if(ans>0)
            {
                flag=1;break;
            }
        }
        if(flag)puts("NO");
        else puts("YES");
    }
}