对于每一个 \(f(i, j)\),我们考虑如何计算。我们发现,\(\texttt{1010}\) 式的字符串很有用,所以这启发我们如果遇到了一个模式 \(p_i = \texttt{'1'}\),那么我们可以在 \(i + 1\) 的位置放一个 \(\texttt{'1'}\)。这样我们直接处理了 \(i, i + 1, i + 2\)。容易证明这是最优的。
#include <bits/stdc++.h>
using namespace std;
const int N = 3e5 + 7;
int read() {
char c = getchar();
int x = 0, p = 1;
while ((c < '0' || c > '9') && c != '-') c = getchar();
if (c == '-') p = -1, c = getchar();
while (c >= '0' && c <= '9')
x = (x << 1) + (x << 3) + (c ^ 48), c = getchar();
return x * p;
}
int n;
string s;
int f(string p) {
int res = 0;
for (int i = 0; i < (int) p.size(); i ++) {
if (p[i] == '1') {
res ++;
i += 2;
}
}
return res;
}
void solve() {
n = read();
cin >> s; long long ans = 0;
for (int i = 0; i < n; i ++) {
string t = "";
for (int j = i; j < n; j ++) {
t += s[j];
ans += f(t);
}
}
cout << ans <<'\n';
}
signed main() {
int t = read();
while (t --) solve();
return 0;
}
标签:int,Sum,texttt,Substrings,Version,ans,getchar
From: https://www.cnblogs.com/yh2021shx/p/18090518