2014-08-30 解題區/解題區 - UVa UVa 12671 - Disjoint water supply contents 1. Problem2. Sample Input3. Sample Output4. Solution Problem給一張圖,問有多少對 (u, v) 沒有連通路徑。 Sample Input123456789101112131415161718196 61 21 31 42 52 63 68 111 21 31 42 53 46 73 63 74 82 65 6 Sample Output121426 Solution只需要找到每個連通元件的大小即可,連通元件之間的點是無法存有路徑的。 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#include <stdio.h>#include <stdlib.h>#include <math.h>#include <vector>#include <assert.h>#include <map>#include <algorithm>using namespace std;int parent[32767], weight[32767];int findp(int x) { return parent[x] == x ? x : parent[x] = findp(parent[x]);}int main() { int n, m, x, y; while (scanf("%d %d", &n, &m) == 2 && n) { for (int i = 0; i <= n; i++) { parent[i] = 0, weight[i] = 0; } vector<int> g[1024]; for (int i = 0; i < m; i++) { scanf("%d %d", &x, &y); if (x == 1) { parent[y] = y; } else g[y].push_back(x); } for (int i = 2; i <= n; i++) { for (int j = 0; j < g[i].size(); j++) { int u = g[i][j]; if (parent[i] == 0) parent[i] = u; else if(findp(i) != findp(u)) parent[i] = i; } } for (int i = 2; i <= n; i++) { weight[findp(i)]++; } int ret = 0; for (int i = 2; i <= n; i++) { if (i == parent[i]) { ret += weight[i] * (n - 1 - weight[i]); } } printf("%d\n", ret/2 + n - 1); } return 0;} Newer UVa 12674 - Go up the ultras Older UVa 12663 - High bridge, low bridge