- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 62 lines of C++ from the credited upstream file abc424_d.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 8 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 7int main() {8 int t;9 cin >> t;10 11 while (t--) {12 int h, w;13 cin >> h >> w;14 15 vector<string> g(h);16 for (int i = 0; i < h; i++) cin >> g[i];17 18 vector<vector<int>> dp(h + 1, vector<int>(1 << w, 1e9));19 dp[0][0] = 0;20 21 for (int i = 0; i < h; i++) {22 for (int prev_mask = 0; prev_mask < (1 << w); prev_mask++) {23 if (dp[i][prev_mask] == 1e9) continue;24 25 for (int cur_mask = 0; cur_mask < (1 << w); cur_mask++) {26 int changes = 0;27 bool valid = true;28 29 for (int j = 0; j < w; j++) {30 if (g[i][j] == '#' && !(cur_mask & (1 << j))) changes++;31 }32 33 if (i > 0) {34 for (int j = 0; j < w - 1; j++) {35 bool tl = (prev_mask & (1 << j)) != 0;36 bool tr = (prev_mask & (1 << (j + 1))) != 0;37 bool bl = (cur_mask & (1 << j)) != 0;38 bool br = (cur_mask & (1 << (j + 1))) != 0;39 40 if (tl && tr && bl && br) {41 valid = false;42 break;43 }44 }45 }46 47 if (valid)48 dp[i + 1][cur_mask] = min(dp[i + 1][cur_mask],49 dp[i][prev_mask] + changes);50 }51 }52 }53 54 int ans = 1e9;55 for (int mask = 0; mask < (1 << w); mask++) ans = min(ans, dp[h][mask]);56 57 cout << ans << endl;58 }59 60 return 0;61}62