#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
void bucket_sort(int M, vector<int>& arr, function<int(int)> cmp){
vector<vector<int>> buckets(M);
for (int x : arr){
buckets[cmp(x)].push_back(x);
}
int idx = 0;
for (int i = 0; i < M; i++){
for (int x : buckets[i]){
arr[idx++] = x;
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
string S;
cin >> S;
int N = S.size();
int G = 10;
vector<int> masks(1 << G);
iota(masks.begin(), masks.end(), 0);
bucket_sort(G+1, masks, [](int mask){
return __builtin_popcount(mask);
});
vector<long long> cost(1 << G, 1e18);
cost[0] = 0;
for (int mask : masks){
for (int i = 0; i < G; i++){
if (mask & (1 << i))
continue;
int cnt_i = 0, cnt_s = 0;
for (int j = 0; j < N; j++){
int g = S[j] - 'A';
if (g == i)
cnt_i++;
if (mask & (1 << g))
cnt_s++;
}
long long c = 0;
int cnt_i_pre = 0, cnt_s_pre = 0;
for (int j = 0; j < N; j++){
int g = S[j] - 'A';
if (g == i){
cnt_i--;
c += min(cnt_i_pre + 2*cnt_s_pre, cnt_i + 2*cnt_s);
cnt_i_pre++;
} else if (mask & (1 << g)){
cnt_s_pre++;
cnt_s--;
}
}
cost[mask | (1 << i)] = min(cost[mask | (1 << i)], cost[mask] + c);
}
}
long long ans = cost[(1 << G) - 1];
cout << ans / 2 << ((ans & 1) ? ".5" : "") << "\n";
return 0;
}
| # | 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... |