hdoj 1171 Big Event in HDU(背包dp+母函数)

时间:2022-04-27 16:56:14

【题目大意】:给出n种数,每种数有m个,问怎么把这n*m个数分成两部分,满足第一部分大于等于第二部分,且尽可能相等。


【解题思路】:dp,多重背包问题。

                            母函数,转化为求n种数m个数可以表示出那些数,计这个数为i,找到i,sum-i使得二者接近。


【代码】:

母函数:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>

using namespace std;

#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

struct Noed{
int x,cnt;
}a[100];

int n;
int c1[300000],c2[300000];

int main() {
while (~scanf("%d",&n)) {
if (n<=0) break;
int sum=0;
for (int i=0; i<n; i++){
scanf("%d%d",&a[i].x,&a[i].cnt);
sum+=a[i].x*a[i].cnt;
}

memset(c2,0,sizeof(c2));
memset(c1,0,sizeof(c1));
for (int i=0; i<=a[0].x*a[0].cnt; i+=a[0].x) c1[i]=1;

int now=a[0].x*a[0].cnt;
for (int i=1; i<n; i++){ //枚举可拆分的范围
for (int j=0; j<=now; j++){ //枚举已知的范围
for (int k=0; k<=a[i].x*a[i].cnt; k+=a[i].x){ //枚举新增的范围
c2[j+k]+=c1[j];
}
}
now+=a[i].x*a[i].cnt;
for (int j=0; j<=now; j++) c1[j]=c2[j],c2[j]=0; //更新
}
int tmp=sum,p,q;
for (int i=sum/2; i<=sum; i++){
if (i>=sum-i && i-(sum-i)<=tmp && c1[i]!=0) tmp=i-(sum-i),p=i,q=sum-i;
}
cout << p << " " << q << endl;
}
return 0;
}

dp,背包

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>

using namespace std;

#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

int a[15005],dp[251005];
int num,sum;

int main(){
int n,m,k;
while(~scanf("%d",&n)){
if(n<0) break;
num=0;
sum=0;
memset(dp,0,sizeof(dp));
for (int i=1; i<=n; i++){
scanf("%d%d",&m,&k);
for (int j=1; j<=k; j++)
a[num++]=m;
sum+=m*k;
}
for (int i=0; i<num; i++)
for (int j=sum/2; j>=a[i]; j--)
dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
printf("%d %d\n",max(dp[sum/2],sum-dp[sum/2]),min(dp[sum/2],sum-dp[sum/2]));
}
return 0;
}