zoukankan      html  css  js  c++  java
  • 关于Tarjan(3)——离线LCA

    LCA(最近公共祖先),指对于一棵树上任意两个节点往上走最早都能到达的节点。

    求LCA有两种方法,一种是倍增,另一种则是Tarjan。。。。。。。。

    Tarjan巧妙利用并查集的思想;

    这里的Tarjan是离线算法
    先Tarjan下去;
    首先有fa[NUM]=num; 
    回溯时将子节点的fa变为num
    如果对于num的询问中另一个点已经访问;
    那他们的LCA为另一个点的find(fa)
    原因:&&一个点与另一个点都位于以他们的LCA为根节点的子树中;
    如果没有相关点的信息,只说明在该节点的上方,故回溯时把fa的变为父节点; 
    这里的find是并查集中的代表元素。。。。。
    再处理各种询问 

    另外,两点距离为dis[x]+dis[y]-2*dis[LCA(x,y)]; 

    附上原题代码及地址http://codevs.cn/problem/2370/

    #include<iostream>
    #include<cstdlib>
    #include<cstdio>
    #define N 50001
    using namespace std;
    struct data{
    	int to,nxt,ans;
    }ask[75001*2];
    struct node{
    	int nxt,to,w;
    }edge[N*2+1];
    int tot,tot1,n,m;
    bool vis[N];
    int dis[N],fa[N];
    int head[N],head1[75001*2];
    int find(int x){if(fa[x]!=x)fa[x]=find(fa[x]);return fa[x];}
    void add1(int x,int y){
    	ask[++tot1].nxt=head1[x];
    	ask[tot1].to=y;
    	head1[x]=tot1;
    }
    void dfs(int num,int hehe){
    	dis[num]=hehe;
    	for(int i=head[num];i;i=edge[i].nxt)
    	if(!dis[edge[i].to]&&edge[i].to){
    		int to=edge[i].to;
    		dfs(to,hehe+edge[i].w);
    	}
    }
    void Tarjan_LCA_haha(int t){
    	vis[t]=true;
    	fa[t]=t;
    	for(int i=head[t];i;i=edge[i].nxt)
    	if(!fa[edge[i].to]&&edge[i].to){
    		int to=edge[i].to;
    		Tarjan_LCA_haha(to);
    		fa[to]=t;
    	}
    	for(int i=head1[t];i;i=ask[i].nxt)
    	if(vis[ask[i].to])
    	ask[i].ans=dis[ask[i].to]+dis[t]-2*dis[find(ask[i].to)];
    }
    int main(){
    	scanf("%d",&n);
    	for(int i=1;i<n;++i){
    		int a,b,c;
    		scanf("%d%d%d",&a,&b,&c);
    		edge[++tot].nxt=head[a];
    		head[a]=tot;
    		edge[tot].w=c;
    		edge[tot].to=b;
    		edge[++tot].nxt=head[b];
    		head[b]=tot;
    		edge[tot].w=c;
    		edge[tot].to=a;
    	}
    	scanf("%d",&m);
    	for(int i=1;i<=m;++i){
    			int a,b;
    			scanf("%d%d",&a,&b);
    			add1(a,b);
    			add1(b,a);
    	}
    	dfs(0,0);
    	Tarjan_LCA_haha(0);
    	for(int i=1;i<=2*m;i+=2)
    	if(ask[i].ans)printf("%d
    ",ask[i].ans);
    	else printf("%d
    ",ask[i+1].ans);
    	return 0;
    }


  • 相关阅读:
    Codeforces 631A Interview【模拟水题】
    Codeforces 651E Table Compression【并查集】
    Codeforces 651D Image Preview【二分+枚举】
    Codeforces 651C Watchmen【模拟】
    Codeforces 651B Beautiful Paintings【贪心】
    18.06.26 16年期末10:游览规划
    18.06.25 POJ4129 16年期末09:变换的迷宫
    18.06.25 POJ4150 16年期末07:上机
    18.06.25 16年期末06 42点
    18.06.25 16年期末01-05集合
  • 原文地址:https://www.cnblogs.com/zzmmm/p/6501180.html
Copyright © 2011-2022 走看看