hdu1671 trie树

题意:给你n个字符串 如果存在某个字符串是另一个字符串的前缀 输出NO否则输出YES

思路:和poj2001很像 代码稍微改改就行, 字典树 如果一个字符串不存在特有前缀,则说明是NO的情况 如果所有字符串都有特有前缀 则是YES的情况

注意: 每次注意释放内存 不然会超时

代码:

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <cstdio>
#include <string>
#include <bitset>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <map>
#include <set>
#define sss(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define mem1(a) memset(a,-1,sizeof(a))
#define mem(a) memset(a,0,sizeof(a))
#define ss(a,b) scanf("%d%d",&a,&b)
#define s(a) scanf("%d",&a)
#define p(a) printf("%d\n", a)
#define INF 0x3f3f3f3f
#define w(a) while(a)
#define PI acos(-1.0)
#define LL long long
#define eps 10E-9
#define N 100000
#define mod 100000000
using namespace std;
void mys(int& res)
{
    int flag=0;
    char ch;
    while(!(((ch=getchar())>='0'&&ch<='9')||ch=='-'))
        if(ch==EOF)  res=INF;
    if(ch=='-')  flag=1;
    else if(ch>='0'&&ch<='9')  res=ch-'0';
    while((ch=getchar())>='0'&&ch<='9')  res=res*10+ch-'0';
    res=flag?-res:res;
}
void myp(int a)
{
    if(a>9)
        myp(a/10);
    putchar(a%10+'0');
}
/*************************THE END OF TEMPLATE************************/
char str[10011][15];
struct node
{
    int sum;
    struct  node *next[10];
    node ()//构造函数 初始化用
    {
        sum=0;
        mem(next);
    }
} ;
node *root = NULL;
void maketree(char *s)
{
    node *p=root;
    node *tmp=NULL;
    for(int i=0; i<strlen(s); i++)
    {
        if(p->next[s[i]-'0']==0)
        {
            tmp=new node ;
            p->next[s[i]-'0']=tmp;
        }
        p=p->next[s[i]-'0'];
        p->sum++;
    }
}
int searchtree(char *s)
{
    node *p=root;
    int cnt = 0;
    for(int i=0; i<strlen(s); i++)
    {
        p=p->next[s[i]-'0'];
        if(p->sum==1)
            break;
       cnt ++;
    }
  // cout<<s<< ":"<<cnt<<endl;
    return cnt;
}
void del(node *rt){
     for(int i=0;i<10;i++){
         if(rt->next[i]!=NULL){
            del(rt->next[i]);
        }
    }
    free(rt);
}
int main()
{
    int n, t;
    s(t);
    w(t--){
        root = new node;
        s(n);
        for(int i=0; i<n; i++){
            cin>>str[i];
            maketree(str[i]);
        }
        bool flag = false;
        for(int i=0; i<n; i++){
            if(strlen(str[i]) == searchtree(str[i])){
               flag = true;
               break;
            }
        }
        if(flag) cout<<"NO"<<endl;
        else cout<<"YES"<<endl;
        del(root);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值