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;
string str;
long long f[1 << 15];
vector<int> pos[15];
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> str;
int n = *max_element(str.begin(), str.end()) - 'A' + 1;
for (int i = 0; i < str.size(); i++) {
pos[str[i] - 'A'].push_back(i);
}
fill(f + 1, f + (1 << n), 1e18);
for (int S = 0; S < 1 << n; S++) {
for (int i = 0; i < n; i++) if (!(S >> i & 1)) {
if (pos[i].empty()) { f[S | (1 << i)] = f[S]; continue; }
auto calc = [&](int p) {
int c0 = 0, c1 = 0;
long long s = 0;
for (int j = p; ~j; j--) {
if (str[j] - 'A' == i) c0++;
else if (S >> (str[j] - 'A') & 1) s += c0;
}
for (int j = p + 1; j < str.size(); j++) {
if (str[j] - 'A' == i) c1++;
else if (S >> (str[j] - 'A') & 1) s += c1;
}
return 2 * s + 1LL * c0 * (c0 - 1) / 2 + 1LL * c1 * (c1 - 1) / 2;
};
f[S | (1 << i)] = min(f[S | (1 << i)], f[S] + calc(-1));
int l = 1, r = pos[i].size() - 1, p = 0;
while (l <= r) {
int mid = (l + r) / 2;
calc(pos[i][mid]) < calc(pos[i][mid - 1]) ? l = (p = mid) + 1 : r = mid - 1;
}
f[S | (1 << i)] = min(f[S | (1 << i)], f[S] + calc(pos[i][p]));
}
}
cout << f[(1 << n) - 1] / 2 << (f[(1 << n) - 1] % 2 ? ".5" : "") << "\n";
return 0;
}
Compilation message (stderr)
passes.cpp: In function 'int main()':
passes.cpp:12:23: warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
12 | for (int i = 0; i < str.size(); i++) {
| ~~^~~~~~~~~~~~
passes.cpp: In lambda function:
passes.cpp:26:39: warning: comparison of integer expressions of different signedness: 'int' and 'std::__cxx11::basic_string<char>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
26 | for (int j = p + 1; j < str.size(); j++) {
| ~~^~~~~~~~~~~~
# | 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... |