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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| #include <cstdio> #include <queue> #include <cstring> #include <algorithm> using namespace std; template <class Type> void read (Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0'; flag && (x = ~x + 1); } template <class Type, class ...rest> void read (Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write (Type x) { x < 0 && (putchar('-'), x = ~x + 1); x > 9 && (write(x / 10), 0); putchar('0' + x % 10); } const int N = 1e5 + 10; char str[N]; int n, cnt, last, g[N], f[N]; struct Node { int p, len, nxt[4]; } tr[N]; int get (int x, int t) { while (str[t - 1 - tr[x].len] != str[t]) x = tr[x].p; return x; } int main () { int T; read(T); while (T--) { scanf("%s", str + 1), str[0] = '$'; n = strlen(str + 1); tr[0].p = 1, tr[1].len = -1; last = 0, cnt = 2; for (int i = 1; i <= n; ++i) { int c, p = get(last, i); if (str[i] == 'A') c = 0; else if (str[i] == 'T') c = 1; else if (str[i] == 'C') c = 2; else if (str[i] == 'G') c = 3; if (!tr[p].nxt[c]) { int q = cnt++; tr[q].len = tr[p].len + 2; tr[q].p = tr[get(tr[p].p, i)].nxt[c]; tr[p].nxt[c] = q; if (tr[q].len <= 2) g[q] = tr[q].p; else { int t = g[p]; while (str[i - 1 - tr[t].len] != str[i] || (tr[t].len + 2) * 2 > tr[q].len) t = tr[t].p; g[q] = tr[t].nxt[c]; } } last = tr[p].nxt[c]; } for (int i = 2; i < cnt; ++i) f[i] = tr[i].len; queue <int> q; q.push(0); f[0] = 1; int res = n; while (!q.empty()) { int t = q.front(); q.pop(); for (int i = 0; i < 4; ++i) { int v = tr[t].nxt[i]; if (!v) continue; f[v] = min(f[t] + 1, f[g[v]] + 1 + tr[v].len / 2 - tr[g[v]].len); res = min(res, f[v] + n - tr[v].len); q.push(v); } } for (int i = 0; i < cnt; ++i) for (int j = 0; j < 4; ++j) tr[i].nxt[j] = 0; write(res), puts(""); } return 0; }
|