- 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
- 66 lines of C++ from the credited upstream file abc325_c.cpp.
- The implementation visibly relies on sequence storage.
- 5 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 <algorithm>2#include <iostream>3#include <vector>4 5using namespace std;6 7void sensor_traverse(vector<string>& grid, unsigned long i, unsigned long j,8 vector<string>& visited, int& visited_sensor_count) {9 visited[i][j] = '#';10 visited_sensor_count++;11 for (unsigned long ti = max((unsigned long)(1), i - 1);12 ti <= min(i + 1, (unsigned long)(grid.size() - 1)); ti++) {13 for (unsigned long tj = max((unsigned long)(1), j - 1);14 tj <= min(j + 1, (unsigned long)(grid[0].size())); tj++) {15 if (ti == i && tj == j) {16 continue;17 }18 19 if (visited[ti][tj] != '#' && grid[ti][tj] == '#') {20 sensor_traverse(grid, ti, tj, visited, visited_sensor_count);21 }22 }23 }24}25 26int main() {27 unsigned long h, w;28 cin >> h >> w;29 30 string dummy(w + 2, '.');31 vector<string> grid(h + 2, dummy);32 int sensor_count = 0;33 for (unsigned long j = 1; j <= h; j++) {34 string s;35 cin >> s;36 sensor_count += count(s.begin(), s.end(), '#');37 s = "." + s + ".";38 grid[j] = s;39 }40 41 int ans = 0;42 vector<string> visited(h + 2, dummy);43 int visited_sensor_count = 0;44 for (unsigned long i = 1; i <= h; i++) {45 if (visited_sensor_count == sensor_count) {46 cout << ans << endl;47 return 0;48 }49 50 for (unsigned long j = 1; j <= w; j++) {51 if (visited_sensor_count == sensor_count) {52 cout << ans << endl;53 return 0;54 }55 56 if (grid[i][j] != '#' || visited[i][j] == '#') {57 continue;58 }59 60 ans++;61 sensor_traverse(grid, i, j, visited, visited_sensor_count);62 }63 }64 65 cout << ans << endl;66}