CF1884B Haunted House 题解
借鉴了当前 另一篇题解,加了更多的说明。
简化题意
给定一个长度为
其中,
分析
特殊的,
假设我们已经求出了
然后考虑再处理一位。
先贪心的考虑这一位,一定是将这个
以上如果不理解的,可以自己手动模拟两个。
然后,为什么一位一位的考虑,就一定是最优解呢?
证明:这个操作方法,截至到每一位,后面所有的
实现
两个指针,一个
注意:每次都需要将
代码
评测记录:https://codeforces.com/contest/1884/submission/230477092
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
void solve(int n, string s) {
ll ans = 0;
for (int i = n - 1, j = n - 1; ~i; --i, --j) {
while (j >= 0 && s[j] == '1') --j;
if (j < 0) printf("-1 ");
else printf("%lld ", ans += i - j);
}
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int T; cin >> T;
while (T--) {
int n; string s;
cin >> n >> s;
solve(n, s);
} return 0;
}