Give you a string with length N, you can generate N strings by left shifts. For example let consider the string “SKYLONG”, we can generate seven strings:
String Rank
SKYLONG 1
KYLONGS 2
YLONGSK 3
LONGSKY 4
ONGSKYL 5
NGSKYLO 6
GSKYLON 7
and lexicographically first of them is GSKYLON, lexicographically last is YLONGSK, both of them appear only once.
Your task is easy, calculate the lexicographically fisrt string’s Rank (if there are multiple answers, choose the smallest one), its times, lexicographically last string’s Rank (if there are multiple answers, choose the smallest one), and its times also.
题意:给出一个字符串,求出它循环同构的字符串中字典序最小的一个串的开始位置,以及有多少串是同样字典序最小的,然后同样求出字典序最大的串的这两个值
先用最大/最小表示法求出字典序最大或最小的串,并在原串的倍增串中进行KMP匹配。
1 #include<stdio.h>
2 #include<string.h>
3 #include<algorithm>
4 using namespace std;
5
6 const int maxn=1e6+5;
7 char s[maxn<<1],ss[maxn<<1];
8 char tmp[maxn];
9 int p[maxn<<1];
10
11 inline int max(int a,int b){return a>b?a:b;}
12 inline int min(int a,int b){return a<b?a:b;}
13
14 int KMP(char s[],char t[]){
15 int i,j,ans=0; //ans记录字符串出现次数
16 int n=strlen(s),m=strlen(t); //在题目中遇到过,其实strlen很慢,所以如果不先存起来可能有TLE的风险
17 p[0]=p[1]=0; //初始化自匹配数组
18 for(i=1;i<m;i++){ //自匹配
19 j=p[i];
20 while(j&&t[i]!=t[j])j=p[j];
21 p[i+1]=t[i]==t[j]?j+1:0;
22 }
23 j=0; //注意 j=0
24 for(i=0;i<n-1;i++){ //串匹配
25 while(j&&s[i]!=t[j])j=p[j];
26 if(s[i]==t[j])j++;
27 if(j==m){
28 ans++; //此处记录出现次数(模板串在待匹配串中可重叠),或改为直接break表示是否出现过
29 }
30 }
31 return ans;
32 }
33
34 int MINR(char s[],int l){
35 for(int i=0;i<l;++i)s[l+i]=s[i];
36 s[2*l]=0;
37 int i=0,j=1;
38 while(i<l&&j<l){
39 int k=0;
40 while(s[i+k]==s[j+k]&&k<l)++k;
41 if(k==l)return min(i,j);
42 if(s[i+k]>s[j+k])i=max(i+k+1,j+1);
43 else j=max(j+k+1,i+1);
44 }
45 return min(i,j);
46 }
47
48 int MAXR(char s[],int l){
49 for(int i=0;i<l;++i)s[l+i]=s[i];
50 s[2*l]=0;
51 int i=0,j=1;
52 while(i<l&&j<l){
53 int k=0;
54 while(s[i+k]==s[j+k]&&k<l)++k;
55 if(k==l)return min(i,j);
56 if(s[i+k]<s[j+k])i=max(i+k+1,j+1);
57 else j=max(j+k+1,i+1);
58 }
59 return min(i,j);
60 }
61
62 int main(){
63 while(scanf("%s",s)!=EOF){
64 int l=strlen(s);
65 strcpy(ss,s);
66 int pos=MINR(ss,l);
67 for(int i=0;i<l;++i)tmp[i]=ss[i+pos];
68 tmp[l]=0;
69 printf("%d %d ",pos+1,KMP(ss,tmp));
70 strcpy(ss,s);
71 pos=MAXR(ss,l);
72 for(int i=0;i<l;++i)tmp[i]=ss[i+pos];
73 tmp[l]=0;
74 printf("%d %d
",pos+1,KMP(ss,tmp));
75 }
76 return 0;
77 }