HDU1171 Big Event in HDU

//这一题是看能够组合出哪些值,这些值距离sum/2最近的为最优的解
#include<iostream>
#include<cmath>
using namespace std;

int c1[250005];
int c2[250005];

int n,sum;
struct Node{
	int val;
	int count;
};
Node nd[55];

int main(){
	while(scanf("%d",&n)&&n>0){
		sum=0;
		for(int i=0;i<n;i++){
			scanf("%d%d",&nd[i].val,&nd[i].count);
			sum+=nd[i].val*nd[i].count;
		}
		
		memset(c2,0,sizeof(c2));
		memset(c1,0,sizeof(c1));
		for(int i=0;i<=nd[0].count*nd[0].val;i+=nd[0].val)
			c1[i]=1;
		//共n个式子
		for(int i=1;i<n;i++){
			for(int j=0;j<250000;j++){
				for(int k=0;k<=nd[i].val*nd[i].count;k+=nd[i].val){
					c2[j+k]+=c1[j];
				}
			}
			for(int j=0;j<250000;j++){
				c1[j]=c2[j];
				c2[j]=0;
			}
		}
		int max=999999,res;
		for(int i=0;i<250000;i++){
			if(c1[i]!=0&&max>abs(sum/2-i)){
				max=sum/2-i;
				res=i;
			}
		}
		int res1=sum-res;
		if(res<res1){
			int tmp=res;
			res=res1;
			res1=tmp;
		}
		printf("%d %d\n",res,res1);
	}
	return 0;
}

你可能感兴趣的:(c,ini)