Cod sursa(job #1898291)

Utilizator bogdanboboc97Bogdan Boboc bogdanboboc97 Data 1 martie 2017 22:10:37
Problema Problema rucsacului Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>

int knapsack(std::vector< std::pair<int,int> > objects, int maxWeight)
{
    std::vector<int> dp(maxWeight+1,0),aux(maxWeight+1,0);
    int solIndex = 0;

    for(int i=0;i<(int)objects.size();i++)
    for(int j=maxWeight-objects[ i ].first;j>=0;j--)
    if(dp[j] + objects[i].second > dp[ j + objects[i].first ])
    {
            dp[ j + objects[i].first ] = dp[j] + objects[i].second;
            aux[ j + objects[i].first ] = i;
            solIndex=(dp[ solIndex ] < dp[ j + objects[i].first ] ? j + objects[i].first : solIndex);
    }
    return dp[solIndex];
}

int main()
{
    std::ifstream in("rucsac.in");

    std::vector< std::pair<int,int> > objects;
    int n,maxWeight;

    in>>n>>maxWeight;
    for(int i=0;i<n;i++)
    {
        std::pair<int,int> x;
        in>>x.first>>x.second;
        objects.push_back(x);
    }

    std::ofstream out("rucsac.out");
    out<<knapsack(objects,maxWeight)<<'\n';

    return 0;
}