Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 7290 | Accepted: 3054 |
Description
Input
Output
Sample Input
carbohydrate cart carburetor caramel caribou carbonic cartilage carbon carriage carton car carbonate
Sample Output
carbohydrate carboh cart cart carburetor carbu caramel cara caribou cari carbonic carboni cartilage carti carbon carbon carriage carr carton carto car car carbonate carbona
#include<iostream> using namespace std; const int MAX=26; typedef struct TrieNode //结点 { int nCount; //记录该字符出现次数 struct TrieNode *next[MAX]; }TrieNode; TrieNode Memory[1000000]; int allocp=0; void InitTrie(TrieNode **pRoot)//初始化 { *pRoot=NULL; } TrieNode *CreateTrieNode()//创建新结点 { TrieNode *p; p=&Memory[allocp++]; p->nCount=1; for(int i=0;i<MAX;i++) { p->next[i]=NULL; } return p; } //插入 void InsertTrie(TrieNode **pRoot,char s[]) { TrieNode *p; if(!(p=*pRoot)) { p=*pRoot=CreateTrieNode(); } int i=0; while(s[i]) { int k=s[i++]-'a'; if(p->next[k]==NULL) p->next[k]=CreateTrieNode(); else p->next[k]->nCount++; p=p->next[k]; } } int SearchTrie(TrieNode **pRoot,char s[]) { if(*pRoot==NULL) return 0; TrieNode *p=*pRoot; int i=0; while(s[i]) { int k=s[i++]-'a'; if(p->next[k]==NULL) return 0; p=p->next[k]; } return p->nCount; } int SelectPre(TrieNode **pRoot,char s[]) //这道题目变形一下 { TrieNode *p=*pRoot; int i=0; while(s[i]) { int k=s[i++]-'a'; if(p->next[k]->nCount==1) return i; p=p->next[k]; } return i; //返回最后 } int main() { int i,j,n=0; TrieNode *root; InitTrie(&root); char s[1005][25]; while(cin>>s[n]) { InsertTrie(&root,s[n]); n++; } for(i=0;i<n;i++) { j=SelectPre(&root,s[i]); cout<<s[i]<<" "; for(int k=0;k<j;k++) cout<<s[i][k]; cout<<endl; } return 0; }