Interesting one.. It is more about data structure design actually. After you figure out how to represent cells, the DP formula will be very intuitive :)
Data structure: just interleave the 2 strings and form a bitset..
#include <cmath> #include <cstdio> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <bitset> using namespace std; #define MAX_LEN 201 bool calc(int n, string &n1, string &n2) { std::bitset<MAX_LEN> b; vector<bool> dp(2 * n, false); int last = 0; for (int i = 0; i < n; i++) { b[i * 2] = n1[i] - '0'; if (!b[i * 2]) last = i * 2; b[i * 2 + 1] = n2[i] - '0'; if (!b[i * 2 + 1]) last = i * 2 + 1; } for (int i = 0; i < 2 * n; i++) { if (b[i]) { dp[i] = (i == 0) ? true: dp[i - 1]; continue; } // now b[i] is 0 bool prev = (i == 0 ? true : (dp[i - 1])); if (!prev) continue; bool next = false, nnext = false; if (i < (2 * n - 1)) // { next = b[i + 1]; if (!next) dp[i + 1] = true; } if (i < (2 * n - 2)) { nnext = b[i + 2]; if (next && (!nnext)) dp[i + 2] = true; } } return dp[last]; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; string n1, n2; cin >> n1 >> n2; bool r = calc(n, n1, n2); cout << (r ? "YES" : "NO") << endl; } return 0; }