[杂题 背包DP] Codeforces 793E Tinkoff Challenge - Elimination Round E. Problem of offices

74 篇文章 0 订阅

因为都经过根 那么只要考虑根的那么些子树就好了
然后要求 a-b之间是n/2个点 c-d之间是n/2个点
四个点的顺序是 a-c-b-d 或 a-d-b-c
那么背包做一下就好了

If solution of both knapsacks exists, then answer is «YES», otherwise «NO». We can always order items from both knapsacks in needed way. Exactly, all subtrees that are present only in solution of a-b knapsack we place on path between a and c, subtrees that are present in solutions of both knapsacks we place between c and b, subtrees that are present only in solution of c-d knapsack we place between b and d, and subtrees that aren’t present in any solutions we place between d and a.

ps.题解下面的评论里提及了优化方法

这里写图片描述

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<bitset>
using namespace std;

#define read(x) scanf("%d",&(x))

const int N=5005;

struct edge{
  int u,v,next;
}G[N];
int head[N],inum;
inline void add(int u,int v,int p){
  G[p].u=u; G[p].v=v; G[p].next=head[u]; head[u]=p; 
}
#define V G[p].v

int n;
int a,b,c,d;
int A,B,C,D;
int size[N],tot;
int vst[N],pnt;

inline void dfs(int u,int fa,int z){
  for (int p=head[u];p;p=G[p].next)
    if (V!=fa)
      dfs(V,u,z);
  if (!head[u]){
    size[z]++; tot++;
    if (u==a) A=z,vst[z]=1;
    if (u==b) B=z,vst[z]=1;
    if (u==c) C=z,vst[z]=1;
    if (u==d) D=z,vst[z]=1;
  }
}

bitset<N> t,ab,cd;

int main(){
  int x;
  freopen("t.in","r",stdin);
  freopen("t.out","w",stdout);
  read(n); read(a); read(b); read(c); read(d);
  for (int i=2;i<=n;i++) read(x),add(x,i,++inum);
  t[0]=1;
  for (int p=head[1];p;p=G[p].next){
    ++pnt;
    dfs(V,1,pnt);
    if (!vst[pnt]) t|=t<<size[pnt];
  }
  if (tot&1) return printf("NO\n"),0;
  ab=t;
  for (int i=0;i<size[A];i++)
    ab|=ab<<i;
  for (int i=0;i<size[B];i++)
    ab|=ab<<i;

  cd=t;
  for (int i=0;i<size[C];i++)
    cd|=cd<<i;
  for (int i=0;i<size[D];i++)
    cd|=cd<<i;

  if ((tot/2-1-size[C]>=0 && ab[tot/2-1-size[C]] && tot/2-1-size[B]>=0 && cd[tot/2-1-size[B]]) || (tot/2-1-size[D]>=0 && ab[tot/2-1-size[D]] && tot/2-1-size[B]>=0 && cd[tot/2-1-size[B]]))
    printf("YES\n");
  else
    printf("NO\n");
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值