zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    c#FileStream文件读写(转)
    mvc Razor 视图中找不到 ViewBag的定义
    JS正则表达式验证账号、手机号、电话和邮箱
    jquery each循环,
    $.grep(array, callback, [invert])过滤,常用
    arguments 对象
    有关Select option 元素
    MVC零基础学习整理(一)
    根据年月日算出当前日期是星期几
    C# winfrom 模拟ftp文件管理
  • 原文地址:https://www.cnblogs.com/war1111/p/12531532.html
Copyright © 2011-2022 走看看