BZOJ 2679 [Usaco2012 Open]Balanced Cow Subsets

题目链接

https://www.lydsy.com/JudgeOnline/problem.php?id=2679

题解

meet in the middle,枚举左边放在第一个集合,第二个集合还是不放,记录左边能得到的差值和左边的选取状态,右边同理,最后two-pointer扫一下,记录选取状态有没有被考虑过,时间复杂度O(2×3n/2)O(2\times 3^{n/2})O(2×3n/2)

代码

#include <cstdio>
#include <algorithm>

int read()
{
  int x=0,f=1;
  char ch=getchar();
  while((ch<'0')||(ch>'9'))
    {
      if(ch=='-')
        {
          f=-f;
        }
      ch=getchar();
    }
  while((ch>='0')&&(ch<='9'))
    {
      x=x*10+ch-'0';
      ch=getchar();
    }
  return x*f;
}

const int maxn=20;
const int maxk=59049;
const int maxs=1<<maxn;

struct data
{
  int v,con;

  bool operator <(const data &other) const
  {
    if(v==other.v)
      {
        return con<other.con;
      }
    return v<other.v;
  }
};

data tmp[maxk+10],f[maxk+10],g[maxk+10];
int tot,totf,totg,op[maxn+2],n,v[maxn+2],vis[maxs+10],ans;

int search(int x,int mx)
{
  if(x>mx)
    {
      int last=0,con=0;
      for(int i=1; i<=n; ++i)
        {
          last+=v[i]*op[i];
          if(op[i])
            {
              con|=1<<(i-1);
            }
        }
      tmp[++tot].v=last;
      tmp[tot].con=con;
      return 0;
    }
  for(int i=-1; i<=1; ++i)
    {
      op[x]=i;
      search(x+1,mx);
    }
  return 0;
}

int main()
{
  n=read();
  for(int i=1; i<=n; ++i)
    {
      v[i]=read();
    }
  if(n==1)
    {
      puts("1");
      return 0;
    }
  search(1,n/2);
  std::sort(tmp+1,tmp+tot+1);
  for(int i=1; i<=tot; ++i)
    {
      f[i]=tmp[i];
    }
  totf=tot;
  tot=0;
  for(int i=1; i<=n/2; ++i)
    {
      op[i]=0;
    }
  search(n/2+1,n);
  std::sort(tmp+1,tmp+tot+1);
  for(int i=1; i<=tot; ++i)
    {
      g[i]=tmp[i];
    }
  totg=tot;
  int nowf=1,nowg=totg;
  while((nowf<=totf)&&(nowg>0))
    {
      while((nowg>0)&&(f[nowf].v+g[nowg].v>0))
        {
          --nowg;
        }
      if(f[nowf].v+g[nowg].v==0)
        {
          int pastf=nowf,pastg=nowg;
          while((nowf<totf)&&(f[nowf].v==f[nowf+1].v))
            {
              ++nowf;
            }
          while((nowg>1)&&(g[nowg].v==g[nowg-1].v))
            {
              --nowg;
            }
          for(int i=pastf; i<=nowf; ++i)
            {
              for(int j=nowg; j<=pastg; ++j)
                {
                  if(!vis[f[i].con|g[j].con])
                    {
                      vis[f[i].con|g[j].con]=1;
                      ++ans;
                    }
                }
            }
        }
      ++nowf;
    }
  printf("%d\n",ans-1);
  return 0;
}

转载于:https://www.cnblogs.com/Canopus-wym/p/10376116.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值