#include<cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; #define num(x) x-'a'; #define MAX 1000000 struct Trie{ int next[26]; int count; int prefix;//记录以此为前缀串的数量 }tree[MAX]; char suffix[15];//后缀 int f,length; int dfs(int depth,int node){//查找出现次数最多的串,返回以此出发串出现频率最大值 int best=0,sel; if(tree[node].count&&(tree[node].count>f)){ f=tree[node].count; length=depth; best=f; } for(int i=0;i<26;i++){ int j=tree[node].next[i]; if(j&&tree[j].prefix>f){//摆脱TLE的重要剪枝 int t=dfs(depth+1,tree[node].next[i]); if(best<t){ best=t; sel=i; } } } if(best==f){ suffix[depth]=(char)(sel+'a'); } return best; } int insert(char *s){ int len=strlen(s),node=0; static int next=0; if(next==0){ memset(&tree[0],0,sizeof(Trie)); } for(int i=0;i<len;i++){ int c=num(s[i]); if(!tree[node].next[c]){ memset(&tree[++next],0,sizeof(Trie)); tree[node].next[c]=next; } node=tree[node].next[c]; tree[node].prefix++; } return ++tree[node].count; } void search(char *s){ int node=0,len=strlen(s); for(int i=0;i<len;i++){ int c=num(s[i]); if(!tree[node].next[c]){ printf("%s ",s); return; } node=tree[node].next[c]; } printf("%s",s); length=f=0; dfs(0,node);//深搜找后缀 for(int i=0;i<length;i++){ printf("%c",suffix[i]); } printf(" "); } int main(){ int t; char str[12]; scanf("%d",&t); while(t--){ scanf("%s",str); search(str); insert(str); } return 0; }