• [模板]倍增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));
    	}
    } 
    
  • 相关阅读:
    逻辑回归与最大熵模型
    提升方法-AdaBoost
    Python中的类属性、实例属性与类方法、静态方法
    mysqldump详解
    12.python 模块使用,面向对象介绍
    11 python 内置函数
    10.函数的变量与返回值
    9. 函数的定义和参数,默认参数
    linux下iptables详解
    把linux下的yum源更换为阿里云的国内源
  • 原文地址:https://www.cnblogs.com/loi-pingxing/p/7808988.html
Copyright © 2020-2023  润新知