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.
Input
Each line contains one line the string S with length N (N <= 1000000) formed by lower case letters.
Output
Output four integers separated by one space, lexicographically fisrt string’s Rank (if there are multiple answers, choose the smallest one), the string’s times in the N generated strings, lexicographically last string’s Rank (if there are multiple answers, choose the smallest one), and its times also.
Sample Input
abcder aaaaaa ababab
Sample Output
1 1 6 1 1 6 1 6 1 3 2 3
最小表示法的介绍在这里学习的:https://www.cnblogs.com/lykkk/p/10425418.html
求最小字典序的字符串是第几个以及它出现的次数(就是求最小循环节的个数),以及最大字典序的字符串是第几个以及它出现的次数。
最小和最大字典序的位置用最大最小表示法来做,循环节的个数用KMP的next数组来求。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
const int maxn=1e6+5;
char str[maxn];
int net[maxn];
map<char ,int>mapp;
int n;
void getnet(char *s,int net[])
{
net[0]=-1;
int j=0;
int k=-1;
int slen=strlen(s);
while(j<slen)
{
if(k==-1 || s[j]==s[k])
{
j++;
k++;
net[j]=k;
}
else
k=net[k];
}
}
int Min(char *s)//最小
{
int i=0,j=1,k=0;
int slen=strlen(s);
while(i<slen && j<slen && k<slen)
{
if(s[(i+k)%slen]==s[(j+k)%slen])
k++;
else
{
if(s[(i+k)%slen]>s[(j+k)%slen])
i+=k+1;
else
j+=k+1;
if(i==j)
j++;
k=0;
}
}
return min(i,j);
}
int Max(char *s)//最大
{
int i=0,j=1,k=0;
int slen=strlen(s);
while(i<slen && j<slen && k<slen )
{
if(s[(i+k)%slen]==s[(j+k)%slen])
k++;
else
{
if(s[(i+k)%slen]>s[(j+k)%slen])
j+=k+1;
else
i+=k+1;
if(i==j)
j++;
k=0;
}
}
return min(i,j);
}
int main()
{
while(scanf("%s",str)!=EOF)
{
int len=strlen(str);
getnet(str,net);
int t=len-net[len];
int num=1;
if(len%t==0)
{
num=len/t;
}
int ans1=Min(str);
int ans2=Max(str);
printf("%d %d %d %d\n",ans1+1,num,ans2+1,num);
}
return 0;
}