HDU1171:Big Event in HDU(多重背包分析)

通过分析,要使A>=B并且差值最小。所以只要使sum/2的容量下,B最大就Ok了

#include<iostream>

#include<cstdio>

#include<algorithm>

#include<cstring>

#include<string>

using namespace std;

#define N 5000000

int dp[N];

struct Node{

     int v,m;

}num[1005];

bool cmp(Node a,Node b){

    return a.v<b.v;

}

int main(void)

{

    int n;

    int i,j,k;

    while(cin>>n&&n>0){

        int sum=0;

        for(i=1;i<=n;i++){ 

            cin>>num[i].v>>num[i].m;

            sum+=num[i].v*num[i].m;

        }

        sort(num+1,num+1+n,cmp);

        memset(dp,0,sizeof(dp));

        for(i=1;i<=n;i++)

            for(j=1;j<=num[i].m;j++)

                for(k=sum/2;k>=num[i].v;k--){

                    dp[k]=max(dp[k],dp[k-num[i].v]+num[i].v);

                }

        cout<<sum-dp[sum/2]<<" "<<dp[sum/2]<<endl;



    }

    return 0;

}

 

你可能感兴趣的:(event)