题目
Description
小A非常喜欢所有押韵的东西,他认为两个单词押韵当且仅当他们的公共后缀的长度和两个单词中最长的单词的长度相等,或者是最长的单词的长度减一。也就是说LCS(A,B)>=max(|A|,|B|)-1。
有一天,小A读了一个有N个单词的小故事,他想知道,如果挑选一些故事里出现的单词组成一个新的单词序列,能组成的最长的满足以下条件的单词序列的长度是多少:单词序列中任意相邻的两个单词都押韵。(每个单词最多只能用一次)
Input
第一行包含一个正整数N(1<=N<=500000),表示单词的个数。
接下来N行,每行一个由英文小写字母构成的单词,表示原故事里的单词。输入保证所有单词都不一样,并且他们的总长度不超过3,000,000。
Output
输出满足条件的最长单词序列的长度。
Sample Input
输入1:
4
honi
toni
oni
ovi
输入2:
5
k
ask
psk
krafna
sk
输入3:
5
pas
kompas
stas
s
nemarime
Sample Output
输出1:
3
输出2:
4
输出3:
1
Data Constraint
有30%的数据,有N<=18。
题解
首先这题要求的东西有关最长公共后缀,所以我们考虑先把字符串反过来,那就变成前缀了。
然后我们可以有一个trie来保存字符串,并在每一个字符串的末尾打上一个标记
然后就可以开始dp了,我们注意到dp的转移有三种,父亲,儿子,父亲的其他儿子都可以转移。
所以我们就依据此进行转移就好了
贴代码
var
a:array[0..2000005,'a'..'z']of longint;
b,f:array[0..2000005]of longint;
i,j,k,l,n,m,x,y,z,ans,tot:longint;
s,s1:array[0..500005]of char;
ch,cc:char;
procedure dfs(x:longint);
var
ch:char;
tt1,tt2,t1,t2:longint;
begin
//f[x]:=b[x];
for ch:='a' to 'z' do
if a[x,ch]<>0 then
dfs(a[x,ch]);
//if b[x]=0 then exit;
tot:=b[x];
tt1:=0; tt2:=0;
t1:=0; t2:=0;
if x=17 then
begin
x:=x;
end;
for ch:='a' to 'z' do
if f[a[x,ch]]>tt1 then
begin
tt2:=tt1; t2:=t1;
tt1:=f[a[x,ch]];
f[x]:=f[a[x,ch]];
t1:=a[x,ch];
end else
if f[a[x,ch]]>tt2 then
begin
tt2:=f[a[x,ch]];
t2:=a[x,ch];
end;
f[x]:=f[x]+b[x];
tot:=tot+tt1+tt2;
if tot>1 then
begin
tot:=tot;
end;
for ch:='a' to 'z' do
if a[x,ch]<>t1 then
begin
if a[x,ch]<>t2 then
tot:=tot+b[a[x,ch]];
f[x]:=f[x]+b[a[x,ch]];
end;
if b[x]=0 then f[x]:=0;
if tot>ans then ans:=tot;
end;
begin
assign(input,'rhyme.in'); reset(input);
assign(output,'rhyme.out'); rewrite(output);
readln(n);
z:=1;
for i:=1 to n do
begin
x:=0;
while not eoln do
begin
inc(x);
read(s[x]);
end;
readln;
for j:=1 to x do s1[x-j+1]:=s[j];
y:=1;
for j:=1 to x do
begin
if a[y,s1[j]]=0 then
begin
inc(z);
a[y,s1[j]]:=z;
y:=z;
end else y:=a[y,s1[j]];
if j=x then b[y]:=1;
end;
end;
dfs(1);
writeln(ans);
close(input);
end.