您的位置:首页 > 其它

LCA Tarjan模板 HDU2586

2017-07-18 11:04 330 查看
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 40005;
typedef long long ll;
int Par[maxn], vis[maxn], dist[maxn];
vector<int> G[maxn];
vector<int> Dis[maxn];
vector<int> Gx[maxn];
vector<int> Gxnum[maxn];
int getPar (int x) {
int r = x, i = x;
while(r != Par[r])
r = Par[r];
while(i != r) {
int tmp = Par[i];
Par[i] = r;
i = tmp;
}
return r;
}
void merge (int t1, int t2) {
int f1 = getPar(t1);
int f2 = getPar(t2);
if(f1 != f2)
Par[f2] = f1;
}
struct node {
int x, y, zx;
} nod[205];
void dfs (int st) {
for(int i=0; i<G[st].size(); ++i) {
if(!vis[G[st][i]]) {
vis[G[st][i]] = 1;
dist[G[st][i]] = dist[st] + Dis[st][i];
dfs(G[st][i]);
merge(st, G[st][i]);
}
}
for(int i=0; i<Gx[st].size(); ++i) {
if(vis[Gx[st][i]])
nod[Gxnum[st][i]].zx = getPar(Gx[st][i]);
}
}
int main (void) {
ios::sync_with_stdio(false);
int T, n, m, a, b, c;
cin>>T;
while(T --) {
for(int i=0; i<maxn; ++i) {
Par[i] = i, vis[i] = dist[i] = 0;
G[i].clear(), Dis[i].clear();
Gxnum[i].clear(), Gx[i].clear();
}
cin>>n>>m;
for(int i=1; i<n; ++i) {
cin>>a>>b>>c;
G[a].push_back(b);
Dis[a].push_back(c);
G[b].push_back(a);
Dis[b].push_back(c);
}
for(int i=1; i<=m; ++i) {
cin>>a>>b;
Gx[a].push_back(b);
Gx[b].push_back(a);
nod[i].x = a, nod[i].y = b;
Gxnum[a].push_back(i);
Gxnum[b].push_back(i);
}
vis[1] = 1; dfs(1);
for(int i=1; i<=m; ++i) {
int ans = dist[nod[i].x]+dist[nod[i].y]-2*dist[nod[i].zx];
cout<<ans<<endl;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: