题解:P10349 [PA2024] Mrówki
我们先从一些简单的例子来发现规律
- s = “PL”,碰撞结束后 s = “LP”,每个位置碰撞的次数是
cnt = [1,1] 。 - s = “PPL”,碰撞结束后 s = “LPP”,每个位置碰撞的次数是
cnt = [1,2,1] 。 - s = “PPPL”,碰撞结束后 s = “LPPP”,每个位置碰撞的次数是
cnt = [1,2,2,1] 。 - s = “PPPL”,碰撞结束后 s = “LPPP”,每个位置碰撞的次数是
cnt = [1,2,2,1] 。
我们可以发现对于 s = “PPPPP...PL”的情况(就是很多个连续的 ‘P’ 跟上一个 ‘L’),碰撞结束后会变成“LPPPPP...P”,也就是把最后的 ‘L’挪到最前面,并且每个位置碰撞的次数为
这样的话,我们就可以从左往右扫描 s,不断地找到多个连续的 ‘P’跟上一个‘L’的情况,按上述规律处理即可。
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
string s;
cin >> n >> s;
vector<int> a(n + 2, 0);
int j = n + 1; // j 表示第 1 个 'P' 的位置
for (int i = 1; i <= n; i++) if (s[i - 1] == 'P') {
j = i;
break;
}
for (int i = j + 1; i <= n; i++) if (s[i - 1] == 'L') {
// 把 L 换到最前面
swap(s[i - 1], s[j - 1]);
// 用差分数组处理下这一段的碰撞次数
a[j] += 1, a[j + 1] -= 1;
a[i] += 1, a[i + 1] -= 1;
if (i - j > 1) a[j + 1] += 2, a[i] -= 2;
j++;
}
for (int i = 1; i <= n; i++) {
a[i] += a[i - 1];
cout << a[i] << " \n"[i == n];
}
return 0;
}