HDU-2586 How far away?
There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.InputFirst line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.OutputFor each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.Sample Input2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1Sample Output10 25 100 100
1 #include<iostream> 2 #include<stdio.h> 3 #include<vector> 4 #include<algorithm> 5 #include<string.h> 6 using namespace std; 7 int ans[250],vis[40500]; 8 vector< pair <int ,int > > vec[40500]; 9 vector <pair <int ,int > > query[40500]; 10 struct Node{ 11 int f; 12 int len; 13 } pre[40500]; 14 Node Find(int x) 15 { 16 if(pre[x].f==x) 17 { 18 return pre[x]; 19 } 20 else 21 { 22 Node now; 23 now=Find(pre[x].f); 24 pre[x].len+=now.len; 25 pre[x].f=now.f; 26 return pre[x]; 27 } 28 } 29 int dfs(int u,int fa,int length) 30 { 31 pre[u].f=u; 32 pre[u].len=0; 33 vis[u]=1; 34 for(int i=0;i<vec[u].size();i++) 35 { 36 int v=vec[u][i].first; 37 int len=vec[u][i].second; 38 if(v==fa) continue; 39 dfs(v,u,len); 40 } 41 for(int i=0;i<query[u].size();i++) 42 { 43 int v=query[u][i].first; 44 int id=query[u][i].second; 45 if(vis[v]==1) 46 { 47 ans[id]=Find(v).len+Find(u).len; 48 } 49 } 50 pre[u].f=fa; 51 pre[u].len+=length; 52 } 53 int main() 54 { 55 int T; 56 cin>>T; 57 while(T--) 58 { 59 int n,q,x,y,k; 60 cin>>n>>q; 61 for(int i=0;i<n-1;i++) 62 { 63 cin>>x>>y>>k; 64 vec[x].push_back({y,k}); 65 vec[y].push_back({x,k}); 66 vis[y]=1; 67 } 68 for(int i=0;i<q;i++) 69 { 70 cin>>x>>y; 71 query[x].push_back({y,i}); 72 query[y].push_back({x,i}); 73 } 74 for(int i=1;i<=n;i++) 75 { 76 if(vis[i]==0) 77 { 78 dfs(i,i,0); 79 break; 80 } 81 } 82 for(int i=0;i<q;i++) 83 cout<<ans[i]<<endl; 84 for(int i=0;i<=n;i++) 85 { 86 vec[i].clear(); 87 query[i].clear(); 88 } 89 memset(pre,0,sizeof(pre)); 90 memset(vis,0,sizeof(vis)); 91 } 92 return 0; 93 }