#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
const int maxn = 75000+ 10;
vector<int> mp[maxn],dist[maxn],u[maxn],f[maxn];
bool vis[maxn],vt[maxn];
int fa[maxn],w[maxn];
int ans[maxn];
int n;
int find(int x)
{
if(!fa[x])
return x;
return fa[x] = find(fa[x]);
}
void merge(int x,int y)
{
int f1 = find(x);
int f2 = find(y);
if(f1 != f2)
fa[f2] = f1;
}
void Tarjan(int x,int k)
{
ans[x] = k;
for(int i = 0; i<(int)mp[x].size(); i++)
{
if(!vt[mp[x][i]])
{
int v = mp[x][i];
vt[v] = true;
Tarjan(v,k+dist[x][i]);
merge(x,v);
}
}
vis[x] = true;
for(int i = 0; i<(int)u[x].size(); i++)
{
if(vis[u[x][i]])
w[f[x][i]] = ans[x] + ans[u[x][i]] - 2*ans[find(u[x][i])];
}
}
int main()
{
int a,b,c,m;
scanf("%d",&n);
for(int i = 1; i<=n-1; i++)
{
scanf("%d %d %d",&a,&b,&c);
a++,b++;
mp[a].push_back(b),dist[a].push_back(c);
mp[b].push_back(a),dist[b].push_back(c);
}
scanf("%d",&m);
for(int i = 1; i<=m; i++)
{
scanf("%d %d",&a,&b);
a++,b++;
u[a].push_back(b),u[b].push_back(a);
f[a].push_back(i),f[b].push_back(i);
}
vt[1] = true;
Tarjan(1,0);
for(int i = 1; i<=m; i++)
printf("%d\n",w[i]);
return 0;
}
CODE[VS]2370 小机房的树
最新推荐文章于 2018-10-30 22:08:23 发布