/*
題意:給定一張圖,包括n個城市,m條路徑,q個詢問( 圖中沒有環 )。
LCA問題:詢問a,b的最短距離.
則:ans = dis[a] + dis[b] - dis[father]*2;
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn = 10007;
int n, m, c, num;
int deep[maxn], dis[maxn], pa[maxn], head[maxn]; ///pa[]表示父親節點
int ace[maxn]; ///最近公共祖先
struct Node{
int from, to, val, Next;
}edge[maxn<<2];
void init() {
memset(head, -1, sizeof(head));
num = 0;
memset(pa, 0, sizeof(pa));
}
void addedge(int a, int b, int c) {
edge[num].from = a;
edge[num].to = b;
edge[num].val = c;
edge[num].Next = head[a];
head[a] = num++;
}
int Find(int x, int y) {
if(x == y) return x;
if(deep[x] > deep[y]) return Find(pa[x], y);
else return Find(x, pa[y]);
}
void dfs(int now, int paa, int acee, int deepp, int diss) {
pa[now] = paa;
deep[now] = deepp;
dis[now] = diss;
ace[now] = acee;
for(int i = head[now]; i != -1; i = edge[i].Next) {
int v = edge[i].to;
if(pa[v] == 0) dfs(v, now, acee, deepp+1, diss+edge[i].val);
///pa==0,因爲是無向圖。這只是求距離,對父子關係要求不明顯
}
}
int main() {
// freopen("in.txt", "r", stdin);
while(~scanf("%d%d%d", &n, &m, &c)) {
init();
for(int i = 0; i < m; ++i) {
int t1, t2, t3; scanf("%d%d%d", &t1, &t2, &t3);
addedge(t1, t2, t3);
addedge(t2, t1, t3);
}
for(int i = 1; i <= n; ++i) {
if(pa[i] == 0) {
dfs(i, -1, i, 0, 1);
}
}
for(int i = 0; i < c; ++i) {
int t1, t2; scanf("%d%d", &t1, &t2);
if(ace[t1] == ace[t2]) {
int paa = Find(t1, t2);
printf("%d\n", dis[t1]+dis[t2]-2*dis[paa]);
}
else printf("Not connected\n");
}
}
}
HDU 2874(LCA)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.