算法设计-01背包子集树的递归写法

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

const int N = 1010;
int x[N], fx[N], sum[N],v[N], w[N], n, m, ans, bestans;

bool Constraint(int t){
	int ans = 0;
	for(int i = 1; i <= t; i++){
		ans += x[i]*v[i];
	}
	return ans < m;
}
bool Bound(int t){
	return sum[t]+ans > bestans;
}
void Backtrack(int t){
	if(t > n){
		bestans = ans;
		for(int i = 1; i <= n; i++) fx[i] = x[i];
		return;
	}
	if(Constraint(t+1)){
		x[t+1] = 1;
		ans += w[t+1];
		Backtrack(t+1);
		x[t+1] = 0;
		ans -= w[t+1];
	}
	if(Bound(t+1))
		Backtrack(t+1);
}
int main(){
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i++) scanf("%d", &w[i]);
	for(int i = 1; i <= n; i++) scanf("%d", &v[i]); 
	
	sum[n] = v[n];
	for(int i = n-1; i > 0; i--) sum[i] = sum[i+1]+w[i];
	Backtrack(0);
	
	printf("%d\n", bestans);
	for(int i = 1; i <= n; i++) printf("%d ", fx[i]);
	printf("\n");
	return 0;
}
上一篇:NC121—字符串的排列


下一篇:RealSence D435i相机使用