zoukankan      html  css  js  c++  java
  • Rooted Subtrees 题解(LCA+思维)

    题目链接

    题目思路

    看起来好难但是结论好简单

    如果(r,q)中间有(k)个点,那么答案就是(c(k,2)+n)

    题解是这么说的

    You can take any contiguous sub-segment of the path between r and p.

    至于为什么加(n) ,我感觉有点难说清楚

    如果他们两棵树取的子数的节点不同时在中间的k个点中,那么答案就是(n)

    求中间多少个点直接(LCA)即可

    代码

    #include<bits/stdc++.h>
    #define fi first
    #define se second
    #define debug printf(" I am here
    ");
    using namespace std;
    typedef long long ll;
    typedef unsigned long long ull;
    typedef pair<ll,ll> pii;
    mt19937 rnd(time(0));
    const ll INF=0x3f3f3f3f3f3f3f3f;
    const int maxn=2e5+5,inf=0x3f3f3f3f,mod=20071027;
    const double eps=1e-10;
    int n,q;
    int head[maxn],cnt;
    struct edge{
        int to,next;
    }e[maxn<<1];
    int lg[maxn],depth[maxn];
    int fa[maxn][30];
    void add(int u,int v){
        e[++cnt]={v,head[u]};
        head[u]=cnt;
    }
    void dfs(int son,int father)//把0作为最高点,且0的高度为0
    {
        fa[son][0]=father;
        depth[son]=depth[father]+1;
        for(int i=1;i<=lg[depth[son]];i++)
        {
            fa[son][i]=fa[fa[son][i-1]][i-1];//这个转移可以说是算法的核心之一
                                    //意思是son的2^i祖先等于son的2^(i-1)祖先的2^(i-1)祖先
                                        //2^i = 2^(i-1) + 2^(i-1)
        }
        for(int i=head[son];i;i=e[i].next)
        {
            if(e[i].to!=father)//相当于往下搜索
                dfs(e[i].to,son);
        }
    }
    int LCA(int x, int y){
        if(depth[x] < depth[y]) //用数学语言来说就是:不妨设x的深度 >= y的深度
            swap(x, y);
        while(depth[x] > depth[y])
            x = fa[x][lg[depth[x]-depth[y]] - 1]; //先跳到同一深度
        if(x == y)  //如果x是y的祖先,那他们的LCA肯定就是x了
            return x;
        for(int k = lg[depth[x]] - 1; k >= 0; k--) //不断向上跳(lg就是之前说的常数优化)  注意是从大到小跳
            if(fa[x][k] != fa[y][k])  //因为我们要跳到它们LCA的下面一层,所以它们肯定不相等,如果不相等就跳过去。
                x = fa[x][k], y = fa[y][k];
        return fa[x][0];  //返回父节点
    }
    signed main(){
        scanf("%d%d",&n,&q);
        for(int i = 1; i <= n; ++i) //预先算出log2(i)+1的值,用的时候直接调用就可以了
            lg[i] = lg[i-1] + (1 << lg[i-1] == i);  //看不懂的可以手推一下
        for(int i=1,u,v;i<=n-1;i++){
            scanf("%d%d",&u,&v);
            add(u,v),add(v,u);
        }
        dfs(1,0);
        for(int i=1,u,v;i<=q;i++){
            scanf("%d%d",&u,&v);
            int fa=LCA(u,v);
            int k=depth[u]-depth[fa]+depth[v]-depth[fa]+1;
            printf("%lld
    ",1ll*k*(k-1)/2+n);
        }
        return 0;
    }
    
    
    卷也卷不过,躺又躺不平
  • 相关阅读:
    leetcode| Intersection of Two Arrays II
    Spring Boot起步依赖:定制starter
    SpringBoot自动配置的魔法是怎么实现的
    Dubbo中的IoC实现
    必须知道的String知识点
    Dubbo的SPI机制
    为什么要设置HTTP timeout?
    重构代码——简单工厂模式+模板方法模式
    计算机基础——位运算
    系统间HTTP调用代码封装
  • 原文地址:https://www.cnblogs.com/hunxuewangzi/p/15167961.html
Copyright © 2011-2022 走看看