背景:
在
l
u
o
g
u
luogu
luogu的
s
p
o
j
spoj
spoj的账户上提交会
T
L
E
TLE
TLE,当然不是代码的问题。
还是在这道提交吧,这一题可以
A
C
AC
AC。
题目传送门:
https://www.luogu.org/problemnew/show/P3067
题意:
在
n
n
n个数中任意选出一些数分为两组,求分成两组相等的方案数。
思路:
显然有
3
n
3^n
3n的暴力做法。
但是过不了啊。
3
n
2
3^{\frac{n}{2}}
32n的做法好像可以接受。
那就折半搜索吧。
最后排序后两个指针统计答案。
注意:开一个标记数组记录当前方案数是否出现过,最后答案减
1
1
1(空集的情况)。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[50],t[2];
struct node{int x,tmp;} sum[2][1<<21];
bool bz[1<<21];
int n,ans=0;
void dfs(int id,int l,int r,int x,int tmp)
{
if(l==r+1)
{
sum[id][++t[id]]=(node){x,tmp};
return;
}
dfs(id,l+1,r,x,tmp);
dfs(id,l+1,r,x+a[l],tmp|(1<<(l-1)));
dfs(id,l+1,r,x-a[l],tmp|(1<<(l-1)));
}
bool cmp1(node x,node y)
{
return x.x<y.x;
}
bool cmp2(node x,node y)
{
return x.x>y.x;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
dfs(0,1,n/2,0,0);
dfs(1,n/2+1,n,0,0);
sort(sum[0]+1,sum[0]+t[0]+1,cmp1);
sort(sum[1]+1,sum[1]+t[1]+1,cmp2);
int l=1,r=1;
while(l<=t[0]&&r<=t[1])
{
while(r<=t[1]&&sum[0][l].x+sum[1][r].x>0) r++;
int pos=r;
while(r<=t[1]&&!(sum[0][l].x+sum[1][r].x))
{
if(!bz[sum[0][l].tmp|sum[1][r].tmp]) bz[sum[0][l].tmp|sum[1][r].tmp]=true,ans++;
r++;
}
if(l<t[0]&&sum[0][l].x==sum[0][l+1].x) r=pos;
l++;
}
printf("%d",ans-1);
}