#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; const int maxn = 1E5 + 10; const int maxm = maxn * 2; const int maxq = 2E6 + 10; int n, m, q, dis[maxn], vis[maxn], father[maxn], ans[maxq / 2], a, b, c; struct Edge { int v, len, next; }; Edge edge[maxm]; int tot, head[maxn]; void addedge(int a, int b, int c) { edge[tot].v = b; edge[tot].len = c; edge[tot].next = head[a]; head[a] = tot++; } struct Ques { int v, index, next; }; Ques Q[maxq]; int q_tot, q_head[maxn]; void addques(int a, int b, int index) { Q[q_tot].v = b; Q[q_tot].index = index; Q[q_tot].next = q_head[a]; q_head[a] = q_tot++; } int Find(int k) { if (father[k] == k) return k; else return father[k] = Find(father[k]); } void Tarjan_LCA(int k, int deep, int root) { father[k] = k; vis[k] = root; dis[k] = deep; for (int j = head[k]; j != -1; j = edge[j].next) { int v = edge[j].v; if (vis[v] == -1) { Tarjan_LCA(v, deep + edge[j].len, root); father[v] = k; } } for (int j = q_head[k]; j != -1; j = Q[j].next) { int v = Q[j].v; if (vis[v] == root) ans[Q[j].index] = dis[v] + dis[k] - 2 * dis[Find(v)]; } } int main(int argc, char const *argv[]) { while (~scanf("%d%d%d", &n, &m, &q)) { tot = q_tot = 0; memset(head, -1, sizeof(head)); memset(q_head, -1, sizeof(q_head)); memset(vis, -1, sizeof(vis)); for (int i = 0; i < m; i++) { scanf("%d%d%d", &a, &b, &c); addedge(a, b, c); addedge(b, a, c); } for (int i = 0; i < q; i++) { scanf("%d%d", &a, &b); ans[i] = -1; addques(a, b, i); addques(b, a, i); } for (int i = 1; i <= n; i++) if (vis[i] == -1) Tarjan_LCA(i, 0, i); for (int i = 0; i < q; i++) if (ans[i] == -1) printf("Not connected\n"); else printf("%d\n", ans[i]); } return 0; }
询问 a,b 之间的最短距离。因为图中不可能出现环,所以两点之间有且仅有一条路,或者没有。
预处理出ab的祖先和距离,直接返回dis[a]+dis[b]-2*dis[father];