Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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;
}
posted on 2016-02-03 14:32  Tonix  阅读(410)  评论(0编辑  收藏  举报