http://acm.hdu.edu.cn/showproblem.php?pid=6629
Board questions
1 #define bug(x) cout<<#x<<" is "<<x<<endl 2 #define IO std::ios::sync_with_stdio(0) 3 #include <bits/stdc++.h> 4 #define iter ::iterator 5 using namespace std; 6 typedef long long ll; 7 typedef pair<ll,ll>P; 8 typedef pair<P,P>P1; 9 #define mk make_pair 10 #define pb push_back 11 #define se second 12 #define fi first 13 #define rs o<<1|1 14 #define ls o<<1 15 const int N=1e6+5; 16 ll mod=998244353; 17 int T,n; 18 int next1[N],ex[N]; 19 20 void GETNEXT(char *str) 21 { 22 int i=0,j,po,len=strlen(str); 23 next1[0]=len;//初始化next[0] 24 while(str[i]==str[i+1]&&i+1<len)// Calculation Next [. 1] 25 I ++ ; 26 is the Next1 [ . 1 ] = I; 27 po = . 1 ; // position initialization po of 28 for (I = 2 ; I <len; I ++ ) 29 { 30 IF (the Next1 [I -PO] + I <the Next1 [PO] + PO) // first case, the value can be obtained directly next [i] of 31 is the Next1 [I] = the Next1 [I- PO]; 32 the else // second case , continue to match to get next [i] value 33 is { 34 is J = the Next1 [PO] + weight PO- I; 35 IF (J <0 ) J = 0 ; // if i> po + next [po] , will have to start from scratch match 36 the while (I + J <len && STR [J] == STR [J + I]) // calculate next [i] 37 [ J ++ ; 38 is the Next1 [I] = J; 39 po = I; // update location of po 40 } 41 } 42 } 43 // calculate extend array 44 is void EXKMP ( char * S1, char * S2) 45 { 46 is int = I 0 , J, PO, len = strlen (S1), L2 =strlen (S2); 47 GETNEXT (S2); // calculate substring next array 48 the while (S1 [I] == S2 [I] && I <L2 && I <len) // calculate EX [0] 49 I ++ ; 50 EX [ 0 ] = I; 51 is po = 0 ; // initialize po position 52 is for (I = . 1 ; I <len; I ++ ) 53 is { 54 is IF (the Next1 [I-po] + I <EX [po] + po ) // first case, the value can be obtained directly ex [i] of 55 ex [i] = the Next1 [I- PO]; 56 is the else // second case, to continue to match the values obtained ex [i] of 57 is { 58 J = EX [PO] + weight PO- I; 59 IF (J < 0 ) = J 0 ; // if i> ex [po] + po scratch will have matching 60 the while (I + J <len && J < L2 && S1 [J + I] == S2 [J]) // calculate EX [I] 61 is J ++ ; 62 is EX [I] = J; 63 is po = I; // update po position 64 } 65 } 66 } 67 68 char S [N]; 69 int main () { 70 Scanf ( "%d",&T); 71 while(T--){ 72 scanf("%s",s); 73 //getNext(s); 74 EXKMP(s,s); 75 int len=strlen(s); 76 ll ans=0; 77 for(int i=1;i<len;i++){ 78 //bug(extend[i]); 79 ans+=ex[i]+1; 80 if(ex[i]+i>=len)ans--; 81 } 82 printf("%lld\n",ans); 83 for(int i=0;i<=len+2;i++){ 84 next1[i]=ex[i]=0; 85 } 86 } 87 }