ural1471 Distance in the Tree

时间:2023-03-09 22:36:37
ural1471 Distance in the Tree

Distance in the Tree

Time limit: 1.0 second
Memory limit: 64 MB
A weighted tree is given. You must find the distance between two given nodes.

Input

The first line contains the number of nodes of the tree n (1 ≤ n ≤ 50000). The nodes are numbered from 0 to n – 1. Each of the next n – 1 lines contains three integers uvw, which correspond to an edge with weight w (0 ≤ w ≤ 1000) connecting nodes u and v. The next line contains the number of queries m (1 ≤ m ≤ 75000). In each of the next m lines there are two integers.

Output

For each query, output the distance between the nodes with the given numbers.

Sample

input output
3
1 0 1
2 0 1
3
0 1
0 2
1 2
1
1
2

分析:树上两点间距离,直接tarjan;

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#define rep(i,m,n) for(i=m;i<=n;i++)
#define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define vi vector<int>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define ll long long
#define pi acos(-1.0)
#define pii pair<int,int>
#define Lson L, mid, rt<<1
#define Rson mid+1, R, rt<<1|1
const int maxn=1e5+;
const int dis[][]={{,},{-,},{,-},{,}};
using namespace std;
ll gcd(ll p,ll q){return q==?p:gcd(q,p%q);}
ll qpow(ll p,ll q){ll f=;while(q){if(q&)f=f*p;p=p*p;q>>=;}return f;}
int n,m,k,t,p[maxn],ans[maxn],vis[maxn],q[maxn];
int find(int x)
{
return p[x]==x?x:p[x]=find(p[x]);
}
vi query[maxn],a[maxn],len[maxn],id[maxn];
void dfs(int now,int pre,int gao)
{
if(pre!=-)q[now]=q[pre]+gao;
for(int i=;i<a[now].size();i++)
{
if(a[now][i]!=pre)
{
dfs(a[now][i],now,len[now][i]);
}
}
}
void dfs1(int now)
{
vis[now]=;
for(int i=;i<query[now].size();i++)
{
if(vis[query[now][i]])
{
int fa=find(query[now][i]);
ans[id[now][i]]=q[now]+q[query[now][i]]-*q[fa];
}
}
for(int x:a[now])
{
if(!vis[x])
{
dfs1(x);
p[x]=now;
}
}
}
int main()
{
int i,j;
scanf("%d",&n);
rep(i,,n)p[i]=i;
rep(i,,n-)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
a[u].pb(v),a[v].pb(u);
len[u].pb(w),len[v].pb(w);
}
scanf("%d",&t);
rep(i,,t)
{
int a,b;
scanf("%d%d",&a,&b);
query[a].pb(b),query[b].pb(a);
id[a].pb(i),id[b].pb(i);
}
dfs(,-,-);
dfs1();
rep(i,,t)printf("%d\n",ans[i]);
//system("Pause");
return ;
}