Luogu P1948 [USACO08JAN]Telephone Lines S

题目描述

https://www.luogu.com.cn/problem/P1948

Solution

我们考虑二分答案x,把长度大于x的边置为1跑最短路,最后检查最短路是否小于等于k即可

时间复杂度 $O(mlog^2m)$

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
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define maxn 1010
#define maxm 10010
#define cQ const Queue
#define cE const Edge
using namespace std;

int n, m, k;


struct Edge {
int fr, to, next, w, _w;

friend bool operator < (cE &u, cE &v) { return u.w < v.w; }
} e[maxm * 2]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].fr = u; e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

struct Queue {
int v, k;

Queue() {}
Queue(int _v, int _k) { v = _v; k = _k; }

friend bool operator < (cQ &u, cQ &v) { return u.v > v.v; }
}; bool vis[maxn]; int dis[maxn];
priority_queue<Queue> Q;
void dijkstra() {
memset(dis, 10, sizeof dis); dis[1] = 0;
memset(vis, 0, sizeof vis); Q.push(Queue(0, 1));
while (!Q.empty()) {
int u = Q.top().k; Q.pop();
if (vis[u]) continue; vis[u] = 1;
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to, w = e[i]._w;
if (dis[v] > dis[u] + w) {
dis[v] = dis[u] + w;
Q.push(Queue(dis[v], v));
}
}
}
}

bool check(int x) {
for (int i = 0; i < c1; i += 2)
e[i ^ 1]._w = e[i]._w = e[i].w > x;
dijkstra();
return dis[n] <= k;
}

int main() { memset(head, -1, sizeof head);
cin >> n >> m >> k;
for (int i = 1; i <= m; ++i) {
int x, y, z; cin >> x >> y >> z;
add_edge(x, y, z); add_edge(y, x, z);
}
int l = 0, r = 1000000, mid, ans = -1;
while (l <= r) {
mid = l + r >> 1;
if (check(mid)) ans = mid, r = mid - 1;
else l = mid + 1;
} cout << ans << endl;
return 0;
}