題目鏈接:http://acm.hdu.edu.cn/showPRoblem.php?pid=2586
How far away ?
Time Limit: 2000/1000 MS (java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 14305 Accepted Submission(s): 5409
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
Source ECJTU 2009 Spring Contest
【中文題意】有t組數據,每組數據一個n,一個m,n代表點的個數,m代表詢問的次數。 下面n-1行每行輸入三個整數i,j,k,意思為,從i到j有一條長度為k的雙向邊。 下面m行每行兩個整數u,v;讓你輸出從u到v的最短距離。 【思路分析】運用lca的思想,以1為樹根DFS建立樹,記錄每個結點的深度和父結點。 用map記錄彼此之間的距離。 求的時候直接用暴力求LCA的方法求出距離即可【貌似沒有向我這么做的】。 【AC代碼】
#include<cstdio>#include<iostream>#include<cstring>#include<cmath>#include<queue>#include<stack>#include<map>#include<algorithm>using namespace std;int t,n,q;vector<int>G[50005];#define root 1int parent[50005];int depth[50005];map<int,map<int,int> >m;void dfs(int v,int p,int d){ parent[v]=p; depth[v]=d; for(int i=0; i<G[v].size(); i++) { if(G[v][i]!=p) { dfs(G[v][i],v,d+1); } }}void init(){ dfs(root,-1,0);}int lca(int u,int v){ int sum=0; while(depth[u]>depth[v]) { sum+=m[u][parent[u]]; u=parent[u]; } while(depth[v]>depth[u]) { sum+=m[v][parent[v]]; v=parent[v]; } while(u!=v) { sum+=m[v][parent[v]]; sum+=m[u][parent[u]]; u=parent[u]; v=parent[v]; } return sum;}int main(){ scanf("%d",&t); while(t--) { m.clear(); for(int i=0;i<n;i++) { G[i].clear(); } scanf("%d%d",&n,&q); int u,v,cost; for(int i=0; i<n-1; i++) { scanf("%d%d%d",&u,&v,&cost); G[u].push_back(v); G[v].push_back(u); m[u][v]=cost; m[v][u]=cost; //printf("%d**/n",m[u][v]); } init(); for(int i=1; i<=q; i++) { scanf("%d%d",&u,&v); printf("%d/n",lca(u,v)); } } return 0;}新聞熱點
疑難解答