- 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
- 61 lines of C++ from the credited upstream file abc287_c.cpp.
- The implementation visibly relies on ordered lookup.
- 3 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.
1#include <iostream>2#include <map>3 4using namespace std;5using ui = unsigned int;6 7void walk(map<ui, map<ui, bool>>& mm, ui& n, ui pos, ui prev, ui& cnt) {8 if (cnt > n) {9 return;10 }11 12 cnt++;13 auto it = mm[pos].begin();14 while (it != mm[pos].end()) {15 if (it->first != prev) {16 walk(mm, n, it->first, pos, cnt);17 }18 it++;19 }20}21 22int main() {23 ui n, m;24 cin >> n >> m;25 26 if (m == 0 || m < n - 1) {27 cout << "No" << endl;28 return 0;29 }30 31 map<ui, map<ui, bool>> mm;32 for (ui i = 0; i < m; i++) {33 ui v1, v2;34 cin >> v1 >> v2;35 mm[v1][v2] = true;36 mm[v2][v1] = true;37 }38 39 auto it = mm.begin();40 ui has_one = 0;41 while (it != mm.end()) {42 has_one += ui(it->second.size() == 1);43 it++;44 }45 46 if (has_one != 2) {47 cout << "No" << endl;48 return 0;49 }50 51 ui cnt = 0;52 walk(mm, n, 1, 0, cnt);53 54 if (cnt == n) {55 cout << "Yes" << endl;56 } else {57 cout << "No" << endl;58 }59 60 return 0;61}