跳到正文

算法·理论

状压dp满足字典序trick

Lqs888约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年3月20日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

对于需要满足字典序的状压dp,我们需对第一步而不是最后一步进行转移,如HDU1074。

Code

C++
#include<bits/stdc++.h>
using namespace std;
namespace IO{
	#define gc getchar
	#define pc putchar
	#define ps puts
	inline int in(){
		int x=0,f=1;
		char c=gc();
		for(;!isdigit(c);c=gc())if(c=='-')f=-1;
		for(;isdigit(c);c=gc())x=x*10+(c-'0');
		return x*f;
	}
	inline void out(int x){
		if(x<0)pc('-'),x=-x;
		if(x>=10)out(x/10);
		pc(x%10+'0');
	}
	inline void outsp(int x){out(x),pc(' ');}
	inline void outln(int x){out(x),ps("");}
}
using namespace IO;
const int N=15,M=1<<N;
int n,m,sum,a[N+5],b[N+5],f[M],g[M],lst[M];
void print(int s){
	if(!s)return;
	outln(lst[s]);
	print(s-(1<<(lst[s]-1)));
}
int main(){
	n=in(),m=1<<n;
	for(int i=1;i<=n;i++)a[i]=in(),b[i]=in(),sum+=b[i];
	for(int s=1;s<m;s++)f[s]=M;
	for(int s=1;s<m;s++){
		for(int j=1;j<=n;j++)if(s&(1<<(j-1))){
			int t=s-(1<<(j-1)),w=max(0,sum-g[t]-a[j]);
			if(f[s]>f[t]+w){
				f[s]=f[t]+w,g[s]=g[t]+b[j];
				lst[s]=j;
			}
		}
	}
	outln(f[m-1]),print(m-1);
	return 0;
}
原文