题目链接:http://acm.pku.edu.cn/JudgeOnline/problem?id=2001 题目大意:给出一系列单词,求每个单词的最小前缀 题目分析:简单的Trie树。 AC代码: /********************** * * * Author:surpasser * * Date: * * Problem:Shortest * * Prefixes * * * **********************/ #include<cstdio> #include<string> #include<cmath> #include<algorithm> using namespace std; const int MAXN = 20010; const int MAXM = 1001; typedef struct node{ int num; node *next[26]; node(){ num=0; memset(next,0,sizeof(next)); } }*Trie; node trie[MAXN]; char word[MAXM][21]; int num; Trie root; void Insert(char *str) { int i; if(root==NULL) { root = &trie[0]; //sizeof(root->next,NULL,sizeof(root->next)); } Trie now=root; while(*str) { i=*str-'a'; str++; if(now->next[i]==NULL) { now->next[i]=&trie[num]; num++; } now = now->next[i]; now->num++; //sizeof(now->next,NULL,sizeof(now->next)); } } void Find(char *str) { int i; Trie now=root; //if(now==NULL) printf("0/n"); //else printf("1/n"); while(*str) { printf("%c",*str); i=*str-'a'; str++; now=now->next[i]; if(now->num==1) break; } printf("/n"); } int main() { freopen("input.in","r",stdin); int cnt=0; num=1; int i; // char tmp[20]; root=NULL; while(scanf("%s",word[cnt])!=EOF) { Insert(word[cnt]); cnt++; } for(i=0;i<cnt;i++) { printf("%s ",word[i]); Find(word[i]); //if(i!=cnt-1) //printf("/n"); } return 0; }