题目链接

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})

代码

#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;
}