6 1 a 1 b 2 a 2 c 3 4 8 1 a 2 a 2 a 1 a 3 1 b 3 4
4 5 4 5 11
回文树的巧妙应用,可以双端加入字符,询问回文子串的数量,因为是回文的,只要在原来的回文树基础上添加一个指向前端的指针,然后随时更新即可。
#pragma comment(linker, "/STACK:102400000,102400000") #include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<bitset> #include<cstdio> #include<string> #include<cstring> #include<algorithm> #include<functional> using namespace std; typedef long long LL; const int low(int x) { return x&-x; } const int INF = 0x7FFFFFFF; const int maxn = 2e5 + 10; int T, x; char ch[2]; struct linklist { int nt[maxn], ft[maxn], u[maxn], v[maxn], sz; void clear() { sz = 0; } void clear(int x) { ft[x] = -1; } int get(int x, int y) { for (int i = ft[x]; i != -1; i = nt[i]) { if (u[i] == y) return v[i]; } return 0; } void insert(int x, int y, int z) { u[sz] = y; v[sz] = z; nt[sz] = ft[x]; ft[x] = sz++; } }; struct PalindromicTree { const static int maxn = 2e5 + 10; linklist next; LL sz; int last[2], tot[2]; int fail[maxn], len[maxn], cnt[maxn]; char s[maxn]; void clear() { len[1] = -1; len[2] = 0; fail[1] = fail[2] = 1; cnt[1] = cnt[2] = 0; last[0] = last[1] = (sz = 3) - 1; tot[0] = (tot[1] = T - 1) + 1; next.clear(); next.clear(1); next.clear(2); } int Node(int length) { len[sz] = length; cnt[sz] = 1; next.clear(sz); return sz++; } int getfail(int x, int k) { s[tot[0] - 1] = s[tot[1] + 1] = 0; while (s[tot[k]] != s[tot[k] + (k ? -1 : 1)*(len[x] + 1)]) x = fail[x]; return x; } int add(char pos, int k) { int x = (s[tot[k] += k ? 1 : -1] = pos) - 'a', y = getfail(last[k], k); if (!(last[k] = next.get(y, x))) { next.insert(y, x, last[k] = Node(len[y] + 2)); fail[last[k]] = len[last[k]] == 1 ? 2 : next.get(getfail(fail[y], k), x); cnt[last[k]] += cnt[fail[last[k]]]; if (len[last[k]] == tot[1] - tot[0] + 1) last[k ^ 1] = last[k]; } return cnt[last[k]]; } }solve; int main() { while (scanf("%d", &T) != EOF) { LL ans = 0; solve.clear(); while (T--) { scanf("%d", &x); if (x <= 2) { scanf("%s", ch); ans += solve.add(ch[0], x - 1); } else { printf("%lld\n", x == 3 ? solve.sz - 3 : ans); } } } return 0; }