HDU - 3374——String Problem (最大最小表示法)

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


题意:求出最小子串,最大子串,位置和个数(字符串是头尾相连的)

思路:最大最小表示法的模板题。
最大最小法的难点决解: 转载
如果s[i+k]<s[j+k]那么j+=k+1
为什么呢?
首先s[i]到s[i+k-1]一定是大于等于s[i],因为如果其中有一个数小于s[i],那么这个数一定在s[j]到s[j+k-1]中存在,又因为必定有一个会在后面,所以如果s[j]先碰到了,那么一定不会继续到k的位置的,所以一定不存在比s[i]小的字符。
所以从其中的任意一个字符开始当作起始点,都不会比现在更小,所以只有从选出来的序列的后面那一个字符开始才有可能会是最小。
所以j+=k+1


#include<stdio.h>
#include<string.h>
#include<algorithm>
#define M 1000010
using namespace std;
char a[M];
int nextt[M];
void KMP(int len)
{
    int i=0,j=-1;
    nextt[0]=-1;
    while(i<len)
    {
        if(j==-1||a[i]==a[j])
        {
            nextt[++i]=++j;
        }
        else
            j=nextt[j];
    }
}
int posmin(int len)//最小表示法
{
    int i=0,j=1,k=0;
    while(i<len&&j<len&&k<len)
    {
        int pan=a[(i+k)%len]-a[(j+k)%len];
        if(pan==0)
            k++;
        else
        {
            if(pan>0)
                i+=k+1;
            else
                j+=k+1;
            if(i==j)
                j++;
            k=0;
        }
    }
    return min(i+1,j+1);
}
int posmax(int len)//最大表示法
{
    int i=0,j=1,k=0;
    while(i<len&&j<len&&k<len)
    {
        int pan=a[(i+k)%len]-a[(j+k)%len];
        if(pan==0)
            k++;
        else
        {
            if(pan>0)
                j+=k+1;
            else
                i+=k+1;
            if(i==j)
                j++;
            k=0;
        }
    }
    return min(i+1,j+1);
}
int main()
{
    int ten;
    while(~scanf("%s",a))
    {
        ten=1;
        int len=strlen(a);
        KMP(len);
        if(len%(len-nextt[len])==0)
        {
            ten=len/(len-nextt[len]);
        }
        printf("%d %d %d %d\n",posmin(len),ten,posmax(len),ten);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_41380961/article/details/80273410
今日推荐