跳到正文

个人记录

关于双序列DP

wangxinwangxin约 17 分钟
原文
文章信息与版本

文章信息

收录
2026年5月24日
更新
2026年5月24日
篇幅
约 17 分钟

版本

  1. v2当前
  2. v1

双序列 DPDP 是指给定两个序列(比如字符串、数组 AA、BB),在两个序列上同时做动态规划,求最优解.

  • 单序列 DPDP:只有一个数组,从前往后推

  • 双序列 DPDP:两个数组,状态通常是 fi,jf_{i,j},表示 AA 的前 ii 个,BB 的前 jj 个的最优解

Here are some examples.Here\ are\ some\ examples.

最长公共子序列

题意简述

给出 1 1\ , 2 \ 2\ , … \ \ldots\ , n\ n 的两个排列 P1P_1 和 P2P_2 ,求它们的最长公共子序列.

分析

正常人首先一定会考虑暴力,时间复杂度 O(n2)O(n^2),然后正常人就被 TT 飞了.正常人是谁啊?

我们其实不难看出,对于 n2n^2 做法而言,其实就是暴力枚举:将每个状态都分别比较一遍。但其实有些没有必要的状态的枚举,导致浪费许多时间,当元素个数到 10510^5 以下时,就已经超时了。而此时,我们可以通过另一种动态规划的方式来降低时间复杂度.

由于 P1P_1 和 P2P_2 是同一堆数字的不同排列,所以 P1P_1 的子序列在 P2P_2 都有对应的数字,而公共子序列和别的序列的区别只有在 P2P_2 中的顺序是否与在 P1P_1 中的顺序一样。

所以可以先把 P2P_2 的所有数字按在 P1P_1 中的顺序标号,然后就把问题转化成了求 P2P_2 数字标号的最长上升子序列的长度了。这里最长上升子序列使用 O(n log n)O(n\ log\ n) 做法.时间复杂度 O(n log n)O(n\ log\ n).

Code

C++
#include <bits/stdc++.h>
using namespace std;
int l,r,ans=INT_MIN+1000,n,cnt,a[114514],b[114514],c[114514],f[114514];
int fen(int x)
{
	int le=0,ri=cnt,mid;
	while(le<ri)
	{
		mid=(le+ri)/2+1;
		if(f[mid]>=x) ri=mid-1;
		else le=mid;
	}
	return le;
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	cin >> n;
	for (int i=1;i<=n;i++)
	{
		cin >> a[i];
		c[a[i]]=i;
	}
	for (int i=1;i<=n;i++)
	{
		cin >> b[i];
		b[i]=c[b[i]];
	}
	for (int i=1;i<=n;i++)
	{
		int l=fen(b[i])+1;
		ans=max(ans,l);
		f[l]=(!f[l]?b[i]:min(f[l],b[i]));
		cnt=max(cnt,l);
	}
	cout << ans;
	return 0;
}

编辑距离

题意简述

对于两个字符串 AA 和 BB,我们要用最少的字符操作次数,将字符串 AA 转换为字符串 BB。

字符操作共有三种:

  1. 删除一个字符;

  2. 插入一个字符;

  3. 将一个字符改为另一个字符。

分析

依旧正常人暴力思路:递归枚举所有可能的操作(删除 / 插入 / 替换),计算每种操作后的最小操作次数,最终取最小值。

但是这样的话,使用 DFSDFS 每次会考虑整整 33 种情况!!!总时间复杂度高达 O(3max(m,n))O(3^{max(m,n)}),遇到 max(m,n)max(m,n) 为 1616 时,正常人就被 TT 飞了。

聪明的我们突然想到 DFSDFS 时会有各种相同的子问题(其实十分好想)。于是,一个十分人类的记忆化搜索出现了!!!

C++
#include <bits/stdc++.h>
#define N 2001
using namespace std;
string a, b;
int dp[N][N];
int dfs(int i, int j) {
	if (i == 0) return j;
	if (j == 0) return i;
	if (dp[i][j] != -1) return dp[i][j];
	if (a[i - 1] == b[j - 1]) {
		return dp[i][j] = dfs(i - 1, j - 1);
	}
	int op1 = dfs(i - 1, j);
	int op2 = dfs(i, j - 1);
	int op3 = dfs(i - 1, j - 1);
	return dp[i][j] = 1 + min({op1, op2, op3});
}
int main() {
	cin >> a >> b;
	memset(dp, -1, sizeof(dp));
	cout << dfs(a.size(), b.size());
	return 0;
}

最后,稍微转化,得到 DPDP 做法:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
string a,b;
int x,y,sum,f[2001][2001];
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin >> a >> b;
    x=a.size();
    y=b.size();
    for (int i = 0 ; i <= x ; i++)
    {
    	f[i][0]=i;
	}
	for (int i = 0 ; i <= y ; i++)
    {
    	f[0][i]=i;
	}
	for (int i = 1 ; i <= x ; i++)
	{
		for (int j = 1 ; j <= y ; j++)
		{
			if (a[i - 1] == b[j - 1])
			{
				f[i][j] = f[i - 1][j - 1];
			}
			else
			{
				f[i][j] = min(min(f[i-1][j] , f[i][j-1]) , f[i-1][j-1])+1;
			}
		}
	}
	cout << f[x][y];
	return 0;
}

相似基因

题意简述

  1. 给你两个基因序列 s1s1 和 s2s2(只含 AA / CC / GG / TT)。

  2. 你可以在两个基因的任意位置插入空碱基 −-,让两个序列长度变得一样。

  3. 按照题目给的碱基配对分数表,计算每一对碱基的分数之和。

  4. 要求:找到一种插入方式,让总分数最大,输出这个最大值。

碱基之间的分数如下表所示:

ACGT-A5−1−2−1−3C−15−3−2−4G−2−35−2−2T−1−2−25−1-−3−4−2−1∗\def\arraystretch{1.5} \begin{array}{ |c|c|c|c|c|c|} \hline & \tt A & \tt C & \tt G & \tt T & \texttt - \\ \hline \tt A & 5 & -1 & -2 & -1 & -3\\ \hline \tt C & -1 & 5 & -3 & -2 & -4 \\\hline \tt G & -2 & -3 & 5 & -2 & -2 \\\hline \tt T & -1 & -2 & -2 & 5 & -1 \\\hline \texttt - & -3 & -4 & -2 & -1 & * \\\hline \end{array}

分析

我们发现这题的暴力做法和编辑距离几乎一致,只是把三种情况改成了:

  1. s1s1 与 s2s2 配对

  2. s1s1 与 −- 配对

  3. s2s2 与 −- 配对

然后打出暴力代码:

C++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int score(char x, char y) {
    if (x == 'A' && y == 'A') return 5;
    if (x == 'A' && y == 'C') return -1;
    if (x == 'A' && y == 'G') return -2;
    if (x == 'A' && y == 'T') return -1;
    if (x == 'A' && y == '-') return -3;
    if (x == 'C' && y == 'A') return -1;
    if (x == 'C' && y == 'C') return 5;
    if (x == 'C' && y == 'G') return -3;
    if (x == 'C' && y == 'T') return -2;
    if (x == 'C' && y == '-') return -4;
    if (x == 'G' && y == 'A') return -2;
    if (x == 'G' && y == 'C') return -3;
    if (x == 'G' && y == 'G') return 5;
    if (x == 'G' && y == 'T') return -2;
    if (x == 'G' && y == '-') return -2;
    if (x == 'T' && y == 'A') return -1;
    if (x == 'T' && y == 'C') return -2;
    if (x == 'T' && y == 'G') return -2;
    if (x == 'T' && y == 'T') return 5;
    if (x == 'T' && y == '-') return -1;
    if (x == '-' && y == 'A') return -3;
    if (x == '-' && y == 'C') return -4;
    if (x == '-' && y == 'G') return -2;
    if (x == '-' && y == 'T') return -1;
    return 0;
}
string s1, s2;
int dfs(int i, int j) {
    if (i == 0 && j == 0) return 0;
    if (i == 0) return score('-', s2[j-1]) + dfs(i, j-1);
    if (j == 0) return score(s1[i-1], '-') + dfs(i-1, j);
    int op1 = score(s1[i-1], s2[j-1]) + dfs(i-1, j-1);
    int op2 = score(s1[i-1], '-') + dfs(i-1, j);
    int op3 = score('-', s2[j-1]) + dfs(i, j-1);
    return max({op1, op2, op3});
}

int main() {
    int n1, n2;
    cin >> n1 >> s1 >> n2 >> s2;
    cout << dfs(n1, n2) << endl;
    return 0;
}

可惜时间复杂度为 O(3n+m)O(3^{n+m}) (nn , mm 分别为两个字符串的长度),成功被 TT 飞。

聪明的我们再次想到 DFSDFS 时会有各种相同的子问题。于是,一个十分人类的记忆化搜索又出现了!!!

C++
#include <bits/stdc++.h>
using namespace std;
const int INF = -0x3f3f3f3f;
int dp[105][105];
string s1, s2;
int getScore(char a, char b)
{
    int tab[5][5] = {
        {5, -1, -2, -1, -3},
        {-1, 5, -3, -2, -4},
        {-2, -3, 5, -2, -2},
        {-1, -2, -2, 5, -1},
        {-3, -4, -2, -1, 0}
    };
    int x, y;
    if(a == 'A') x = 0;
    else if(a == 'C') x = 1;
    else if(a == 'G') x = 2;
    else if(a == 'T') x = 3;
    else x = 4;

    if(b == 'A') y = 0;
    else if(b == 'C') y = 1;
    else if(b == 'G') y = 2;
    else if(b == 'T') y = 3;
    else y = 4;
    return tab[x][y];
}
int dfs(int i, int j)
{
    if(i == 0 && j == 0) return 0;
    if(dp[i][j] != INF) return dp[i][j];

    int res = INF;
    if(i > 0 && j > 0)
        res = max(res, dfs(i-1, j-1) + getScore(s1[i-1], s2[j-1]));
    if(i > 0)
        res = max(res, dfs(i-1, j) + getScore(s1[i-1], '-'));
    if(j > 0)
        res = max(res, dfs(i, j-1) + getScore('-', s2[j-1]));

    return dp[i][j] = res;
}

int main()
{
    int n1, n2;
    cin >> n1 >> s1;
    cin >> n2 >> s2;
    memset(dp, 0xcf, sizeof(dp));
    cout << dfs(n1, n2) << endl;
    return 0;
}

整理,得到 DPDP 代码:

C++
#include <bits/stdc++.h>
using namespace std;
int la,lb,f[101][101],a[101],b[101];
int d[6][6]={
0,0,0,0,0,0,
0,5,-1,-2,-1,-3,
0,-1,5,-3,-2,-4,
0,-2,-3,5,-2,-2,
0,-1,-2,-2,5,-1,
0,-3,-4,-2,-1,0};
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin >> la;
    for (int i=1;i<=la;i++)
    {
    	char now;
    	cin >> now;
    	if (now=='A'){
    		a[i]=1;
		}
		else if (now=='C'){
			a[i]=2;
		}
		else if (now=='G'){
			a[i]=3;
		}
		else if (now=='T'){
			a[i]=4;
		}
	}
    cin >> lb;
    for (int i=1;i<=lb;i++)
    {
    	char now;
    	cin >> now;
    	if (now=='A'){
    		b[i]=1;
		}
		else if (now=='C'){
			b[i]=2;
		}
		else if (now=='G'){
			b[i]=3;
		}
		else if (now=='T'){
			b[i]=4;
		}
	}
	f[0][0]=0;
	for(int i=1;i<=la;i++){
		f[i][0]=f[i-1][0]+d[a[i]][5];
	}
	for(int i=1;i<=lb;i++){
		f[0][i]=f[0][i-1]+d[5][b[i]];
	}
	for (int i=1;i<=la;i++){
		for (int j=1;j<=lb;j++){
			f[i][j]=max(f[i-1][j-1]+d[a[i]][b[j]],max(f[i-1][j]+d[a[i]][5],f[i][j-1]+d[5][b[j]]));
		}
	}
	cout << f[la][lb];
	return 0;
}

Cow Checklist G

题意简述

  1. 有 H 头荷斯坦牛(编号 1H)和 G 头根西牛(编号 1G),每头牛都在二维平面上有坐标。

  2. 要求:

    • 从荷斯坦牛 1出发,必须在荷斯坦牛 H 结束;

    • 必须按编号顺序访问两类牛(1→2→3… 不能跳号、不能倒序);

    • 把两个牛序列交错合并成一个总序列,访问所有 H+G 头牛;

    • 移动消耗能量 = 两点间距离的平方。

  3. 求满足所有条件的最小总消耗能量。

分析

详见 兰华杯赛后总结 T4T4

总结

状态定义

定义状态:fi,jf_{i,j}

表示:

第一个序列处理了前 ii 个

第二个序列处理了前 jj 个

此时的 最优值(最小 / 最大)

如果需要记录最后停在哪里,就加一维:

fi,j,0和fi,j,1f_{i,j,0} 和 f_{i,j,1}

00:最后在第一个序列

11:最后在第二个序列

转移方程

  1. 两个当前位置匹配

    i 和 j 直接对应

    fi−1,j−1+代价f_{i-1,j-1} + 代价
  2. 第一个序列动,第二个不动(删 / 跳过 / 配空)

    fi−1,j+代价f_{i-1,j} + 代价
  3. 第二个序列动,第一个不动(插 / 跳过 / 配空)

    fi,j−1+代价f_{i,j-1} + 代价

求最小 →min → min

求最大 →max → max

原文