hdu 1171

//背包问题:f[v]=max(f[v],f[v-cost]+weight)
#include<iostream>
#define max(a,b) a>b?a:b
using namespace std;
int c[300000],i,k,sum,a[110],b[110],n;
//01背包
void bag(int cost,int weight)
{
 for(i=sum/2;i>=cost;i--)
  c[i]=max(c[i],c[i-cost]+weight);
}
//完全背包
void complete(int cost,int weight)
{
 for(i=cost;i<=sum/2;i++)
  c[i]=max(c[i],c[i-cost]+weight);
}
//多重背包
void multiply(int cost,int weight,int amount)
{
 if(cost*amount>=sum/2)
  complete(cost,weight);
 k=1;
 while(k<amount)
 {
  bag(k*cost,k*weight);
  amount-=k;
  k+=k;
 }
 bag(amount*cost,amount*weight);
}
int main()
{
 int i;            //注意重新定义,否则结果会出错。
 while(cin>>n&&n>0)
 {
  memset(a,0,sizeof(a));
  memset(b,0,sizeof(b));
  memset(c,0,sizeof(c));
  for(sum=0,i=1;i<=n;i++)
  {
   cin>>a[i]>>b[i];
   sum+=a[i]*b[i];
  }
  for(i=1;i<=n;i++)
   multiply(a[i],a[i],b[i]);
  cout<<sum-c[sum/2]<<" "<<c[sum/2]<<endl;
 }
 return 0;
}

posted @ 2012-07-27 15:44  疼痛落在指尖  阅读(160)  评论(0编辑  收藏  举报