- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 69 lines of C++ from the credited upstream file ccc21s4.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3#include <iostream>4#include <vector>5#include <deque>6#include <set>7 8using namespace std;9 10int main() {11 int n, w, d;12 cin >> n >> w >> d;13 14 vector<vector<int>> graph(n + 1);15 16 for (int i = 0; i < w; i++) {17 int a, b;18 cin >> a >> b;19 graph[b].push_back(a);20 }21 22 vector<int> route(n);23 for (int i = 0; i < n; i++) {24 cin >> route[i];25 }26 27 vector<int> dist(n + 1, 9999999);28 deque<pair<int, int>> queue;29 vector<bool> vis(n, false);30 31 queue.push_back({ n, 0 });32 33 while (!queue.empty()) {34 auto [node, time] = queue.front();35 queue.pop_front();36 37 dist[node] = time;38 for (int neighbor : graph[node]) {39 if (!vis[neighbor]) {40 vis[neighbor] = true;41 queue.push_back({ neighbor, time + 1 });42 }43 }44 }45 46 multiset<pair<int, int>> ms; 47 for (int i = 0; i < n; i++) {48 ms.insert({i + dist[route[i]], route[i]});49 }50 51 for (int i = 0; i < d; i++) {52 int x, y;53 cin >> x >> y; x--; y--;54 int sx = route[x];55 int sy = route[y];56 ms.erase({ x + dist[sx], sx });57 ms.erase({ y + dist[sy], sy });58 ms.insert({ y + dist[sx], sx });59 ms.insert({ x + dist[sy], sy });60 swap(route[x], route[y]);61 cout << ms.begin()->first << endl;62 63 64 65 66 67 }68 69}