Distance in the Tree
Time limit: 1.0 second
Memory limit: 64 MB
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 u, v, w, 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+10; const int dis[4][2]={{0,1},{-1,0},{0,-1},{1,0}}; using namespace std; ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);} ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p;p=p*p;q>>=1;}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!=-1)q[now]=q[pre]+gao; for(int i=0;i<a[now].size();i++) { if(a[now][i]!=pre) { dfs(a[now][i],now,len[now][i]); } } } void dfs1(int now) { vis[now]=1; for(int i=0;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]]-2*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,1,n)p[i]=i; rep(i,1,n-1) { 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,1,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(1,-1,-1); dfs1(1); rep(i,1,t)printf("%d ",ans[i]); //system("Pause"); return 0; }