标签:
A sly knapsack problem in disguise! Thanks to https://github.com/bhajunsingh/programming-challanges/tree/master/hackerrank/algorithms/the-indian-job
Lesson learnt: The Italian\Indian job is two-way 01 Knapsack. And some complext problem can be converted to a simpler one.
Code is amazingly simple:
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int knapsack(vector<int> &A, int G) { int n = A.size(); vector<int> dp(G + 1); for(int i =1; i <= n; i ++) for(int v =G; v >= A[i - 1]; v --) dp[v] = max(dp[v], dp[v- A[i - 1]]+ A[i- 1]); return dp[G]; } int main() { int T; cin >> T; while(T--) { // Get input int N, G; cin >> N >> G; vector<int> A(N); int total = 0; for(int i = 0; i < N; i++) { cin >> A[i]; total += A[i]; } // if(total > 2 * G) cout << "NO" << endl; else cout << ((total - knapsack(A, G) <= G) ? "YES" : "NO") << endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/tonix/p/4996541.html