题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251
AC代码:
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<cstring> 5 #include<queue> 6 #include<string> 7 #include<cmath> 8 using namespace std; 9 char ss[1010][1010]; 10 #define MAX 26 11 typedef struct trie 12 { 13 trie *next[MAX]; 14 int v; 15 }; 16 trie root; 17 void creattrie(char *str) 18 { 19 int len = strlen(str); 20 trie *p = &root,*q; 21 for(int i=0;i<len; i++) 22 { 23 int id = str[i] - ‘a‘; 24 if(p->next[id] == NULL) 25 { 26 q=new trie; 27 q->v = 1; 28 for(int j=0; j<MAX; j++) 29 q->next[j] = NULL; 30 p->next[id] = q; 31 p=p->next[id]; 32 } 33 else 34 { 35 //printf("id = %d %d\n",id,p->next[id]->v); 36 p->next[id]->v+=1; 37 //printf("id = %d %d\n",id,p->next[id]->v); 38 p=p->next[id]; 39 } 40 } 41 } 42 int findtrie(char *str) 43 { 44 int i; 45 int len = strlen(str); 46 trie *p = &root; 47 for(i=0;i<len;i++) 48 { 49 //printf("asss\n"); 50 int id = str[i] - ‘a‘; 51 p=p->next[id]; 52 if(p->v == 1) 53 return i+1; 54 } 55 return i; 56 } 57 int main() 58 { 59 int T,n,ans; 60 scanf("%d",&T); 61 while(T--) 62 { 63 ans = 0; 64 for(int i=0;i<MAX;i++) 65 { 66 root.next[i] = NULL; 67 } 68 scanf("%d",&n); 69 70 getchar(); 71 for(int i=0;i<n;i++) 72 { 73 gets(ss[i]); 74 creattrie(ss[i]); 75 } 76 memset(ss,0,sizeof(ss)); 77 for(int i=0;i<n;i++) 78 { 79 int kk = findtrie(ss[i]); 80 //printf("kk = %d\n",kk); 81 ans = ans+kk; 82 } 83 printf("%d\n",ans); 84 } 85 return 0; 86 }
时间: 2024-09-30 06:18:55