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;
#define ll long long
#define pb push_back
#define pii pair<int,int>
#define all(x) x.begin(), x.end()
int main() {
	ios::sync_with_stdio(false), cin.tie(0);
	int n;
	string s;
	cin >> n >> s;
	vector <pii> a;
	for (int i = 0; i < n; ++i) {
		if (s[i] == s[i + n]) {
			a.emplace_back(i, s[i] == 'B' ? 1 : 0);
		}
	}
	ll ans = 0;
	while (!a.empty()) {
		pii mn = {1 << 30, -1};
		int sz = a.size();
		for (int i = 0; i < sz; ++i) {
			if (a[i].second != a[(i + 1) % sz].second) {
				int len = abs(a[i].first - a[(i + 1) % sz].first);
				mn = min(mn, {min(len, n - len), i});
			}
		}
		ans += mn.first;
		int x = mn.second;
		int y = (x + 1) % sz;
		if (x > y) {
			swap(x, y);
		}
		a.erase(a.begin() + y);
		a.erase(a.begin() + x);
	}
	cout << 1ll * n * (n - 1) / 2 - ans << '\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... |