POJ 3630 Phone List

来源:互联网 发布:江苏省软件行业协会 编辑:程序博客网 时间:2024/05/19 04:52

题意:给你许多电话号码,判断其中是否有号码是其它号码的前缀,有输出NO,没有输出YES.

思路:可以用qsort做,先对号码(按字符串输入)排序,然后判断。

           我是用trie树解的,最好开静态数组开辟空间,不然很容易超时。

 

#include<cstdio>#include<iostream>#include<cstdlib>using namespace std;#define Max_Child 10int flag;typedef struct trie_node{   int count;   struct trie_node *child[Max_Child];}node, *Tree;node num[400080];int x;node *diction;node *InitTree(){    node *p=num+x++;for(int i=0;i<Max_Child;i++){    p->child[i]=NULL;}p->count=0;return p;}void insert_node(char *str){   if(str==NULL) return;   node *t=diction;   char *p=str;      while(*p!=0)   {   if(*(p+1)==0&&t->child[*p-'0']!=NULL) {flag=1;break;}   if(t->count==1){flag=1;break;}        if(NULL==t->child[*p-'0']&&t->count!=1) {    node *temp=InitTree();  t->child[*p-'0']=temp; }   t=t->child[*p-'0'];  p++;   }      t->count=1;}int main(){  int c,n,i;  char str[11];  scanf("%d",&c);  while(c--)  {  flag=0;x=0;  diction=InitTree();     scanf("%d",&n); for(i=0;i<n;i++) {    scanf("%s",str);if(!flag){   insert_node(str);  } } if(flag) printf("NO\n"); else printf("YES\n");  }   return 0;}


 

 

原创粉丝点击