洛谷 P2516 [HAOI2010]最长公共子序列

25 篇文章 0 订阅

洛谷 P2516 [HAOI2010]最长公共子序列


题目

题目描述

字符序列的子序列是指从给定字符序列中随意地(不一定连续)去掉若干个字符(可能一个也不去掉)后所形成的字符序列。令给定的字符序列X=“x0,x1,…,xm-1”,序列Y=“y0,y1,…,yk-1”是X的子序列,存在X的一个严格递增下标序列

ABCBDAB.
BACBBD.

输出样例#1:

4
7

题解

DP

f[i][j]表示两个字符串分别以i、j结尾时的最长公共子串的长度
r[i][j]表示两个字符串分别以i、j结尾时的最长公共子串的数量

很显然,f[i][j]就是由f[i-1][j]、f[i][j-1]、f[i-1][j-1]推过来的,所以只需要记住f[i-1][0~m-1]的状态就可已推出f[i][1~m]的状态


代码

#include<iostream>
#include<cstdio>
#include<cstring>
#define tt 100000000
using namespace std;

int n,m,now,pre;
int f[2][5005],r[2][5005];
char s1[5005],s2[5005];

int main()
{    
    scanf("%s",s1+1);n=strlen(s1+1)-1;
    scanf("%s",s2+1);m=strlen(s2+1)-1;
    for(int k=0;k<=m;k++) r[0][k]=1; 
    r[1][0]=1;now=1;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            f[now][j]=max(f[pre][j],f[now][j-1]);
            r[now][j]=0;
            if (s1[i]==s2[j]) f[now][j]=max(f[now][j],f[pre][j-1]+1); 
            if (s1[i]==s2[j]&&f[now][j]==f[pre][j-1]+1) r[now][j]+=r[pre][j-1];
            if (f[pre][j]==f[now][j]) r[now][j]+=r[pre][j];
            if (f[now][j-1]==f[now][j]) r[now][j]+=r[now][j-1];
            if (f[pre][j-1]==f[now][j]) r[now][j]-=r[pre][j-1];
            r[now][j]=(r[now][j]+tt)%tt;
        }
        now=pre;pre=(pre+1)%2;
    }
    printf("%d\n%d",f[pre][m],r[pre][m]);
    return 0;
}
这道题目还可以使用树状数组或线段树来实现,时间复杂度也为 $\mathcal{O}(n\log n)$。这里给出使用树状数组的实现代码。 解题思路: 1. 读入数据; 2. 将原数列离散化,得到一个新的数列 b; 3. 从右往左依次将 b 数列中的元素插入到树状数组中,并计算逆序对数; 4. 输出逆序对数。 代码实现: ```c++ #include <cstdio> #include <cstdlib> #include <algorithm> const int MAXN = 500005; struct Node { int val, id; bool operator<(const Node& other) const { return val < other.val; } } nodes[MAXN]; int n, a[MAXN], b[MAXN], c[MAXN]; long long ans; inline int lowbit(int x) { return x & (-x); } void update(int x, int val) { for (int i = x; i <= n; i += lowbit(i)) { c[i] += val; } } int query(int x) { int res = 0; for (int i = x; i > 0; i -= lowbit(i)) { res += c[i]; } return res; } int main() { scanf("%d", &n); for (int i = 1; i <= n; ++i) { scanf("%d", &a[i]); nodes[i] = {a[i], i}; } std::sort(nodes + 1, nodes + n + 1); int cnt = 0; for (int i = 1; i <= n; ++i) { if (i == 1 || nodes[i].val != nodes[i - 1].val) { ++cnt; } b[nodes[i].id] = cnt; } for (int i = n; i >= 1; --i) { ans += query(b[i] - 1); update(b[i], 1); } printf("%lld\n", ans); return 0; } ``` 注意事项: - 在对原数列进行离散化时,需要记录每个元素在原数列中的位置,便于后面计算逆序对数; - 设树状数组的大小为 $n$,则树状数组中的下标从 $1$ 到 $n$,而不是从 $0$ 到 $n-1$; - 在计算逆序对数时,需要查询离散化后的数列中比当前元素小的元素个数,即查询 $b_i-1$ 位置上的值; - 在插入元素时,需要将离散化后的数列的元素从右往左依次插入树状数组中,而不是从左往右。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值