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;
}
相关推荐
SupL!19 分钟前
LoftQ原理
算法
Navigator_Z2 小时前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟2 小时前
力扣100——双指针
算法·leetcode
明志数科3 小时前
具身智能真机采集工程实践:5类高频失效模式与规避清单
人工智能·算法·机器学习
CSDN_RTKLIB3 小时前
空间哈希与拓扑缓存
算法
大熊背5 小时前
IspPipeline色相旋转模块实现
人工智能·算法·计算机视觉
爱学习的小白柏5 小时前
同城双活的核心不是双活,是逼着数据别出机房
大数据·人工智能·算法·langchain·ai编程
鹿角片ljp5 小时前
LeetCode 31:下一个排列|右找小,右找大,交换,右反转
java·数据结构·算法
橘子汽水1686 小时前
Leetcode 198,118打家劫舍,杨辉三角
算法·leetcode
LuminousCPP6 小时前
数据结构-排序(三):快速排序进阶|挖坑法、双指针交换与手动栈非递归实现
c语言·数据结构·笔记·算法·排序算法