cjweffort

博客园 首页 联系 订阅 管理

01背包问题

(1)排序数据为降序

(2)背包处理

// 1068. Find More Coins.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

#define max(a, b) ((a) > (b) ? (a) : (b))
const int N = 10003;
int coin[N], dp[103];
vector<int> ans[N];
typedef vector<int>::iterator IT;
typedef vector<int>::reverse_iterator RIT;

bool cmp(int m1, int m2){
	return m1 > m2;
}

int main()
{
	int n, total;
	cin >> n >> total;
	for(int i = 1; i <= n; i++)
		cin >> coin[i];
	coin[0] = 0;
	sort(coin + 1, coin + 1 + n, cmp);
	memset(dp, 0, sizeof(dp));
	for(int i = 1; i <= n; i++){
		for(int j = total; j >= coin[i]; j--){
			if(dp[j] <= dp[j - coin[i]] + coin[i]){
				dp[j] = dp[j - coin[i]] + coin[i];
				ans[j].clear();
				for(IT ite = ans[j - coin[i]].begin(); ite != ans[j - coin[i]].end(); ite++)
					ans[j].push_back(*ite);
				ans[j].push_back(coin[i]);
			}
		}
	}
	if(dp[total] != total)
		cout << "No Solution" << endl;
	else{
		bool flag = true;
		for(RIT ite = ans[total].rbegin(); ite != ans[total].rend(); ite++){
			if(flag){
				flag = false;
				cout << *ite;
			}
			else
				cout << " " << *ite;
		}
		cout << endl;
	}
	return 0;
}



posted on 2013-10-10 19:59  cjweffort  阅读(264)  评论(0编辑  收藏  举报