Problem Description
Nowadays, we all know that Computer College is the biggest department in HDU. But, maybe you don’t know that Computer College had ever been split into Computer College and Software College in 2002.
The splitting is absolutely a big event in HDU! At the same time, it is a trouble thing too. All facilities must go halves. First, all facilities are assessed, and two facilities are thought to be same if they have the same value. It is assumed that there is N (0<N<1000) kinds of facilities (different value, different kinds).
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 50 — the total number of different facilities). The next N lines contain an integer V (0<V<=50 —value of facility) and an integer M (0<M<=100 —corresponding number of the facilities) each. You can assume that all V are different.
A test case starting with a negative integer terminates input and this test case is not to be processed.
Output
For each case, print one line containing two integers A and B which denote the value of Computer College and Software College will get respectively. A and B should be as equal as possible. At the same time, you should guarantee that A is not less than B.
输入样例
2
10 1
20 1
3
10 1
20 2
30 1
-1
输出样例
20 10
40 40
母函数做法,最后输出的方法为核心
#include<bits/stdc++.h> using namespace std; const int N=25e4; int val[60],cnt[60]; int c1[N],c2[N]; int main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); int n; while(cin>>n,n>0) { int sum=0; for(int i=0;i<n;++i) {cin>>val[i]>>cnt[i];cnt[i]=val[i]*cnt[i];sum+=cnt[i]; } //cout<<sum<<endl; for(int i=0;i<=sum;++i) c1[i]=0,c2[i]=0; for(int i=0;i<=cnt[0];i+=val[0]) c1[i]=1; for(int i=1;i<n;++i) {for(int j=0;j<=sum;++j) for(int k=0;k<=cnt[i]&&k+j<=sum;k+=val[i]) c2[j+k]+=c1[j]; for(int j=0;j<=sum;++j) c1[j]=c2[j],c2[j]=0; } for(int i=sum/2;i>=0;--i) if(c1[i]) {cout<<sum-i<<' '<<i<<'\n'; break; } } }
背包做法,二进制拆分时先减后乘倍,避免拆分出现负数,同时一个数拆分能拆除logn+2种
附ac代码
#include<bits/stdc++.h> using namespace std; const int N=6000,M=26e4+100; int val[N]; int cnt=0; int dp[M]; void chai(int value,int num) { int i=1; while(num>=i) { val[cnt++]=value*i; num-=i; i<<=1; } if(num) val[cnt++]=num*value; } int main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); int n,value,num; while(cin>>n,n>0) { int sum=0; memset(dp,0,sizeof(dp)); cnt=0; memset(val,0,sizeof(val)); for(int i=0;i<n;++i) { cin>>value>>num; sum+=value*num; chai(value,num); } dp[0]=1; for(int i=0;i<cnt;++i) for(int j=sum;j>=val[i];--j) { if(dp[j-val[i]]) dp[j]=1; } for(int i=sum/2;i>=0;--i) if(dp[i]) {cout<<sum-i<<' '<<i<<'\n'; break;} } return 0; }
标签:hdu,val,int,Big,HDU,value,num,cnt,dp From: https://www.cnblogs.com/ruoye123456/p/17066015.html