yzoj P2043 & 洛谷 P1282 多米诺骨牌 题解

题意

类似于就是背包。

解析

代码

跟解析有点不一样v[i]价值,w[i]重量,s背包容积,背包转移即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e4+5; 
int n,s,x,y,tot,ans;
int v[maxn],w[maxn],dp[maxn];
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		scanf("%d %d",&x,&y);
		if(x>y){
			s+=x-y;
			v[i]=2*(x-y);
			w[i]=1;
		}
		else{
			s+=y-x;
			v[i]=2*(y-x);
			w[i]=-1;
			tot++;
		}
	}
	for(int i=1;i<=s;++i) dp[i]=maxn;
	dp[0]=0;
	for(int i=1;i<=n;++i){
		for(int j=s;j>=v[i];--j){
			if(dp[j-v[i]]!=maxn){
				dp[j]=min(dp[j],dp[j-v[i]]+w[i]);
			}
		}
	}
	for(int i=s;i>=0;--i){
		if(dp[i]!=maxn){
			ans=dp[i];
			break;
		}
	}
	printf("%d",ans+tot);
	return 0;
}
/*
4
6 1
1 5
1 3
1 2
*/
原文地址:https://www.cnblogs.com/donkey2603089141/p/11416802.html