hdu3374最大最小表示法加kmp

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<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 1000005
using namespace std;
char p[maxn];
int m;
int f[maxn];
void getfail(char *P, int *f)
{

    f[0] = f[1] = 0;
    for(int i = 1; i < m; i++)//虽然字符串是0到m-1,但是要求出f[m]的值
    {
        int j = f[i];
        while(j && P[i] != P[j]) j = f[j];
        f[i + 1] = P[i] == P[j] ? j + 1 : 0;
    }
}
int getmin(char*s)
{


    int i=0,j=1,k=0;
    while(i<m&&j<m&&k<m)
    {
        int t=s[(i+k)%m]-s[(j+k)%m];
        if(t==0)
            k++;
        else
        {
            if(t>0)
                i+=k+1;
            else
                j+=k+1;
            if(i==j)
                j++;
            k=0;
        }
    }
    return min(i,j);
}
int getmax(char*s)
{
    int i=0,j=1,k=0;
    while(i<m&&j<m&&k<m)
    {
        int t=s[(i+k)%m]-s[(j+k)%m];
        if(t==0)
            k++;
        else
        {
            if((t>0))
                j+=k+1;
            else
                i+=k+1;
            if(i==j)
                j++;
            k=0;
        }
    }
    return min(i,j);
}
int main()
{
    while(~scanf("%s",p))
    {
        m=strlen(p);
        getfail(p,f);
        int ans;
        if(m%(m-f[m])==0)
            ans=m/(m-f[m]);
            else ans=1;
            printf("%d %d %d %d\n",getmin(p)+1,ans,getmax(p)+1,ans);
    }
    return 0;
}

​

猜你喜欢

转载自blog.csdn.net/sdauguanweihong/article/details/87989560
今日推荐