UVa 10987 - Antifloyd

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

給定經由 n 個節點的無向圖,任兩點之間的最短路結果,請問原圖中的邊為何?用最少數量的邊完成。如果有可能無解則輸出 Need better measurements.

Sample Input

1
2
3
4
5
6
7
2
3
100
200 100
3
100
300 100

Sample Output

1
2
3
4
5
6
7
Case #1:
2
1 2 100
2 3 100
Case #2:
Need better measurements.

Solution

最短路徑符合三角不等式,否則將會有更短的邊,檢查 f[i][j] <= f[i][k] + f[k][j],窮舉所有可能進行檢查,$O(n^3)$ 完成。接著窮舉找到任兩個相鄰點 i, j 之間是否存在內點。若不存在內點,則表示 i, j 在原圖上有一條邊權重為 f[i][j]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// floyd
#include <stdio.h>
#include <algorithm>
using namespace std;
const int MAXN = 128;
int f[MAXN][MAXN];
int anti_floyd(int n) {
int adj[MAXN][MAXN] = {};
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
adj[i][j] = 1;
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (f[i][k] + f[k][j] < f[i][j]) {
puts("Need better measurements.");
return 0;
}
if (i == j || i == k || j == k)
continue;
if (f[i][k] + f[k][j] == f[i][j])
adj[i][j] = 0;
}
}
}
int e = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (i == j) continue;
e += adj[i][j];
}
}
printf("%d\n", e);
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++)
if (adj[i][j])
printf("%d %d %d\n", i+1, j+1, f[i][j]);
}
return 1;
}
int main() {
int testcase, cases = 0, n;
scanf("%d", &testcase);
while (testcase--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++)
scanf("%d", &f[i][j]), f[j][i] = f[i][j];
f[i][i] = 0;
}
printf("Case #%d:\n", ++cases);
int valid = anti_floyd(n);
puts("");
}
return 0;
}