P5304 [GXOI/GZOI2019]旅行者

题目描述

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

简要题意:给定一个 $n$ 个点 $m$ 条边的有向图,同时给定 $k$ 个点,求这 $k$ 个点两两最短距离的最小值

$n\le 10^5,m\le 5\times 10^5$

Solution

我们考虑按照二进制的每一位为 $0$ 或 $1$ 将这 $k$ 个点划分成两个集合,$s$ 连其中一个集合,$t$ 连另一个,然后求 $s$ 到 $t$ 的最短路,注意到这样一定可以求出最小值

时间复杂度 $O(n\log m\log n)$

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
72
73
74
75
76
77
78
#include <iostream>
#include <queue>
#include <tuple>
#define maxn 100010
#define maxm 500010
#define ll long long
#define INF 1000000000000000000
using namespace std;

int n, m, k;

struct Edge {
int to, next, w;
} e[maxm]; int c1, head[maxn];
inline void add_edge(int u, int v, int w) {
e[c1].to = v; e[c1].w = w;
e[c1].next = head[u]; head[u] = c1++;
}

struct node {
int k; ll d;

friend bool operator < (const node &u, const node &v) { return u.d > v.d; }
}; bool vis[maxn]; ll dis[maxn]; int s, t;
ll dijkstra(int s, int t) {
for (int i = s; i <= t; ++i) dis[i] = INF; dis[s] = 0;
for (int i = s; i <= t; ++i) vis[i] = 0;
priority_queue<node> Q; Q.push({ s, 0 });
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({ v, dis[v] });
}
}
} return dis[t];
}

void work() {
cin >> n >> m >> k; s = 0, t = n + 1;
vector<tuple<int, int, int>> E;
for (int i = 1; i <= m; ++i) {
int x, y, z; cin >> x >> y >> z;
E.emplace_back(x, y, z);
} vector<int> vec;
for (int i = 1, x; i <= k; ++i) cin >> x, vec.push_back(x);
ll ans = INF;
for (int o = 0; o < 20; ++o) {
fill(head + s, head + t + 1, -1), c1 = 0;
for (auto u : vec)
if (u >> o & 1) add_edge(s, u, 0);
else add_edge(u, t, 0);
for (auto [u, v, w] : E) add_edge(u, v, w);
ans = min(ans, dijkstra(s, t));

fill(head + s, head + t + 1, -1), c1 = 0;
for (auto u : vec)
if (u >> o & 1) add_edge(u, t, 0);
else add_edge(s, u, 0);
for (auto [u, v, w] : E) add_edge(u, v, w);
ans = min(ans, dijkstra(s, t));
} cout << ans << "\n";
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);

int T; cin >> T;
while (T--) work();

return 0;
}