HDU——3374 String Problem (最大最小表示法+循环节+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

题意:求最大最小表示法,就是求一个字符串,输出左移补在右边的字典序最大和最小的下标和最小循环节循环的次数(输出一个下标输出一个次数)比如说样例第一个:

生成的字符串有:

1.abcder   2.bcdera  3.cderab  4.derabc  5.eabcdr  6.rabcde  所以字典序最小的是1  然后循环节次数是 1  然后字典序最大是6 然后循环节次数是 1  所以输出 1 1 6 1

题解:可以看出循环节循环次数,不论字典序最大还是最小,都是一样的~~这样利用 len/(len-nexts[len])就求出最小循环节循环次数了~~(len-nexts[len])它是最小循环节~然后最小最大的下标就用模板跑一下就好了~~上代码:

#include <iostream>
#include <cstring>
using namespace std;
const int MAX = 1e6+10;
char str[MAX];
int nexts[MAX];
int len;
void getnexts(){//nexts[]模板(KMP)
	//memset(nexts,0,sizeof(nexts));//初始,不初始化都对,还没碰上有错的
	int i,j;
	i=j=0;
	nexts[0]=-1;
	j=-1;
	while(i<len){
		if(j==-1||str[i]==str[j]) nexts[++i]=++j;
		else j=nexts[j];
	}
}
int posmin(int len){//最小表示法模板
    int i=0,j=1,k=0;
    while(i<len&&j<len&&k<len){
        int pan=str[(i+k)%len]-str[(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=str[(i+k)%len]-str[(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(){
	while(~scanf("%s",str)){
		len=strlen(str);
		getnexts();
		int ci=len/(len-nexts[len]);//循环次数
		cout << posmin(len) << " " << ci << " " << posmax(len) << " " << ci << endl;
	}
	return 0;
}

 

全部评论

相关推荐

点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务