hdu 1709 The Balance (母函数)
http://acm.hdu.edu.cn/showproblem.php?pid=1709 题意:有n个砝码,第i个的重量为w[i],问从1到sum(所有砝码的重量之和)那些重量无法称量。(所有质量都是整数) 思路:母函数。 一个砝码可以看做有三种状态,放,放左边(+),放右边(-)
需要注意的一点是放在右边(-)的时候,可能是j-w[i],也可能是w[i]-j
/* ***********************************************
Author :111qqz
Created Time :2016年02月26日 星期五 17时57分05秒
File Name :code/hdu/1709.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
19#define pi pair < int ,int >
20#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E4+7;
7int a[N],tmp[N];
8int n;
9int w[N];
10int ans[N];
11int main()
12{
13 #ifndef ONLINE_JUDGE
14 freopen("code/in.txt","r",stdin);
15 #endif
1 while (~scanf("%d",&n))
2 {
3 for ( int i = 1 ; i <= n ; i++) scanf("%d",&w[i]);
4 // sort(w+1,w+n+1);
5 ms(ans,0);
6 ms(tmp,0);
7 ms(a,0);
8 a[0] = 1;
9 a[w[1]] = 1;
1 int cur = w[1];
2 for ( int i = 2 ; i <= n ; i++)
3 {
4 for ( int j = 0 ; j <= cur ; j++)
5 {
6 tmp[j] +=a[j];
7 tmp[j+w[i]]+=a[j];
8 if (j-w[i]>0) tmp[j-w[i]] +=a[j];
9 if (w[i]-j>0) tmp[w[i]-j] +=a[j]; //一开始忘记考虑,wa了好多次
}
cur += w[i];
1 for ( int j = 0 ; j <= cur ; j++)
2 {
3 // cout<<"j:"<<j<<" tmp[j]:"<<tmp[j]<<endl;
4 a[j] = tmp[j];
5 tmp[j] = 0 ;
6 }
1 }
2 int cnt = 0 ;
3 for ( int i = 1 ; i <= cur ; i++)
4 {
5 if (a[i]==0) ans[++cnt] = i;
6 }
1 printf("%d\n",cnt);
2 if (cnt==0) continue;
3 for ( int i = 1 ; i <= cnt-1 ; i++) printf("%d ",ans[i]);
printf("%d\n",ans[cnt]);
}
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}