题目链接https://vjudge.net/problem/16282/origin
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
题目大意,给你一个字符串,按字典序求最小的循环同构字符串第几个出现,出现几次,最大的第几个出现,出现几次。
先上代码
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
char s[1000010];
int nest[1000010];
void get_nest()
{
int i=0,j=-1;
nest[0]=-1;
for(; s[i];)
if(j==-1||s[i]==s[j])
{
++i;
++j;
nest[i]=j;
}
else j=nest[j];
}
int minx(int len)
{
int i=0,j=1,k=0,t;
for(;i<len&&j<len&&k<len;)
{
if(s[(i+k)%len]==s[(j+k)%len])
{
++k;
}
else
{
if(s[(i+k)%len]>s[(j+k)%len])
{
i=i+k+1;
}
else
{
j=j+k+1;
}
if(i==j)
{
++j;
}
k=0;
}
}
if(i<j)
{
return i;
}
else
{
return j;
}
}
int maxx(int len)
{
int i=0,j=1,k=0,t;
for(;i<len&&j<len&&k<len;)
{
if(s[(i+k)%len]==s[(j+k)%len])
{
++k;
}
else
{
if(s[(i+k)%len]<s[(j+k)%len])
{
i=i+k+1;
}
else
{
j=j+k+1;
}
if(i==j)
{
++j;
}
k=0;
}
}
if(i<j)
{
return i;
}
else
{
return j;
}
}
int main ()
{
while(~scanf("%s",&s))
{
int len=strlen(s);
get_nest();
int min=minx(len);
int max=maxx(len);
int r=len-nest[len];
if(len%r==0)
{
r=len/r;
}
else
{
r=1;
}
printf("%d %d %d %d\n",min+1,r,max+1,r);
}
}
比较两个字符串肯定会超时的,对应的两个字符串的大小可以用比较对应的字符大小来表示。
最小表示法。
令i=0,j=1
如果S[i] > S[j] i=j, j=i+1
如果S[i] < S[j] j++
如果S[i]==S[j] 设指针k,分别从i和j位置向下比较,直到S[i] != S[j]
如果S[i+k] > S[j+k] i=i+k
否则j++
返回i和j的小者,这种思路下时间复杂度为O(N)。