折半搜索
查看原帖
折半搜索
699471
yuxiaoyu20090104楼主2023/8/12 00:06
#include<bits/stdc++.h>
#define mod 5000007
using namespace std;
int n,a[30],cnt,head[mod+2],ans;
struct Edge{int nxt,data;}e[mod+2];
void hash(int x)
{
	int hash=x%mod;
	e[++cnt].data=x;
	e[cnt].nxt=head[hash];
	head[hash]=cnt;
}
void dfs1(int res1,int res2,int step)
{
	if(step>(n>>1))
	{
		if(res1<res2)return;
		hash(res1-res2);
		return;
	}
	dfs1(res1+a[step],res2,step+1);
	dfs1(res1,res2+a[step],step+1);
	dfs1(res1,res2,step+1);
}
int find(int x)
{
	int ans1=0,hash=x%mod;
	for(int i=head[hash];i;i=e[i].nxt)
		if(e[i].data==x)
		{
			ans1++;
			cout<<x<<" ";
		}
	return ans1;
}
void dfs2(int res1,int res2,int step)
{
	if(step>n)
	{
		if(res1<res2)return;
		ans+=find(res1-res2);
		return;
	}
	dfs2(res1+a[step],res2,step+1);
	dfs2(res1,res2+a[step],step+1);
	dfs2(res1,res2,step+1);
}
int main()
{
	//freopen("P3067_2.in","r",stdin);
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	dfs1(0,0,1);
	dfs2(0,0,(n>>1)+1);
	cout<<ans-1;
	return 0;
}

测评信息 https://www.luogu.com.cn/record/120396744

2023/8/12 00:06
加载中...