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 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 namespacestd;intKnapsack (vector<int> &a,intG) { intn =a.size (); Vector<int> dp (G +1); for(inti =1; I <= N; i + +) for(intV =g; V >= a[i-1]; V--) Dp[v]= Max (Dp[v], dp[v-a[i-1]]+ a[i-1]); returnDp[g]; }intMain () {intT CIN >>T; while(t--) { //Get Input intN, G; CIN>> N >>G; Vector<int>A (N); intTotal =0; for(inti =0; i < N; i++) {cin>>A[i]; Total+=A[i]; } // if(Total >2*G) cout<<"NO"<<Endl; Elsecout<< ((Total-knapsack (A, G) <= g)?"YES":"NO") <<Endl; } return 0;}
Hackerrank "The Indian Job"