//Autor: Bartłomiej Czarkowski #include <bits/stdc++.h> using namespace std; const int N = 101'000; int n; int dp[N][3]; char s[N]; int daj(int x) { if (!x) { return 0; } return max(1, x - 1); } void solve() { scanf("%d%s", &n, s + 1); int lf = 1; while (s[lf] == '0' && lf < n) { ++lf; } if (lf == n && s[n] == '0') { printf("0\n"); return; } int rg = n; while (s[rg] == '0') { --rg; } vector <int> v1, v2; int ost = lf; for (int i = lf + 1; i <= rg; ++i) { if (s[i] == '1') { v1.push_back(i - ost - 1); ost = i; } } v2.push_back(lf - 1); v2.push_back(n - rg); sort(v1.begin(), v1.end()); reverse(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); reverse(v2.begin(), v2.end()); int m = v1.size(); for (int i = 0; i <= m; ++i) { for (int j = 0; j <= 2; ++j) { dp[i][j] = -1e9; } } dp[0][0] = 0; dp[0][1] = v2[0]; dp[0][2] = v2[0] + max(0, v2[1] - 1); for (int i = 1; i <= m; ++i) { dp[i][0] = dp[i - 1][0] + daj(max(0, v1[i - 1] - (i - 1) * 4)); for (int j = 1; j <= 2; ++j) { dp[i][j] = max(dp[i - 1][j] + daj(max(0, v1[i - 1] - (i - 1) * 4 - j * 2)), dp[i][j - 1] + max(0, v2[j - 1] - i * 2 - (j - 1))); } } printf("%d\n", n - dp[m][2]); } int main() { int q=1; scanf("%d", &q); while(q--) { solve(); } return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | //Autor: Bartłomiej Czarkowski #include <bits/stdc++.h> using namespace std; const int N = 101'000; int n; int dp[N][3]; char s[N]; int daj(int x) { if (!x) { return 0; } return max(1, x - 1); } void solve() { scanf("%d%s", &n, s + 1); int lf = 1; while (s[lf] == '0' && lf < n) { ++lf; } if (lf == n && s[n] == '0') { printf("0\n"); return; } int rg = n; while (s[rg] == '0') { --rg; } vector <int> v1, v2; int ost = lf; for (int i = lf + 1; i <= rg; ++i) { if (s[i] == '1') { v1.push_back(i - ost - 1); ost = i; } } v2.push_back(lf - 1); v2.push_back(n - rg); sort(v1.begin(), v1.end()); reverse(v1.begin(), v1.end()); sort(v2.begin(), v2.end()); reverse(v2.begin(), v2.end()); int m = v1.size(); for (int i = 0; i <= m; ++i) { for (int j = 0; j <= 2; ++j) { dp[i][j] = -1e9; } } dp[0][0] = 0; dp[0][1] = v2[0]; dp[0][2] = v2[0] + max(0, v2[1] - 1); for (int i = 1; i <= m; ++i) { dp[i][0] = dp[i - 1][0] + daj(max(0, v1[i - 1] - (i - 1) * 4)); for (int j = 1; j <= 2; ++j) { dp[i][j] = max(dp[i - 1][j] + daj(max(0, v1[i - 1] - (i - 1) * 4 - j * 2)), dp[i][j - 1] + max(0, v2[j - 1] - i * 2 - (j - 1))); } } printf("%d\n", n - dp[m][2]); } int main() { int q=1; scanf("%d", &q); while(q--) { solve(); } return 0; } |