https://codeforces.com/problemset/problem/1304/E

https://codeforces.com/problemset/problem/1304/E
用lca求树上距离
只有3种情况
a->b
a->x+x->y+y->b
a->y+y->x+x->b
因为距离过长就可以来回走,所以k-len得是偶数

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(int i=a;i<=b;++i)

using namespace std;

int n,m,s,x,y,a,b,k;
int f[N][21],deep[N];
bool flag;
void in(int &x){
    int y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(int x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

struct node{
    int n;
    node *next;
}*e[N];

void push(int x,int y){
    node *p;
    p=new node();
    p->n=y;
    if(e[x]==0) e[x]=p;
    else{
        p->next=e[x]->next;
        e[x]->next=p;
    }
}

void build(int now){
    deep[now]=deep[f[now][0]]+1;
    for(int i=1;(1<<i)<=deep[now];i++) f[now][i]=f[f[now][i-1]][i-1];
    for(node *i=e[now];i!=NULL;i=i->next){
        if(i->n!=f[now][0]){
            f[i->n][0]=now;
            build(i->n);
        }
    }
} 

int query(int x,int y){
    if(deep[x]<deep[y]) swap(x,y);
    int c=deep[x]-deep[y];
    for(int i=0;i<=log2(c);i++) if((1<<i)&c) x=f[x][i];
    if(x==y) return x;
    for(int i=log2(deep[x]);i>=0;i--){
        if(f[x][i]!=f[y][i]){
            x=f[x][i];
            y=f[y][i];
        }
    }
    return f[x][0];
}

int l(int x,int y){
    return deep[x]+deep[y]-2*deep[query(x,y)];
}

int main(){ 
      in(n);
      For(i,1,n-1){
        in(x),in(y);
        push(x,y);
        push(y,x);
    }
    f[1][0]=1;
    build(1);
    in(m);
    for(int i=1;i<=m;i++){
        flag=0;
        in(x),in(y);in(a);in(b);in(k);
        if(l(a,b)<=k&&(k-l(a,b))%2==0) flag=1;
        else if((l(a,x)+1+l(y,b))<=k&&(k-(l(a,x)+1+l(y,b)))%2==0) flag=1;
        else if((l(a,y)+1+l(x,b))<=k&&(k-(l(a,y)+1+l(x,b)))%2==0) flag=1;
        if(flag) puts("YES");
        else puts("NO");
    }
  return 0;
}

 

posted @ 2020-03-20 14:27  WeiAR  阅读(366)  评论(0编辑  收藏  举报