后缀数组,求不同回文子串的数量
#include <STDIO.H> #include <STRING.H> // hdu 3948 const int MAXN = 200010; int wa[MAXN], wb[MAXN], ws[MAXN], wv[MAXN]; int rank[MAXN], height[MAXN], r[MAXN], sa[MAXN]; inline int min(const int a, const int b){return a<b?a:b;} inline void swap(int &x, int &y) {int a = x; x = y; y = a;} bool cmp(int *r, int a, int b, int l) { return (r[a] == r[b] && r[a+l] == r[b+l]); } // r: 待排序的字符串,长度为n,最大值小于m // ws:基数排序 // sa:存放排序结果 void da(int *r, int *sa, int n, int m) { //用倍增算法求后缀数组 int i, j, p, *x = wa, *y = wb, *t; // 使用基数排序对长度为1的字符串进行排序 for (i = 0; i< m; ++i) ws[i] = 0; // 初始化ws for (i = 0; i< n; i++) ws[x[i]=r[i]]++; for (i = 1; i< m; i++) ws[i]+=ws[i-1]; for (i = n-1; i>= 0; --i) sa[--ws[x[i]]] = i; // 进行若干次基数排序,基数排序要分两次,第一次是对第二关键字排序 // 第二次是对第一关键字排序。对第二关键字排序的结果可以利用上一次求得的sa直接算出 for (j=1, p=1; p< n; j*=2, m=p) { for (p=0, i=n-j; i< n; ++i) y[p++] = i; //变量j是当前字符串的长度,数组y保存的是对第二关键字排序的结果 for (i=0; i< n; ++i) if (sa[i] >= j) y[p++] = sa[i] - j; for (i=0; i< n; ++i) wv[i] = x[y[i]]; for (i=0; i< m; ++i) ws[i] = 0; for (i=0; i< n; ++i) ws[wv[i]]++; for (i=1; i< m; ++i) ws[i]+= ws[i-1]; for (i=n-1; i>=0; --i) sa[--ws[wv[i]]] = y[i]; // 计算rank 值 for (t=x,x=y,y=t,p=1,x[sa[0]]=0,i=1; i< n; ++i) x[sa[i]] = cmp(y, sa[i-1], sa[i], j)?p-1:p++; } } /* height:定义height[i]=suffix(sa[i-1])和suffix(sa[i])的最长公共前缀, 也就是排名相邻的两个后缀的最长公共前缀 */ void calHeight(int *r, int *sa, int n) { int i, j, k = 0; for (i = 1; i<= n; ++i) rank[sa[i]] = i; for (i = 0; i< n; height[rank[i++]] = k) for (k?k--:0, j = sa[rank[i]-1]; r[i+k] == r[j+k]; k++); } char str[MAXN]; // 将字符串翻转后用一个特殊字符间隔连接到原字符串后 int mGet() // r = str + '*' + reverse(str) { int l; for (l = 0; str[l]; l++) r[l] = str[l]; r[l] = '#'; for (int i = l-1; i >= 0; i--) r[++l] = str[i]; r[++l] = 0; return l; } int LOG[MAXN]; int st[MAXN][20]; /* st[i][j]表示height[j]到height[j+2^i-1]的最小值 初始化st[i][0]=height[i],st[i][j]=min(st[i][j-1],st[i+(1<<j-1)][j-1]) */ void initRMQ(const int &n) { //初始化RMQ int i, j, k, limit ; for (i=0; i< n; ++i) st[i][0] = height[i]; k = LOG[n]; for (j = 1; j<= k; ++j) { limit = n - (1<<(j-1)); for (i = 0; i<= limit; ++i) st[i][j] = min(st[i][j-1], st[i+(1<<(j-1))][j-1]); } } int query(int x, int y) { if (x > y) swap(x, y); ++x; int k= LOG[y-x+1]; return min(st[x][k], st[y-(1<<k)+1][k]); } int solve(int n) { int ans = 0, st1 = 0, st2 = 0; int j; rank[n] = 0; for (int i = 2; i<= n; ++i) { st1 = min(st1, height[i]); j = query(i, rank[n-sa[i]-1]); if (j > st1) ans += j-st1, st1 = j; st2 = min(st2, height[i]); j = query(i, rank[n-sa[i]]); if ( j > st2) ans += j-st2, st2 = j; } return ans; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif int t, cs = 0; int i; // LOG[i] == log2 i ; for (i = 1, LOG[0] = -1; i< MAXN; ++i) LOG[i] = LOG[i>>1] + 1; scanf("%d", &t); while (t--) { scanf("%s", str); int n = mGet(); da(r, sa, n+1, 128); calHeight(r, sa, n); initRMQ(n+1); printf("Case #%d: %d\n", ++cs, solve(n)); } return 0; }