1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>
using namespace std;

class SOLVE
{
public:
    int cc[200];
    deque<int> p[200];

    const int S = 2 << 18;
    int sc[2 << 19]{};

    template <class T = int>
    T query(int w, int p, int k, int pp, int kk)
    {
        if (pp > k || kk < p)
        {
            return 0;
        }
        if (pp <= p && kk >= k)
        {
            return sc[w];
        }
        T p1 = query(w * 2, p, (p + k) / 2, pp, kk), p2 = query(w * 2 + 1, (p + k) / 2 + 1, k, pp, kk);
        return p1 + p2;
    }

    void insert(int w)
    {
        w += S;
        while (w)
        {
            sc[w]++;
            w /= 2;
        }
    }
    int solveMe(string s)
    {
        int np = 0;
        int j = 0;
        for (auto i : s)
        {
            cc[i]++;
            p[i].push_back(j++);
            np += (cc[i] % 2) ? 1 : -1;
        }
        int rozw = 0;
        long long wn = 0;
        if (np > 1)
        {
            cout << "-1\n";
            exit(0);
        }
        for (auto i : s)
        {
            if (p[i].size() == 0)
                continue;
            if (p[i].size() == 1)
            {
                wn += (s.size() / 2 - rozw);
                continue;
            }
            p[i].pop_front();
            int op = s.size() - rozw - 1;
            long long k = op - p[i].back() + query(1, 1, (int)S, 1, p[i].back());
            if (op > p[i].back())
                wn += k;
            // cout << wn << ' ' << op << ' ' << p[i].back() << ' ' << k << '\n';
            insert(p[i].back());
            p[i].pop_back();
            rozw++;
        }
        return wn;
    }
};

int main()
{
    ios_base::sync_with_stdio(0);
    string s;
    cin >> s;
    int wn = SOLVE().solveMe(s);
    // cout << wn << '\n';
    reverse(s.begin(), s.end());
    wn = max(wn, SOLVE().solveMe(s));
    cout << wn << '\n';
}