PAT甲級 1068. Find More Coins(揹包dp)

題目鏈接:傳送門

思路:用01揹包的模板可以直接判斷是否有可行解,然後是記錄字典序最小的答案序列,需要以貪心的思想先排序,以從大到小的順序選取物品,這樣保證輸出的結果最前面的物品最小。還有就是要用二維數組進行路徑記錄。

代碼:

#include <bits/stdc++.h>

using namespace std;

const int maxn = 1e4 + 5 , N = 405;

int a[maxn] , dp[N];
int g[maxn][N];
int n , m;

vector <int> ans;

int main() {
	ios::sync_with_stdio(0);
	cin >> n >> m;
	for(int i = 0 ; i < n ; i++)cin >> a[i];
	dp[0] = 1;
	sort(a , a + n);
	for(int i = n - 1 ; i >= 0 ; i--) {
		for(int j = m ; j  >= a[i] ; j--) {
			if(dp[j - a[i]]) {
				dp[j] = 1;
				g[i][j] = 1;
			}
		}
	}
	if(!dp[m])cout << "No Solution\n";
	else {
		int t = m , cnt = 0;
		while(cnt < n && t > 0) {
		    if(!g[cnt][t]) {
		    	cnt++;
			}
		    else {
		    	ans.push_back(a[cnt]);
		    	t = t - a[cnt];cnt++;
			}
		}
		for(int i = 0 ; i < ans.size() ; i++) {
			if(i > 0)cout << " ";
			cout << ans[i];
		}
		cout << "\n";
	}
	return 0;
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章