您的位置:首页 > 其它

poj3630—Phone List(字典树)

2017-08-27 00:11 351 查看
传送门:点我
Sample Input
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346

Sample Output
NO
YES

题意:给出一些字符串,判断是否有字符串是另一个字符串的前缀
字典树算法详解:http://blog.csdn.net/piaocoder/article/details/47836559

动态会超时,只能静态建树(188ms)

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 100009
int flag1,cnt;
struct TrieNode
{
int flag;
TrieNode* Next[10];
} node
;
char s
[13];
TrieNode* NewNode()
{
memset(&node[cnt],0,sizeof(TrieNode));
return &node[cnt++];
}
int cmp(const void* a,const void* b)//字符串字典序排序
{
return strcmp((char*)a,(char*)b);
}
void Insert(char* s,TrieNode* p)
{
if(flag1==1)
return;
int len=strlen(s);
for(int i=0; i<len; i++)
{
int j=s[i]-'0';
if(p->Next[j]==NULL)
p->Next[j]=NewNode();
if(p->flag==1)
{
flag1=1;
return ;
}
p=p->Next[j];
}
p->flag=1;
}
int main()
{
int t,n,i;
cin>>t;
while(t--)
{
flag1=0;
cnt=0;
scanf("%d",&n);
TrieNode* root=NewNode();
for(i=0; i<n; i++)
scanf("%s",s[i]);
qsort(s,n,sizeof(s[0]),cmp);//字符串字典序排序
for(i=0; i<n; i++)
Insert(s[i],root);
printf("%s\n",flag1?"NO":"YES");
}
return 0;
}

排序水过(313ms):
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string>
#define N 10010
using namespace std;
string tel
;
bool judge(int n)
{
int i,k,len;
for(k=0;k<n-1;k++)
{
len=tel[k].size();//<tel[k+1].size()?tel[k].size():tel[k+1].size();
for(i=0;i<len;i++)
if(tel[k][i]!=tel[k+1][i])
break;
if(i==len) return true;
}
return false;
}
int main()
{
int t,i,n;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(i=0;i<n;i++) cin>>tel[i];
sort(tel,tel+n);
if(judge(n)) printf("NO\n");
else printf("YES\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: