HackerRank "Dorsey Thief"

A variation to 0-1 Knapsack. (No Python code got fully AC. Python is too slow for this problem)

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() 
{
    //    Get input
    int N, X; cin >> N >> X;
    vector<int> weight, cost;
    for (int i = 0; i < N; i++)
    {
        int w, c; cin >> w >> c;
        weight.push_back(w);
        cost.push_back(c);
    }

    //    T
    typedef pair<long long, int> Rec; // max-profit, cost
    vector<Rec> f(X + 1);
    for (int i = 0; i < N; i++)
        for (int v = X; v >= cost[i]; v--)
        {
            int newCost = f[v - cost[i]].second + cost[i];
            long long newProf = f[v - cost[i]].first + weight[i];
            if (newCost == v)
            {
                f[v].first = max(f[v].first, f[v - cost[i]].first + weight[i]);
                f[v].second = v;
            }
        }
    if (f[X].second < X)
        cout << "Got caught!" << endl;
    else
        cout << f[X].first << endl;
    return 0;
}

你可能感兴趣的:(HackerRank "Dorsey Thief")