0%

AtCoder Beginner Contest 143 E.Travel by Car(重构最短路)

题目链接

首先用 $floyed$ 求出每个点到其他所有点的距离, 然后把最短路小于 $l$ 的边变为1,剩下的为 $inf$ , 再求一次最短路

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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf = 1e17 + 10;
const int N = 310;

ll n, m, l, q;
ll a[105000], b[105000], c[105000];
ll fuel[N][N];
ll dist[N][N];
ll s[105000], t[105000];

int main() {
cin >> n >> m >> l;
for(int i = 1; i <= m; i++) cin >> a[i] >> b[i] >> c[i];
cin >> q;
for(int i = 1; i <= q; i++) cin >> s[i] >> t[i];

for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
fuel[i][j] = inf;
dist[i][j] = inf;
}
fuel[i][i] = 0;
dist[i][i] = 0;
}
for(int i = 1; i <= m; i++) {
fuel[a[i]][b[i]] = min(fuel[a[i]][b[i]], c[i]);
fuel[b[i]][a[i]] = min(fuel[b[i]][a[i]], c[i]);
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
for(int k = 1; k <= n; k++) {
fuel[j][k] = min(fuel[j][k], fuel[j][i] + fuel[i][k]);
}
}
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if(i == j) continue;
if(fuel[i][j] <= l) dist[i][j] = 1;
}
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
for(int k = 1; k <= n; k++) {
dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k]);
}
}
}
for(int i = 1; i <= q; i++) {
if(dist[t[i]][s[i]] < inf)
cout << dist[t[i]][s[i]] - 1 << endl;
else cout << -1 << endl;
}

return 0;
}
求大佬赏个饭