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
#include <iostream>
#include <queue>
#include <utility>

namespace {
    using std::string;
    using std::cin;
    using std::getline;
    using std::cout;
    using std::swap;
    using queue_t = std::queue<size_t>;

    void swap_pair(
        size_t & cnt, queue_t & q, string & word, size_t i, size_t k
    ) noexcept {
        cnt += k - i;
        swap(word[i], word[k]);
        q.pop();
    }
}

int main() {
    string word;
    queue_t q;
    size_t swap_cnt = 0;
    getline(cin, word);
    size_t const WORD_HALF = word.length() / 2;
    size_t const WORD_END = word.length() - 1;
    size_t k = 0;
    for (k = 0; k < WORD_HALF; ++k) {
        if (!q.empty())
        {
            if (word[q.front()] != word[k]) {
                swap_pair(swap_cnt, q, word, q.front(), k);
            } else if (word[WORD_END - q.front()] != word[WORD_END - k]) {
                swap_pair(swap_cnt, q, word, WORD_END - k, WORD_END - q.front());
            }
        }
        if (word[k] != word[WORD_END - k])
            q.push(k);
    }
    if (word.length() % 2 == 0 && q.size() % 2 == 1) {
        cout << "-1";
    } else {
        while (q.size() > 1 && k < word.length()) {
            if (word[q.front()] != word[k]) {
                swap_pair(swap_cnt, q, word, q.front(), k);
                while (!q.empty() && word[q.front()] == word[WORD_END - q.front()])
                    q.pop();
            } else {
                ++k;
            }
        }
        if (word.length() % 2 == 0) {
            if (q.empty())
                cout << swap_cnt;
            else
                cout << "-1";
        } else {
            if (q.empty())
                cout << swap_cnt;
            else
                cout << swap_cnt + WORD_HALF - q.front();
        }
    }
    return 0;
}