#include <bits/stdc++.h>
#define len(s) (ll) s.size()
using namespace std;
typedef long long ll;
typedef long double ld;
const int N = 2e5 + 11;
const int MAX = 1e6;
const long long inf = 1e18 + 10;
ll n;
ll a[N], dp[(1 << 16)], pr[30][N], sf[30][N], cnt[30][30][N];
string s, t;
vector<ll> g[N];
ll f(ll x, ll pos, ll msk)
{
ll ans = pos * (pos - 1) / 2 + (len(g[x]) - pos) * (len(g[x]) - pos - 1) / 2;
for (ll y = 0; y < 15; y++)
if (x != y && (msk >> y & 1))
ans += cnt[x][y][pos] * 2;
return ans;
}
int main()
{
cin >> s, n = len(s);
for (ll i = 0; i < n; i++)
a[i] = s[i] - 'A', g[a[i]].push_back(i);
for (ll x = 0; x < 15; x++)
{
for (ll y = 0; y < 15; y++)
{
if (x == y)
continue;
for (ll i = 0; i < len(g[x]) + 10; i++)
pr[x][i] = sf[x][i] = 0;
for (ll i = 0, j = 0; i < len(g[x]); i++)
{
while (j < len(g[y]) && g[y][j] <= g[x][i])
j++;
pr[x][i + 1] = pr[x][i] + j;
}
for (ll i = len(g[x]) - 1, j = len(g[y]) - 1; i >= 0; i--)
{
while (j >= 0 && g[y][j] >= g[x][i])
j--;
sf[x][i + 1] = sf[x][i + 2] + len(g[y]) - j - 1;
}
for (ll i = 0; i <= len(g[x]); i++)
cnt[x][y][i] = pr[x][i] + sf[x][i + 1];
}
}
for (ll msk = 1; msk < (1 << 15); msk++)
{
dp[msk] = inf;
for (ll i = 0; i < 15; i++)
{
if ((msk >> i & 1))
{
dp[msk] = min(dp[msk], dp[(msk ^ (1 << i))] + f(i, 0, msk));
ll l = 1, r = len(g[i]);
while (r - l > 1)
{
ll middle = (l + r) / 2;
if (f(i, middle, msk) > f(i, middle + 1, msk))
l = middle;
else
r = middle;
}
for (ll j = l; j <= r; j++)
dp[msk] = min(dp[msk], dp[(msk ^ (1 << i))] + f(i, j, msk));
}
}
}
ll ans = dp[(1 << 15) - 1];
if (ans % 2)
cout << ans / 2 << ".5";
else
cout << ans / 2;
}
# | 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... |