# 子集和【省选模拟赛】

## 反向背包DP

Posted by yjjr's blog on March 13, 2018 1 minutes to read

# 分析

S内有负数的时候，考虑下Si中最大的数X和次大的数Y，S内一定存在一个数的绝对值=X-Y

F[i][j]表示前i个数，是否有若干个数的正和为j

$j=\sum_{k=1}^i S[i]*(0/1)$

# code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
#include<set>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#define reg(x) for(int i=last[x];i;i=e[i].next)
#define lson (x<<1)
#define rson (x<<1|1)
#define mid ((l+r)>>1)
#define pi acos(-1)
#define mp make_pair
#define pb push_back
#define pa pair<int,int>
#define fi first
#define se second
#define lowbit(x) ((x)&(-x))
using namespace std;
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline ll getgcd(ll x,ll y){return !x?y:getgcd(y%x,x);}
inline ll getlcm(ll x,ll y){return x/getgcd(x,y)*y;}
inline ll qpow(int x,int y,int p){
ll re=1;
while(y){
if(y&1)re=(re*x)%p;
y>>=1,x=(x*x)%p;
}
return re;
}
const int maxn=1e4+6,S=66;
struct node{ll s,p,d;}a[maxn];
int n,cnt=0,f[S][maxn],now=0,tmp;ll mn,v[maxn],ans[S];
inline bool cmpa(const node &s1,const node &s2){return s1.s<s2.s;}
void get_element()
{
ll d=a[n].s-a[n-1].s;int pos=0;ans[++cnt]=d;
dep(i,n,1){
int p=lower_bound(a+1,a+n+1,(node){a[i].s+ans[cnt],0,0},cmpa)-a;
if(a[p].s!=a[i].s+ans[cnt])continue;
ll b=min(a[i].p-a[i].d,a[p].p-a[p].d);
a[i].d+=b,a[p].p-=b;
}
rep(i,1,n)
if(a[i].d)a[++pos]=(node){a[i].s,a[i].d,0};
n=pos;
}
void remove_zero(){
ll gcd=a[1].p;
rep(i,2,n)gcd=getgcd(gcd,a[i].p);
while(gcd%2==0){
rep(i,1,n)a[i].p/=2;
ans[++cnt]=0;gcd/=2;
}
}
void work()
{
int tmp=n;remove_zero();
while(n!=1)get_element();n=tmp;
sort(ans+1,ans+cnt+1);
f[0][lower_bound(v+1,v+n+1,0)-v]=now;
rep(i,1,cnt){
rep(j,1,n)if(f[i-1][j]==now)f[i][j]=now;
dep(j,n,1){
if(v[j]<ans[i])break;
int p=lower_bound(v+1,v+n+1,v[j]-ans[i])-v;
if(v[p]==v[j]-ans[i]&&f[i-1][p]==now)f[i][j]=now;
}
}
for(int i=cnt,p=lower_bound(v+1,v+n+1,mn)-v;i>=1;i--){
ll y=v[p]-ans[i];
int t=lower_bound(v+1,v+n+1,y)-v;
if(v[t]==y&&f[i-1][t]==now)ans[i]=-ans[i],p=t;
}
sort(ans+1,ans+cnt+1);
rep(i,1,cnt)printf(" %d",ans[i]);printf("\n");
}
int main()
{
rep(K,1,T){
mn=cnt=0;++now;mem(a,0);