A sly knapsack problem in disguise! Thanks to
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#include #include #include #include using namespace std;int knapsack(vector &A, int G){ int n = A.size(); vector 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 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;}