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;
}
相关推荐
AiXed2 分钟前
PC微信协议之nid算法
python·网络协议·算法·微信
谈笑也风生1 小时前
经典算法题之子集(四)
算法
mit6.8241 小时前
划分dp+滑窗+前缀和|deque优化
算法
Zach_yuan2 小时前
算法1111
算法
不穿格子的程序员2 小时前
从零开始刷算法——二分-搜索旋转排序数组
数据结构·算法
做怪小疯子2 小时前
LeetCode 热题 100——哈希——最长连续序列
算法·leetcode·哈希算法
做怪小疯子3 小时前
LeetCode 热题 100——双指针——三数之和
算法·leetcode·职场和发展
高山上有一只小老虎3 小时前
等差数列前n项的和
java·算法
sin_hielo3 小时前
leetcode 2536
数据结构·算法·leetcode
flashlight_hi3 小时前
LeetCode 分类刷题:203. 移除链表元素
算法·leetcode·链表