- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 77 lines of C++ from the credited upstream file ccc23s4.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12#include <bits/stdc++.h>3using namespace std;4#define int long long5const int N = 5e5 + 100;6struct s {7 int x, y, l, c;8} e[N];9int p[N];10vector<pair<int, int>> g[N];11int dis[N];12bool vis[N];13int n, m, ans;14 15int dijk(int st, int ed, int d) {16 priority_queue<pair<int, int>> q;17 memset(dis, 0x3f, sizeof(dis));18 memset(vis, false, sizeof(vis));19 dis[st] = 0;20 q.push({0, st});21 while (q.size()) {22 int loc = q.top().second;23 q.pop();24 if (vis[loc]) continue;25 vis[loc] = true;26 for (auto i : g[loc]) {27 int to = i.first;28 int l = i.second;29 if (vis[to]) continue;30 if (dis[to] > dis[loc] + l) {31 dis[to] = dis[loc] + l;32 q.push({-dis[to], to});33 }34 }35 }36 return d < dis[ed];37}38 39int find(int x) {40 if (x == p[x]) return x;41 p[x] = find(p[x]);42 return p[x];43}44 45bool cmp(s a, s b) {46 if (a.l == b.l) return a.c < b.c;47 return a.l < b.l;48}49 50signed main() {51 cin >> n >> m;52 for (int i = 0; i < m; i++) {53 p[i] = i;54 }55 for (int i = 0; i < m; i++) {56 cin >> e[i].x >> e[i].y >> e[i].l >> e[i].c;57 }58 sort(e, e + m, cmp);59 for (int i = 0; i < m; i++) {60 s it = e[i];61 int rx = find(it.x);62 int ry = find(it.y);63 if (rx != ry) {64 p[rx] = ry;65 ans += it.c;66 g[it.x].push_back({it.y, it.l});67 g[it.y].push_back({it.x, it.l});68 } else if (dijk(it.x, it.y, it.l)) {69 ans += it.c;70 g[it.x].push_back({it.y, it.l});71 g[it.y].push_back({it.x, it.l});72 }73 }74 cout << ans << endl;75 return 0;76}77