/* -*- coding: utf-8 -*- * * 1951.cc: No.1951 消えたAGCT(2) - yukicoder */ #include #include using namespace std; /* constant */ const int MAX_N = 500000; enum { A = 'A' - 'A', G = 'G' - 'A', C = 'C' - 'A', T = 'T' - 'A' }; /* typedef */ template struct BIT { int n; T bits[MAX_N + 1]; BIT() {} BIT(int _n) { init(_n); } void init(int _n) { n = _n; } T sum(int x) { x = min(x, n); T s = 0; while (x > 0) { s += bits[x]; x -= (x & -x); } return s; } void add(int x, T v) { if (x <= 0) return; while (x <= n) { bits[x] += v; x += (x & -x); } } int lower_bound(T v) { int k = 1; while ((k << 1) <= n) k <<= 1; int x = 0; for (; k > 0; k >>= 1) if (x + k <= n && bits[x + k] < v) { x += k; v -= bits[x]; } return x + 1; } }; /* global variables */ char s[MAX_N + 4]; int cs[26]; BIT bit; /* subroutines */ inline int prv(int x, int d) { return (x + 26 - d) % 26; } /* main */ int main() { int n; scanf("%d%s", &n, s); for (int i = 0; i < n; i++) cs[s[i] - 'A']++; bit.init(n); for (int i = 1; i <= n; i++) bit.add(i, 1); int cnt = 0, d = 0; for (;; cnt++) { int c1 = cs[prv(A, d)] + cs[prv(G, d)] + cs[prv(C, d)] + cs[prv(T, d)]; if (c1 == 0) break; int x = bit.lower_bound(c1); bit.add(x, -1); int c2 = --cs[s[x - 1] - 'A']; d = (d + c2) % 26; //printf("c1=%d, c2=%d, x=%d, d=%d\n", c1, c2, x, d); } printf("%d\n", cnt); return 0; }