• [模板]倍增LCA


    洛谷P1967

    用倍增法,fa[i][j]表示节点i向上
    2^j步所能到大的点
    minx[i][j]表示i向上2^j步所经过的最小边

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #define LL long long
    using namespace std;
    const int MAXN = 200000 + 50;
    struct edge{
    	int f,t,v;
    }l[MAXN << 1],e[MAXN << 1];
    int n,m,q;
    int x,y,z;
    int head[MAXN],next[MAXN << 1],tot,rank[MAXN],f[MAXN];
    void init(int n){
    	for(int i = 1;i <= n;i ++){
    		f[i] = i;
    		head[i] = -1;
    	}
    }
    int find(int x){
    	return f[x] == x ? x : f[x] = find(f[x]);
    }
    void build(int f,int t,int v){
    	l[++tot] = (edge){f,t,v};
    	next[tot] = head[f];
    	head[f] = tot;
    }
    void merge(int a,int b){
    	a = find(a);
    	b = find(b);
    	if(rank[a] < rank[b])swap(a,b);
    	f[b] = a;
    	if(rank[a] == rank[b])rank[a] ++;
    }
    bool cmp(edge a,edge b){
    	return a.v > b.v;
    }
    bool same(int a,int b){
    	return find(a) == find(b);
    }
    void smt(){
    	for(int i = 1;i <= m;i ++){
    		if(!same(e[i].f,e[i].t)){
    			merge(e[i].f,e[i].t);
    			build(e[i].f,e[i].t,e[i].v);
    			build(e[i].t,e[i].f,e[i].v);
    		}
    	}
    }
    int fa[MAXN][30],minx[MAXN][30],deep[MAXN];
    void dfs(int p,int u){
    	for(int i = 1;i <= 29;i ++){
    		fa[u][i] = fa[fa[u][i - 1]][i - 1];
    		minx[u][i] = min(minx[u][i - 1],minx[fa[u][i - 1]][i - 1]);
    	}
    	for(int i = head[u];i != -1;i = next[i]){
    		int t = l[i].t;
    		if(t == p)continue;
    		deep[t] = deep[u] + 1;
    		minx[t][0] = l[i].v;
    		fa[t][0] = u;
    		dfs(u,t);
    	}
    }
    int LCA(int a,int b){
    	if(deep[a] < deep[b])swap(a,b);
    	int ans = 2147483647;
    	int t = deep[a] - deep[b];
    	for(int i = 0;i <= 25;i ++){
    		if(t & (1 << i)){
    			ans = min(ans,minx[a][i]);
    			a = fa[a][i];
    		}
    	}
    	if(a == b)return ans;
    	for(int i = 25;i >= 0;i --){
    		if(fa[a][i] != fa[b][i]){
    			ans = min(ans,min(minx[a][i],minx[b][i]));
    			a = fa[a][i];
    			b = fa[b][i];
    		}
    	}
    	ans = min(ans,min(minx[a][0],minx[b][0]));
    	return ans;
    }
    
    int main(){
    	scanf("%d%d",&n,&m);
    	init(n);
    	for(int i = 1;i <= m;i ++){
    		scanf("%d%d%d",&x,&y,&z);
    		e[i] = (edge){x,y,z};
    	}
    	sort(e + 1,e + m + 1,cmp);
    	smt();
    	dfs(1,1);
    	scanf("%d",&q);
    	for(int i = 1;i <= q;i ++){
    		scanf("%d%d",&x,&y);
    		if(!same(x,y))printf("-1
    ");
    		else printf("%d
    ",LCA(x,y));
    	}
    } 
    
  • 相关阅读:
    vue-cli脚手架工具构建&初始化vue项目
    2020/05/17 Github加速-DNS配置
    同时将本地git仓库提交到gitee和github
    git远程仓库在本地看不到&push 到远程仓库失败的解决方案
    stylus的使用-变量和函数
    webpack使用4-HRM热替换&SourceMap&解析es语法
    webpack使用3-plugin插件的使用
    webpack使用2-常用的几个loader的使用
    webpack基本使用
    spring框架里面的注入?
  • 原文地址:https://www.cnblogs.com/loi-pingxing/p/7808988.html
Copyright © 2020-2023  润新知