HDU 1709 The Balance

//将砝码质量分为1 2 4 -1 -2 -4就能够用母函数来做了
//思想是相同的
#include<iostream>
using namespace std;

int c1[10005];
int c2[10005];
int n,sum,res;
int weight[105];

int main(){
	while(scanf("%d",&n)!=EOF){
		res=sum=0;
		for(int i=0;i<n;i++){
			scanf("%d",&weight[i]);	
			sum+=weight[i];
			weight[n+i]=-weight[i];
		}
		memset(c1,0,sizeof(c1));
		memset(c2,0,sizeof(c2));
		for(int i=0;i<=weight[0];i+=weight[0])
			c1[i]=1;
		for(int i=1;i<2*n;i++){
			for(int j=0;j<10005;j++){
				if(i<=n-1){
					for(int k=0;k<=weight[i];k+=weight[i]){
							c2[j+k]+=c1[j];
					}
				}else{
					for(int k=weight[i];k<=0;k+=-weight[i]){
						if(j+k>=0){
							c2[j+k]+=c1[j];
						}
					}
				}
			}
			for(int j=0;j<10005;j++){
					c1[j]=c2[j];
					c2[j]=0;
			}
		}
		//==================================output
		for(int i=0;i<=sum;i++){
			if(c1[i]==0){
				res++;
			}
		}
		//=====================================
		bool flag=false;
		printf("%d\n",res);
		if(res!=0){
			for(int i=0;i<=sum;i++){
				if(c1[i]==0&&flag==false){
					printf("%d",i);
					flag=true;
				}
				else if(c1[i]==0&&flag){
					printf(" %d",i);
				}
			}
			printf("\n");
		}
	}	
	return 0;
}

你可能感兴趣的:(HDU 1709 The Balance)