字典树模板题,表示很简单,只是看不懂题。。。
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
#define N 100005
char a[N][15];
int n;
int ptr;
struct Node {
int son[27];
int ex;
int num;
int smx;
int smid;
}t[1000000];
int mx;
int mid;
void init(int nn){
memset(t[nn].son, -1, sizeof(t[nn].son));
t[nn].ex = -1;
t[nn].num = 0;
t[nn].smx = 0;
}
void ins(int id, int c, int rt){
if(a[id][c] == '\0'){
t[rt].num ++;
t[rt].ex = id;
return;
}
int nc = a[id][c] - 'a';
if(t[rt].son[nc] == -1){
init(ptr);
t[rt].son[nc] = ptr;
ptr++;
}
int next = t[rt].son[nc];
ins(id, c + 1, next);
if(a[id][c + 1] == '\0'){
if(t[next].num > t[rt].smx){
t[rt].smx = t[next].num;
}
}
else {
if(t[next].smx > t[rt].smx){
t[rt].smx = t[next].smx;
}
}
}
void query(int id, int c, int rt, int len){
if(c >= len){
if(t[rt].ex != -1 && t[rt].num > mx){
mx = t[rt].num;
mid = t[rt].ex;
}
for(int i = 0; i <= 25; i++){
if(t[rt].son[i] != -1 && (t[t[rt].son[i]].smx == t[rt].smx || t[t[rt].son[i]].num == t[rt].smx)){
query(id, c + 1, t[rt].son[i], len);
break;
}
}
return ;
}
if(t[rt].son[a[id][c] - 'a'] != -1)query(id, c + 1, t[rt].son[a[id][c] - 'a'], len);
}
int main(){
ptr = 1;
init(0);
scanf("%d", &n);
for(int i = 0 ; i < n; i++){
scanf("%s", a[i]);
int len = strlen(a[i]);
mx = 0;
mid = i;
query(i, 0, 0, len);
ins(i, 0, 0);
printf("%s\n", a[mid]);
}
return 0;
}