zoukankan      html  css  js  c++  java
  • HackerRank "The Indian Job"

    A sly knapsack problem in disguise! Thanks to https://github.com/bhajunsingh/programming-challanges/tree/master/hackerrank/algorithms/the-indian-job
    Lesson learnt: The ItalianIndian 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;
    }
  • 相关阅读:
    9-15
    9-5
    8-26
    8-24
    7-20
    7-17
    我离职后要干些什么
    6-18
    5-28
    5-20
  • 原文地址:https://www.cnblogs.com/tonix/p/4996541.html
Copyright © 2011-2022 走看看