跳到正文

个人记录

dp of dp学习笔记

Cute_Fish约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年7月30日
篇幅
约 3 分钟

版本

  1. v1当前

dp of dp本质上其实是一种状压,通过用外层dp的状态表示内层dp的转移情况等信息,在此不过多赘述,直接做题。

1.BZOJ3864 Hero meet devil⁡\color{black}\operatorname{1.BZOJ3864 \ Hero \ meet \ devil}

考虑以最长公共子序列做为内层dp。

设 fi,jf_{i,j} 表示 ss 串前 ii 个字母和 tt 串前 jj 个字母的最长公共子序列。转移容易得到。

直接做复杂度高,如何优化?

注意到从 fi−1,jf_{i-1,j} 转移到 fi,jf_{i,j} 最多差 11 ,所以可以以 ff 的差分数组做状压,可以通过!

C++
#include <bits/stdc++.h>
#include <ext/rope>
using namespace __gnu_cxx;
using namespace std;
typedef long long ll;
#define int ll
const char ch[4]={'A','C','G','T'};
const int mod=1e9+7;
int cnt[1<<15],f[1001][1<<15],res[17],pre[1<<15][4],f2[17],g[17]; 
signed main(){
	int T;cin>>T;
	while(T--){
		string s;cin>>s;
		int m;cin>>m;
		int n=s.size();
		for(int i=0;i<(1<<n);i++){
					f2[0] = 0;
			for(int j = 1; j <= n; j++) {
				f2[j] = f2[j - 1];
				if(i & (1 << (j - 1))) f2[j]++;//还原f数组
			}  
			cnt[i]=f2[n];
			for(int k=0;k<4;k++){
				g[0]=0;
				for(int j=1;j<=n;j++){
					g[j]=max(g[j-1],f2[j]);
					if(ch[k]==s[j-1])g[j]=f2[j-1]+1;
				}//LCS转移
				int num=0;
				for(int j=1;j<=n;j++)num+=((g[j]-g[j-1])<<j-1);//差分做状压
				pre[i][k]=num;//预处理操作后的状态
		    }
		}
		memset(f,0,sizeof(f));
	    f[0][0] = 1;
		for(int i = 1; i <= m; i++) 
			for(int j = 0; j < (1 << n); j++) 
				for(int k = 0; k < 4; k++) (f[i][pre[j][k]]+=f[i-1][j])%=mod;
		for(int i = 0; i <= n; i++)res[i] = 0;
		for(int i = 0; i < (1 << n); i++)(res[cnt[i]]+=f[m][i])%=mod;
		for(int i = 0; i <= n; i++) cout<<res[i]<<"\n";
	}
}

2.[SDOI/SXOI2022]小N的独立集⁡\color{black}\operatorname{2. [SDOI/SXOI2022] 小 N 的独立集}

原文