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;
}
相关推荐
小赵起名困难户1 小时前
蓝桥杯备赛1-2合法日期
算法
shichaog1 小时前
腿足机器人之八- 腿足机器人动力学
算法·机器人
悄悄敲敲敲3 小时前
C++:dfs习题四则
c++·算法·深度优先
牛大了20234 小时前
[LeetCode力扣hot100]-二叉树相关手撕题
算法·leetcode·职场和发展
ll7788114 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
德先生&赛先生5 小时前
LeetCode-633. 平方数之和
数据结构·算法·leetcode
mengyoufengyu7 小时前
算法12-贪心算法
python·算法·贪心算法
SharkWeek.7 小时前
【力扣Hot 100】链表4
算法·leetcode·链表
小白菜又菜7 小时前
Leetcode 518. Coin Change II
算法·leetcode
HUT_Tyne2657 小时前
力扣hot100第四天
算法·leetcode·职场和发展