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 int ll
#define pii pair<ll, ll>
#define f first
#define s second
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
#define pb push_back
#define MX(a,b) a=max(a,b)
#define MN(a,b) a = min(a,b)
#define FOR(i,a,b) for (int i = a; i<b; ++i)
#define REP(i,n) FOR(i,0,n)
#define REP1(i,n) FOR(i,1,n+1)
#ifdef BALBIT
#define bug(...) cerr<<"#"<<__LINE__<<": "<<#__VA_ARGS__<<"- ", _do(__VA_ARGS__)
template<typename T> void _do( T && x) {cerr<<x<<endl;}
template<typename T, typename ...S> void _do( T && x, S && ...y) {cerr<<x<<", "; _do(y...);}
#else
#define bug(...)
#define endl '\n'
#endif // BALBIT
const int maxn = 1e5+5;
int ps[15][maxn];
int a[maxn];
int frm[15][1<<15];
int sf[15][maxn], sb[15][maxn]; // sig front, sig back
vector<int> where[15];
const int G = 15;
ll dp[1<<15];
signed main(){
ios::sync_with_stdio(0), cin.tie(0);
bug(1,2);
string _baa; cin>>_baa;
int n = SZ(_baa);
REP(i, n) {
a[i+1] = _baa[i] - 'A';
}
// a is 1-indexed!!
REP(g, G) {
REP1(i,n) {
ps[g][i] = ps[g][i-1] + (a[i] == g);
}
}
REP1(i,n) {
where[a[i]].pb(i);
}
REP(to,G) {
memset(sf, 0, sizeof sf); memset(sb, 0, sizeof sb);
REP(oth,G) {
REP1(i,n) {
sf[oth][i] = sf[oth][i-1];
if (a[i] == to) {
sf[oth][i] += ps[oth][i-1];
}
}
for (int i = n; i>=1; --i) {
sb[oth][i] = sb[oth][i+1];
if (a[i] == to) {
sb[oth][i] += (ps[oth][n] - ps[oth][i]);
}
}
}
REP(M, (1<<G)) {
if (M & (1<<to)) continue;
int bl = 0, br = SZ(where[to]); // first node where it's better to go to the right
while (bl != br) {
int bm = (bl + br) /2;
int i = where[to][bm];
int sl=ps[to][i-1],sr=(ps[to][n]-ps[to][i]);
REP(oth, G) {
if (M & (1<<oth)) {
sl += ps[oth][i-1] * 2;
sr += (ps[oth][n] - ps[oth][i]) * 2;
}
}
if (sr < sl) {
br = bm;
}else{
bl = bm+1;
}
}
if (bl-1 >=0) {
int i = where[to][bl-1];
frm[to][M] += sf[to][i];
REP(oth, G) {
if (M & (1<<oth)) {
frm[to][M] += sf[oth][i] * 2;
}
}
}
if (bl < SZ(where[to])) {
int i = where[to][bl];
frm[to][M] += sb[to][i];
REP(oth, G) {
if (M & (1<<oth)) {
frm[to][M] += sb[oth][i] * 2;
}
}
}
}
}
memset(dp, 0x3f, sizeof dp);
REP(M, (1<<G)) {
if (M == 0) {
dp[M] = 0; continue;
}
REP(j, G) {
if (M & (1<<j)) {
MN(dp[M], dp[M^(1<<j)] + frm[j][M^(1<<j)]);
}
}
}
ll re = dp[(1<<G)-1];
if (re % 2 == 0) cout<<re/2<<endl;
else cout<<(re/2)<<".5"<<endl;
// cout<<(dp[(1<<G)-1]/2.0)<<endl;
}
# | 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... |