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
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string slowo;
    cin >> slowo;
    int k = slowo.size() / 2, g=k; //k - srodek slowa; g - srodek dla nieparzystych wyrazow
    int a=0, b=0;
    if (slowo.size() % 2 == 1) {
        if (slowo[g] == 'a') a++;
        else b++;
        k++;
    }
    int zmiany = 0, tmp=0;

    for (int i = 0; i < slowo.size(); i++) {
        if (slowo[i] == 'a') a++;
        else b++;

    }

    if (slowo.size() <= 2 || ((a<2 || b<2) && slowo.size()%2==1) || (slowo.size()%2==0 && a%2==1)) cout << -1;
    else {
        for (int i = 0; i < slowo.size() / 2; i++) {
            if (slowo[i] != slowo[slowo.size() - 1 - i]) {
                int tmpA = 0, tmpB = 0, j = i;
                while (slowo[slowo.size() - 1 - i] != slowo[j] && j<slowo.size()) {
                    tmpA++;
                    j++;
                }
                j = slowo.size() - 1 - i;
                while (slowo[i] != slowo[j] && j>=0) {
                    tmpB++;
                    j--;
                }
                if (tmpB > tmpA) {
                    zmiany += tmpA;
                    swap(slowo[i], slowo[i + tmpA]);
                }
                else {
                    zmiany += tmpB;
                    swap(slowo[slowo.size() - 1 - i], slowo[slowo.size() - 1 - i - tmpB]);
                }
            }
        }
        cout << zmiany;
    }
}