题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2586
题目:
Problem Description
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.
Input
First 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.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.
Sample Input
2
3 2
1 2 10
3 1 15
1 2
2 3
2 2
1 2 100
1 2
2 1
Sample Output
10
25
100
100
题意:给定一棵带权树,m次询问,两个点之间的距离。
题解:暴力DFS。
1 #include <vector> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int N=12345; 7 int fa[N],ans; 8 vector < pair<int,int> > E[N]; 9 vector < pair<int,int> > q[N]; 10 bool root[N],vis[N]; 11 12 void init(){ 13 for(int i=0;i<N;i++){ 14 fa[i]=i; 15 E[i].clear(); 16 q[i].clear(); 17 vis[i]=false; 18 root[i]=true; 19 } 20 } 21 22 int Find(int x){ 23 return fa[x]==x?x:fa[x]=Find(fa[x]); 24 } 25 26 void Union(int x,int y){ 27 int fx=Find(x),fy=Find(y); 28 if(fx!=fy){ 29 fa[fy]=fx; 30 } 31 } 32 33 void solve(int u){ 34 vis[u]=1; 35 for(int i=0;i<E[u].size();i++){ 36 int v=E[u][i]; 37 if(vis[v]) continue; 38 solve(v); 39 Union(u,v); 40 } 41 for(int i=0;i<q[u].size();i++){ 42 int v=q[u][i]; 43 if(!vis[v]) continue; 44 ans=Find(v); 45 } 46 } 47 48 int main(){ 49 int t,n,m; 50 scanf("%d",&t); 51 while(t--){ 52 int u,v,w; 53 init(); 54 scanf("%d%d",&n,&m); 55 for(int i=1;i<n;i++){ 56 scanf("%d%d%d",&u,&v,&w); 57 E[u].push_back(make_pair(v,w)); 58 E[v].push_back(make_pair(u,w)); 59 } 60 for(int i=1;i<=m;i++){ 61 scanf("%d%d",&u,,&v); 62 Q[u].push_back(make_pair(v,i)); 63 Q[v].push_back(make_pair(u,i)); 64 } 65 tarjan(); 66 67 } 68 return 0; 69 }
原文地址:https://www.cnblogs.com/Leonard-/p/8733105.html