HackerRank "Dorsey Thief"

时间:2023-07-13 13:28:44

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 = ; 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 + );
for (int i = ; 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 ;
}