跟那个排序二叉树的那个静态树一样,不大习惯静态的,但是不静态会tle,94ms
View Code
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct node { int flag; int next[11]; }trie; int leap,count; trie tr[100010]; new_node() { int i; count++; tr[count].flag = 0; for(i = 0;i < 10;i++) tr[count].next[i] = -1; } int insert(char *s,trie *root ) { int flag,shorts,ct,i; flag = 1; shorts = 1; ct = 0; for(i = 0;s[i] != '\0';i++) { if(root[ct].next[s[i]-'0'] == -1) { new_node(); shorts = 0; root[ct].next[s[i]-'0'] = count; } ct = root[ct].next[s[i]-'0']; if(root[ct].flag) flag = 0; } root[ct].flag = 1; if(shorts) flag = 0; return flag; } int main() { char s[100]; int t,n,flag,i; scanf("%d",&t); while(t--) { count = -1; new_node(); scanf("%d%*c",&n); leap = 1; while(n--) { gets(s); flag = 1; flag = insert(s,tr); if(!flag) leap = 0; } if(leap) puts("YES"); else puts("NO"); } return 0; }
这个是动态的,结果跟某人说的一样,超时。毕竟动态的省空间,静态省时间嘛~
View Code
1 #include<iostream> 2 #include<stdio.h> 3 #include<stdlib.h> 4 #include<string.h> 5 #include<string.h> 6 using namespace std; 7 typedef struct node 8 { 9 int flag; 10 struct node *next[11]; 11 node() 12 { 13 flag = 0; 14 memset(next,NULL,sizeof(next)); 15 } 16 }trie; 17 int leap; 18 19 int insert(char *s,trie *root ) 20 { 21 int i = 0; 22 trie *p; 23 int flag,shorts; 24 flag = 1; 25 shorts = 1; 26 for(i = 0;s[i] != '\0';i++) 27 { 28 if(root->next[s[i]-'0'] == NULL) 29 { 30 root->next[s[i]-'0'] = new node; 31 shorts = 0; 32 } 33 root = root->next[s[i]-'0']; 34 if(root->flag) 35 flag = 0; 36 } 37 root->flag = 1; 38 if(shorts) 39 flag = 0; 40 return flag; 41 } 42 43 int main() 44 { 45 char s[100]; 46 int t,n,flag,i; 47 scanf("%d",&t); 48 while(t--) 49 { 50 trie *root; 51 root = new node; 52 scanf("%d%*c",&n); 53 leap = 1; 54 while(n--) 55 { 56 gets(s); 57 flag = 1; 58 flag = insert(s,root); 59 if(!flag) 60 leap = 0; 61 } 62 if(leap) 63 puts("YES"); 64 else 65 puts("NO"); 66 } 67 68 return 0; 69 }