This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int N = 200000;
template <class T>
struct fenwick {
vector<T> tree;
int n;
fenwick(int n) : n(n) {
tree.resize(n + 1);
}
void update(int a, T x) {
for ( ; a <= n; a += (a & -a)) {
tree[a] += x;
}
}
T query(int a) {
T res = 0;
for ( ; a > 0; a -= (a & -a)) {
res += tree[a];
}
return res;
}
int lower_bound(T k) {
int res = 0;
T sum = 0;
for (int i = __lg(n); i >= 0; --i) {
if (res + (1 << i) <= n && sum + tree[res + (1 << i)] < k) {
res += 1 << i;
sum += tree[res];
}
}
return res + 1;
}
};
int black[N], white[N], n;
long long calc(int k) {
vector<array<int, 2>> segments;
for (int i = 0; i < n; ++i) {
int b = black[i], w = white[(i + k) % n];
if (b > w) {
swap(b, w);
}
segments.push_back({b, w});
}
sort(segments.begin(), segments.end());
long long ans = 0;
fenwick<int> fenw(2 * n);
for (auto [l, r] : segments) {
ans += fenw.query(r) - fenw.query(l);
fenw.update(r, 1);
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string s;
cin >> n >> s;
int b = 0, w = 0;
for (int i = 0; i < 2 * n; ++i) {
if (s[i] == 'B') {
black[b++] = i;
} else {
white[w++] = i;
}
}
int low = 0, high = n - 1;
while (low < high) {
int mid = (low + high) / 2;
if (calc(mid) < calc(mid + 1)) {
low = mid + 1;
} else {
high = mid;
}
}
cout << calc(low) << "\n";
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |