题意:给你n个字符串(n<=1e3),求每个字符串的非公共前缀,如果不存在就输出本身。
思路:字典树中的val记录前缀数量,如果val==1就说明只有这个字符串本身有这前缀,也就是答案。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 27;
const int maxnode = 20*1000+5;
int ch[maxnode][maxn], val[maxnode], sz;
char str[1005][maxn];
void init()
{
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
}
void Insert(char *s)
{
int u = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(ch[u][s[i]-'a'] == 0)
{
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;
ch[u][s[i]-'a'] = sz++;
}
u = ch[u][s[i]-'a'];
val[u]++;
}
}
void Match(char *s)
{
int u = 0;
int len = strlen(s);
for(int i = 0; i < len; i++)
{
if(val[ch[u][s[i]-'a']] == 1)
{
printf("%s ", s);
for(int j = 0; j <= i; j++)
printf("%c", s[j]);
printf("\n");
return ;
}
u = ch[u][s[i]-'a'];
}
printf("%s %s\n", s, s);
}
int main(void)
{
int cnt = 0;
init();
while(gets(str[cnt]) != NULL)
{
Insert(str[cnt]);
cnt++;
}
for(int i = 0; i < cnt; i++)
Match(str[i]);
return 0;
}