【NOI2017模拟4.2】押韵

该博客介绍了如何利用Trie数据结构解决NOI2017模拟赛中的押韵问题。题目要求找到故事中单词序列的最长押韵子序列,每个单词最多使用一次。博客提供了输入输出示例,并详细解释了将问题转化为求最长公共前缀的过程,以及如何通过Trie和动态规划进行求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值