#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> using namespace std; const int M = 26; int n; #define maxn 1005 char S[maxn][21]; struct Node { int v; Node *next[M]; }*root; void Creat(char *s) //分配内存最好使用calloc 因为会进行初始化 而malloc不初始化 都是随机的数据垃圾 { int len = strlen(s); Node *p = root, *q; for(int i=0; i<len; i++) { int id = s[i] - 'a'; //cout<<id<<" "; if(p->next[id] == NULL) { q = (Node *)calloc(1, sizeof(Node)); q->v = 1; p->next[id] = q; p = q; } else { p = p->next[id]; p->v++; } } } void Find(char *s) { int len = strlen(s); Node *p = root; for(int i=0; i<len; i++) { int id = s[i] - 'a'; p = p->next[id]; printf("%c", s[i]); if(p->v == 1) break; } cout<<endl; } int main() { n = 0; root = (Node *)calloc(1, sizeof(Node)); // 根节点 //root = new Node; while(~scanf("%s", S[n])) { Creat(S[n++]); } for(int i=0; i<n; i++) { printf("%s ", S[i]); Find(S[i]); } return 0; }
时间: 2024-10-23 04:39:03