1511: [poi2006] okr-periods of wordstime limit: 5 sec memory limit: 64 MB
Submit: 174 solved: 92
[Submit] [Status] Description a string is a sequence of limited lowercase characters. In particular, an empty sequence can also be a string. A string P is the prefix of string a. if and only if string B exists, make a = Pb. if p a and P is not an empty string, P is a proper prefix of. defines the cycle of Q As A. Only when Q is a proper prefix of A and A is a QQ prefix (not necessarily proper prefix ). for example, both Abab and ababab are the cycles of abababa. the maximum cycle of A is the longest cycle or an empty string (when a has no cycle). For example, the maximum cycle of A is Abab. the maximum period of the string ABC is an empty string. returns a string and returns the sum of the maximum cycle lengths of all its prefixes. the first line of input is an integer k (1 K 1 000 000 000) indicating the length of the string. the next line indicates the string given. output outputs an integer to indicate the sum of the maximum cycle lengths of all its prefixes. sample input8
Babababa
Sample output24
Hintsource
Question:
I thought for a while and found that the maximum period is actually the Len of the prefix -- the shortest prefix = The suffix Len
The correctness is obvious, and then KMP is done.
Code:
1 #include<cstdio> 2 3 #include<cstdlib> 4 5 #include<cmath> 6 7 #include<cstring> 8 9 #include<algorithm>10 11 #include<iostream>12 13 #include<vector>14 15 #include<map>16 17 #include<set>18 19 #include<queue>20 21 #include<string>22 23 #define inf 100000000024 25 #define maxn 1000000+526 27 #define maxm 500+10028 29 #define eps 1e-1030 31 #define ll long long32 33 #define pa pair<int,int>34 35 #define for0(i,n) for(int i=0;i<=(n);i++)36 37 #define for1(i,n) for(int i=1;i<=(n);i++)38 39 #define for2(i,x,y) for(int i=(x);i<=(y);i++)40 41 #define for3(i,x,y) for(int i=(x);i>=(y);i--)42 43 #define mod 100000000744 45 using namespace std;46 47 inline int read()48 49 {50 51 int x=0,f=1;char ch=getchar();52 53 while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}54 55 while(ch>=‘0‘&&ch<=‘9‘){x=10*x+ch-‘0‘;ch=getchar();}56 57 return x*f;58 59 }60 int n,next[maxn];61 ll ans;62 char s[maxn];63 64 int main()65 66 {67 68 freopen("input.txt","r",stdin);69 70 freopen("output.txt","w",stdout);71 72 n=read();73 scanf("%s",s+1);74 for(int i=2,j=0;i<=n;i++)75 {76 while(j&&s[j+1]!=s[i])j=next[j];77 if(s[j+1]==s[i])j++;78 next[i]=j;79 }80 for1(i,n)if(next[next[i]]!=0)next[i]=next[next[i]];81 for1(i,n)if(next[i])ans+=(ll)(i-next[i]);82 printf("%lld\n",ans);83 84 return 0;85 86 }
View code
Bzoj1511: [poi2006] okr-periods of words