[jzoj 4743] 积木{状态压缩dp}

版权声明:~~~感谢支持! https://blog.csdn.net/qq_39897867/article/details/88368387

题目

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述


解题思路

我们可以设 f [ s ] [ i ] [ j ] f[s][i][j] 为状态为 s s 最上面为 i i 且状态摆放状态 j j 的最优解。
那么动态转移方程易推。

f [ s ( 1 < < i 1 ) ] [ i ] [ 1 / 2 / 3 ] = m a x ( f [ s ( 1 < < i 1 ) ] [ i ] [ 1 / 2 / 3 ] , f [ s ] [ j ] [ 1 / 2 / 3 ] + a / b / c [ i ] ) ; f[s|(1<<i-1)][i][1/2/3]=max(f[s|(1<<i-1)][i][1/2/3],f[s][j][1/2/3]+a/b/c[i]);

时间复杂度为 O ( 2 n n 2 ) O(2^n*n^2)


代码

~~码风见谅qwq

#include<cstdio>
#include<algorithm>
#define rep(i,x,y) for (register int i=x;i<=y;i++)
using namespace std;
const int maxn=(1<<15);
int n,a[20],b[20],c[20]; 
int f[maxn][20][4],ans;
int main(){
	scanf("%d",&n); 
	for (int i=1;i<=n;i++) {
		scanf("%d%d%d",&a[i],&b[i],&c[i]); 
		f[1<<i-1][i][1]=a[i]; 
		f[1<<i-1][i][2]=b[i]; 
		f[1<<i-1][i][3]=c[i]; 
	}
	int lw=1<<n; 
	rep(s,1,lw-1)  rep(i,1,n) if ((s&(1<<i-1))==0){
	  rep(j,1,n) if ((s&(1<<(j-1)))&&i!=j){
	  	 if ((b[j]>=b[i]&&c[j]>=c[i])||(b[j]>=c[i]&&c[j]>=b[i]))  	  f[s|(1<<i-1)][i][1]=max(f[s|(1<<i-1)][i][1],f[s][j][1]+a[i]); 	  	  
		 if ((b[j]>=a[i]&&c[j]>=c[i])||(b[j]>=c[i]&&c[j]>=a[i]))  	  f[s|(1<<i-1)][i][2]=max(f[s|(1<<i-1)][i][2],f[s][j][1]+b[i]); 	 
		 if ((b[j]>=b[i]&&c[j]>=a[i])||(b[j]>=a[i]&&c[j]>=b[i])) 	  f[s|(1<<i-1)][i][3]=max(f[s|(1<<i-1)][i][3],f[s][j][1]+c[i]);
		  
	  	 if ((a[j]>=b[i]&&c[j]>=c[i])||(a[j]>=c[i]&&c[j]>=b[i]))  	  f[s|(1<<i-1)][i][1]=max(f[s|(1<<i-1)][i][1],f[s][j][2]+a[i]); 	  	  
		 if ((a[j]>=a[i]&&c[j]>=c[i])||(a[j]>=c[i]&&c[j]>=a[i]))  	  f[s|(1<<i-1)][i][2]=max(f[s|(1<<i-1)][i][2],f[s][j][2]+b[i]); 	 
		 if ((a[j]>=b[i]&&c[j]>=a[i])||(a[j]>=a[i]&&c[j]>=b[i])) 	  f[s|(1<<i-1)][i][3]=max(f[s|(1<<i-1)][i][3],f[s][j][2]+c[i]);
		 
	  	 if ((a[j]>=b[i]&&b[j]>=c[i])||(a[j]>=c[i]&&b[j]>=b[i]))  	  f[s|(1<<i-1)][i][1]=max(f[s|(1<<i-1)][i][1],f[s][j][3]+a[i]); 	  	  
		 if ((a[j]>=a[i]&&b[j]>=c[i])||(a[j]>=c[i]&&b[j]>=a[i]))  	  f[s|(1<<i-1)][i][2]=max(f[s|(1<<i-1)][i][2],f[s][j][3]+b[i]); 	 
		 if ((a[j]>=b[i]&&b[j]>=a[i])||(a[j]>=a[i]&&b[j]>=b[i])) 	  f[s|(1<<i-1)][i][3]=max(f[s|(1<<i-1)][i][3],f[s][j][3]+c[i]);		 	 	 		 
	  }
	 }
	rep(s,0,lw-1) rep(i,1,n) rep(j,1,3) ans=max(ans,f[s][i][j]); 
	printf("%d",ans); 
}

猜你喜欢

转载自blog.csdn.net/qq_39897867/article/details/88368387