标签:output sts php ons set war transport The uri
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2874
题目:
1 #include <cstdio> 2 #include <vector> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 1e4 + 7; 7 int n, m, q, u, v, k, cnt; 8 int cost[maxn], deep[maxn], fa[maxn][30], vis[maxn]; 9 10 struct edge { 11 int v, l; 12 edge(int v = 0, int l = 0) : v(v), l(l) {} 13 }; 14 15 vector<edge> G[maxn]; 16 17 void init() { 18 for(int i = 0; i <= n; i++) { 19 G[i].clear(); 20 } 21 cnt = 0; 22 memset(vis, 0, sizeof(vis)); 23 memset(cost, 0, sizeof(cost)); 24 } 25 26 void dfs(int u, int d, int p) { 27 fa[u][0] = p; 28 deep[u] = d; 29 vis[u] = cnt; 30 for(int i = 0; i < G[u].size(); i++) { 31 int v = G[u][i].v; 32 if(v != p) { 33 cost[v] = cost[u] + G[u][i].l; 34 dfs(v, d + 1, u); 35 } 36 } 37 } 38 39 void lca() { 40 for(int i = 1; i <= n; i++) { 41 for(int j = 1; (1 << j) <= n; j++) { 42 fa[i][j] = -1; 43 } 44 } 45 for(int j = 1; (1 << j) <= n; j++) { 46 for(int i = 1; i <= n; i++) { 47 if(fa[i][j-1] != -1) { 48 fa[i][j] = fa[fa[i][j-1]][j-1]; 49 } 50 } 51 } 52 } 53 54 int query(int u, int v) { 55 if(deep[u] < deep[v]) swap(u, v); 56 int k; 57 for(k = 0; (1 << (k+1)) <= deep[u]; k++); 58 for(int i = k; i >= 0; i--) { 59 if(deep[u] - (1 << i) >= deep[v]) { 60 u = fa[u][i]; 61 } 62 } 63 if(u == v) return u; 64 for(int i = k; i >= 0; i--) { 65 if(fa[u][i] != -1 && fa[u][i] != fa[v][i]) { 66 u = fa[u][i]; 67 v = fa[v][i]; 68 } 69 } 70 return fa[u][0]; 71 } 72 73 int main() { 74 while(~scanf("%d%d%d", &n, &m, &q)) { 75 init(); 76 while(m--) { 77 scanf("%d%d%d", &u, &v, &k); 78 G[u].push_back(edge(v, k)); 79 G[v].push_back(edge(u, k)); 80 } 81 for(int i = 1; i <= n; i++) { 82 if(vis[i] == 0) { 83 cnt++; 84 dfs(i, 0, -1); 85 } 86 } 87 lca(); 88 for(int i = 0; i < q; i++) { 89 scanf("%d%d", &u, &v); 90 if(vis[u] != vis[v]) { 91 printf("Not connected\n"); 92 } else { 93 printf("%d\n", cost[u] + cost[v] - 2 * cost[query(u,v)]); 94 } 95 } 96 } 97 return 0; 98 }
Connections between cities(LCA)
标签:output sts php ons set war transport The uri
原文地址:https://www.cnblogs.com/Dillonh/p/9135364.html