码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank "The Indian Job"

时间:2015-11-26 09:23:26      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

HackerRank "The Indian Job"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4996541.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!