现在的位置: 首页 > 综合 > 正文

hdu1671

2012年07月17日 ⁄ 综合 ⁄ 共 1148字 ⁄ 字号 评论关闭

http://acm.hdu.edu.cn/showproblem.php?pid=1671

给你一些字符串,判断是否某一些字符串是另一些字符串的前缀,设置节点变量visit表示某一字符串,遍历字典树时检查沿途的界定是否具有标记,并检查末字符节点是否有后继字符,记得释放内存

刚才看了牛人的代码,既然是树那么就可以用堆的形式表现出来,访问方便效率也会比较高

1 #include<stdio.h>
2  struct node
3 {
4 node*next[10];
5 int visit;
6 void ini()
7 {
8 visit=0;
9 for(int i=0;i<10;i++)
10 next[i]=NULL;
11 } //节点初始化
12 };
13 int bulid(char *s,node*root)
14 {
15 for(;*s!='\0';s++)
16 {
17 if(root->next[*s-'0']==NULL)
18 {
19 node*p=new node;
20 p->ini();
21 root->next[*s-'0']=p;
22 root=root->next[*s-'0'];
23 }
24 else
25 {
26 root=root->next[*s-'0'];
27 if(root->visit) return 1;
28 } //检查沿途是否有标记
29 }
30 root->visit=1; //标记末字符
31 for(int i=0;i<10;i++)
32 if(root->next[i]!=NULL)
33 return 1; //检查末字符是否有后继字符
34 return 0;
35 }
36 void end(node*root)
37 {
38 for(int i=0;i<10;i++)
39 {
40 if(root->next[i]!=NULL) end(root->next[i]);
41 delete root->next[i];
42 root->next[i]=NULL;
43 }
44 } //释放内存
45 int main()
46 {
47 int sum;
48 scanf("%d",&sum);
49 while(sum--)
50 {
51 int num;
52 scanf("%d",&num);
53 char number[15];
54 int g=0;
55 node*root=new node;
56 root->ini();
57 while(num--)
58 {
59 scanf("%s",number);
60 if(bulid(number,root)) {g=1;break;}
61 }
62 while(g&&num)
63 {
64 scanf("%s",number);
65 num--;
66 }
67 if(g) printf("NO\n");
68 else printf("YES\n");
69 end(root);
70 }
71 return 0;
72 }

抱歉!评论已关闭.