Question: hdoj 2874 Connections between cities
After the war, some cities were destroyed. The graph is not connected, so you can find the distance between any two points,
Analysis: It is obvious that the LCA
However, the graph is not connected, so we need to perform each vertex in Tarjan. Then mark it.
In addition, the question becomes vector. It seems that we will learn to use arrays to simulate the adjacent table in the future.
AC code:
# Include <iostream> # include <cstdio> # include <cstring> # include <vector> using namespace std; # define N 10010 # define M 10010 # define Q limit 10int head [N]; struct edge {int u, v, w, next;} e [2 * M]; int _ head [N]; struct ask {int u, v, lca, next;} ea [2 * Q]; int dir [N], fa [N], vis [N]; int k; inline void add_edge (int u, int v, int w, int & k) {e [k]. u = u; e [k]. v = v; e [k]. w = w; e [k]. next = head [u]; head [u] = k ++;} inline voi D add_ask (int u, int v, int & k) {ea [k]. u = u; ea [k]. v = v; ea [k]. lca =-1; ea [k]. next = _ head [u]; _ head [u] = k ++;} int find (int x) {return x = fa [x]? X: fa [x] = find (fa [x]);} void Tarjan (int u, int c) {vis [u] = c; fa [u] = u; for (int k = head [u]; k! =-1; k = e [k]. next) if (! Vis [e [k]. v]) {int v = e [k]. v, w = e [k]. w; dir [v] = dir [u] + w; Tarjan (v, c); fa [v] = u ;}for (int k =__ head [u]; k! =-1; k = ea [k]. next) if (vis [ea [k]. v] = c) ea [k]. lca = ea [k ^ 1]. lca = find (ea [k]. v);} void Clear (int n) {memset (head,-1, sizeof (head); memset (_ head,-1, sizeof (_ head); memset (vis, 0, sizeof (vis);} int main () {int n, m, c; while (~ Scanf ("% d", & n, & m, & c) {Clear (n); k = 0; for (int I = 0; I <m; I ++) {int x, y, z; scanf ("% d", & x, & y, & z ); add_edge (x, y, z, k); add_edge (y, x, z, k);} k = 0; for (int I = 0; I <c; I ++) {int x, y; scanf ("% d", & x, & y); add_ask (x, y, k); add_ask (y, x, k) ;}int cnt = 0; for (int I = 1; I <= n; I ++) {if (vis [I] = 0) {dir [I] = 0; Tarjan (I, ++ cnt) ;}}for (int I = 0; I <c; I ++) {int f = 2 * I; int ans = dir [ea [f]. u] + dir [ea [f]. v]-2 * dir [ea [f]. lca]; // printf ("LCA: % d \ n", e [f]. lca); if (ea [f]. lca =-1) puts ("Not connected"); else printf ("% d \ n", ans) ;}} return 0 ;}
Hdoj 2874 Connections between cities [Tarjan offline LCA]