int n; ll ans; int a[N]; char s[N]; bool vis[N]; list<int> id[128];
namespace bit { int a[N]; #define lowbit(x) (x&-x) voidadd(int x) { for(; x <= n; x += lowbit(x)) a[x] += 1; } intquery(int x) { int ans = 0; for(; x >= 1; x -= lowbit(x)) ans += a[x]; return ans; } }
intmain() { scanf("%s", s+1); n = strlen(s+1); for(int i = 1; i <= n; i++) id[s[i]].push_back(i); int tot = 0; for(int i = 0; i < 128; i++) tot += id[i].size()%2; if(n%2 == 0and tot > 0) { cout << "-1"; goto end; } if(n%2 == 1and tot > 1) { cout << "-1"; goto end; } for(int i = 1, pos = 0; i <= n; i++) { if(vis[i]) continue; if(!id[s[i]].size()) continue; if(id[s[i]].size() == 1) a[i] = (n+1)/2; else { pos++; int j = *--id[s[i]].end(); id[s[i]].pop_front(); id[s[i]].pop_back(); a[i] = pos, a[j] = n-pos+1; vis[i] = vis[j] = true; } } for(int i = n; i >= 1; i--) { ans += bit::query(a[i]-1); bit::add(a[i]); }
voidsolve(int l, int r); voidget_left(int l, int r); voidget_right(int l, int r); intbinary_search(Stack &a, Stack &b);
intmain() { scanf("%s", s+1); n = strlen(s+1); for(int i = 1; i <= n; i++) s[i] -= 'a'; Hash::prework(n); solve(1, n); printf("%lld", len); }
voidsolve(int l, int r) { if(l == r) return; int mid = (l+r)>>1; get_left(l, mid); get_right(mid+1, r);
for(int a = 0; a < 3; a++) { for(int b = 0; b < 3; b++) { if(a == b) continue; t.clear(); for(int i = l; i <= mid; i++) if(s[i] == a) ++t[f1[i][b]]; for(int i = mid+1; i <= r; i++) if(s[i] == b) len += t[f2[i][a]]; } }
solve(mid+1, r); for(int i = mid; i >= l; i--) pre.del(s[i]); for(int i = r; i > mid; i--) suf.insert(s[i]); solve(l, mid); for(int i = mid+1; i <= r; i++) suf.del(s[i]); }
voidget_left(int l, int r) { tmp.clear(); for(int i = r; i >= l; i--) tmp.insert(s[i]); for(int i = l; i <= r; i++) { tmp.del(s[i]); for(int a = 0; a < 3; a++) { if(a == s[i]) continue; pre.insert(a); int x = binary_search(pre, tmp); f1[i][a] = (pre.hash1[pre.t-x]*pw[tmp.t-x]%P + tmp.hash2[tmp.t-x])%P; pre.del(a); } pre.insert(s[i]); } } voidget_right(int l, int r) { tmp.clear(); for(int i = r; i >= l; i--) suf.insert(s[i]); for(int i = l; i <= r; i++) { suf.del(s[i]); for(int a = 0; a < 3; a++) { if(a == s[i]) continue; tmp.insert(a); int x = binary_search(tmp, suf); f2[i][a] = (tmp.hash2[tmp.t-x] + suf.hash1[suf.t-x]*pw[tmp.t-x]%P)%P; tmp.del(a); } tmp.insert(s[i]); } } intbinary_search(Stack &pre, Stack &suf) { int l = 0, r = min(pre.t, suf.t); while(l < r) { int mid = (l+r+1)>>1; ll hash1 = (pre.hash1[pre.t] - pre.hash1[pre.t-mid]*pw[mid]%P+P)%P; ll hash2 = (suf.hash1[suf.t] - suf.hash1[suf.t-mid]*pw[mid]%P+P)%P; if(hash1 == hash2) l = mid; else r = mid-1; } return l; }