AcWing1171. 距离(lca&&tarjan)

输入样例1:

复制代码
2 2 
1 2 100 
1 2 
2 1

输出样例1:

复制代码
100
100

输入样例2:

复制代码
3 2
1 2 10
3 1 15
1 2
3 2

输出样例2:

复制代码
10
25
cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+5;
int n,m,x,y,k,res[N];
int vis[N];
int dis[N];
int p[N];
vector<pair<int,int>>query[N],e[N];

void dfs(int u,int fa){
	for(auto it:e[u]){
		int to=it.first;
		if(to==fa) continue;
		dis[to]=dis[u]+it.second;
		dfs(to,u);
	}
}
int find(int x){
	if(p[x]!=x) p[x]=find(p[x]);
	return p[x];
}
void tarjan(int u){
	vis[u]=1;
	for(auto it:e[u]){
		int to=it.first;
		if(!vis[to]){
			tarjan(to);
			p[to]=u;
		}
	}
	for(auto it:query[u]){
		int y=it.first;
		int id=it.second;
		if(vis[y]==2){
			int anc=find(y);
			res[id]=dis[u]+dis[y]-dis[anc]*2;
		}
	}
	vis[u]=2;
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<n-1;i++){
		scanf("%d%d%d",&x,&y,&k);
		e[x].push_back({y,k});
		e[y].push_back({x,k});
	}
	for(int i=0;i<m;i++){
		scanf("%d%d",&x,&y);
		if(x!=y){
			query[x].push_back({y,i});
			query[y].push_back({x,i});
		}
	}
	for(int i=1;i<=n;i++) p[i]=i;
	dfs(1,-1);
	tarjan(1);
	for(int i=0;i<m;i++) printf("%d\n",res[i]);
	return 0;
}
相关推荐
伊玛目的门徒30 分钟前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry1 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵2 小时前
【无标题】
数据结构·算法
Kx_Triumphs4 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎4 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀5 小时前
约瑟夫环问题
算法
科技大视界7 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴7 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe7 小时前
算法滑动窗口
数据结构·算法