HDU 2586 How far away ?,hdu2586
How far away ?Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6309 Accepted Submission(s): 2368
Problem DescriptionThere 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 Input
23 21 2 103 1 151 22 32 21 2 1001 22 1
Sample Output
1025100100
題目的意思就是給定一些houses的編號,及這些編號房子之間的距離,然後有m次詢問,每次詢問給出兩個房子的編號,要求給出這兩個房子的最小距離。這張圖是樹圖,也就是總共N個點N-1條邊,然後能把所有點全部連通。本身分析題目很容易知道本題就是求最小公用祖先的問題,首先確定一個根節點,然後DFS遍曆一遍計算此根節點到所有節點的距離,然後可以用離線的tarjan演算法,來找到兩個詢問節點a和b的最近公用祖先c,然後要求的結果就是dist[a] - dist[c] + dist[b] - dist[c],意思很好理解,畫棵樹看看就可以了,而且這種思路也是很容易想到的。這裡用了一下非遞迴的DFS直接來求,每次詢問直接使用DFS求亮點之間的距離,也可以很輕鬆的AC。
#include <cstdio>#include <vector>#include <stack>#include <string>using namespace std;const int N = 40005;int n, m, t;vector<int> adj[N];vector<int> wei[N];int dist[N];bool visit[N];void init(int n){for (int i = 0; i <= n; ++i){adj[i].clear();wei[i].clear();}}int dfs(int x, int y){int res = 0;memset(visit, 0, sizeof(visit));memset(dist, 0, sizeof(dist));stack<int> st;st.push(x);visit[x] = true;while (!st.empty()){int tx = st.top();st.pop();if (tx == y)break;for (int i = 0; i < adj[tx].size(); ++i){int ty = adj[tx][i];if (visit[ty])continue;st.push(ty);visit[ty] = true;dist[ty] = dist[tx] + wei[tx][i];}}return dist[y];}int main(){int a, b, w;scanf("%d", &t);while (t--){scanf("%d %d", &n, &m);init(n);for (int i = 0; i < n - 1; ++i){scanf("%d %d %d", &a, &b, &w);adj[a].push_back(b);adj[b].push_back(a);wei[a].push_back(w);wei[b].push_back(w);}for (int i = 0; i < m; ++i){scanf("%d %d", &a, &b);printf("%d\n", dfs(a, b));}if (t != 0)printf("\n");}return 0;}