#include #include #include using namespace std; size_t N; vector A; vector pos[26]; int base_cost[26]; int haslft(size_t i) { return i > 0 && A[i - 1] < A[i] ? 1 : 0; } int hasrht(size_t i) { return i + 1 < N && A[i + 1] < A[i] ? 1 : 0; } #define MAXN 55 int memo[MAXN][MAXN][MAXN]; int solve(int x, size_t L, size_t R) { if (x == -1) { return haslft(L) + hasrht(R - 1); } int& ref = memo[x][L][R]; if (ref != -1) return ref; size_t matched = A[L] == x ? 1 : 0; if (L && A[L - 1] == x) { ++matched; --L; } if (R < N && A[R] == x && L != R) { ++matched; ++R; } if (pos[x].size() == matched) { return solve(x - 1, L, R); } int base = 0; if (A[L] != x) base += haslft(L); if (A[R - 1] != x) base += hasrht(R - 1); ref = N; for (size_t i : pos[x]) { if (i == L || i + 1 == R) { continue; } ref = min(ref, solve(x - 1, i, R) - haslft(i) - hasrht(R - 1)); ref = min(ref, solve(x - 1, L, i + 1) - haslft(L) - hasrht(i)); for (size_t j : pos[x]) { if (j == L || j + 1 == R || i == j) { continue; } ref = min(ref, solve(x - 1, i, j + 1) - haslft(i) - hasrht(j)); } } ref += base + base_cost[x]; return ref; } int main() { string S; cin >> S; for (size_t i = 0; i < S.size(); i++) { if (i == 0 || S[i] != S[i - 1]) { A.push_back(S[i] - 'a'); } } N = A.size(); int mx = -1; for (size_t i = 0; i < A.size(); i++) { mx = max(mx, A[i]); pos[A[i]].push_back(i); base_cost[A[i]] += haslft(i) + hasrht(i); } int result = N; memset(memo, -1, sizeof(memo)); for (size_t i = 0; i < N; i++) { if (A[i] == mx) { result = min(result, solve(mx, i, i + 1)); } } cout << result << endl; return 0; }