因为都经过根 那么只要考虑根的那么些子树就好了
然后要求 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;
}