• p3398 仓鼠找sugar (LCA+讨论)


    分情况讨论,结果是两条路径有公共点时,深度大的LCA在另一条路径上且另一条路径的两个端点至少其中一个的与深度大的LCA的LCA为那个深度大的LCA

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    int u[501000*2],v[500100*2],fir[500000+10],nxt[501000*2],cnt,dfs_clock=0,top[500010],dfn[500100],fa[500100],dep[500100],sz[500100],heason[500100];
    void addedge(int ui,int vi){
        ++cnt;
        u[cnt]=ui;
        v[cnt]=vi;
        nxt[cnt]=fir[ui];
        fir[ui]=cnt;	
    }
    void dfs1(int u,int f){
        fa[u]=f;
        sz[u]=1;
        int maxsz=-1;
        for(int i=fir[u];i;i=nxt[i]){
            if(v[i]==f)
                continue;
            dep[v[i]]=dep[u]+1;
            dfs1(v[i],u);
            sz[u]+=sz[v[i]];
            if(sz[v[i]]>maxsz){
                maxsz=sz[v[i]];
                heason[u]=v[i];
            }
        }
    }
    void dfs2(int u,int topf){
        dfn[u]=++dfs_clock;
        top[u]=topf;
        if(!heason[u])
            return;
        dfs2(heason[u],topf);
        for(int i=fir[u];i;i=nxt[i]){
            if(v[i]==fa[u])
                continue;
            if(v[i]!=heason[u])
                dfs2(v[i],v[i]);
        }
    }
    int lca(int x,int y){
        while(top[x]!=top[y])
            (dep[top[x]]<dep[top[y]])?y=fa[top[y]]:x=fa[top[x]];
        return (dep[x]<dep[y])?x:y;
    }
    int ison(int x,int y,int a,int b){
        int Lca1=lca(x,y),Lca2=lca(a,b);
        if(dep[Lca1]<dep[Lca2])
            swap(Lca2,Lca1),swap(x,a),swap(y,b);
        return (lca(Lca1,a)==Lca1||lca(Lca1,b)==Lca1);
    }
    int main(){
        int n,m;
        scanf("%d %d",&n,&m);
        for(int i=1;i<n;i++){
            int a,b;
            scanf("%d %d",&a,&b);
            addedge(a,b);
            addedge(b,a);
        }
        dfs1(1,0);
        dfs2(1,1);
        for(int i=1;i<=m;i++){
            int x,y,a,b;
            scanf("%d %d %d %d",&x,&y,&a,&b);
            printf("%c
    ",(ison(x,y,a,b))?'Y':'N');
        }
        return 0;
    }
    
  • 相关阅读:
    Speex for Android
    反射(高大上)、类的内置方法
    hashlib摘要算法模块,logging日志,configparser配置文件模块
    抽象类,接口类,封装,property,classmetod,statimethod
    面对对象三大特征:继承 多态(鸭子类型)(面试题)
    面向对象命名空间及组合(面试题)
    初始面向对象
    模块与包
    常用模块
    列表表达式,生成器表达式,
  • 原文地址:https://www.cnblogs.com/dreagonm/p/10011421.html
Copyright © 2020-2023  润新知