hdu3374 String Problem(KMP+最小表示法)

String Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1648    Accepted Submission(s): 742


Problem Description
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
 

Author
WhereIsHeroFrom
抄袭此处,哈哈
/*
可以拿来当模板用的,变量名都没改。。。。。。不过加了注释了,防止以后看不懂
Time:2014-12-2 14:10
*/
#include
#include
#include
using namespace std;
const int MAX=1000000+10;
char str[MAX];
int next[MAX];
/*
比找最小表示法,相当于找着一个字符串a,再找一个一直循环比较
如果他是最小的,就会一直增加比较,直到长度为len则返回
如果出现i和j相等的情况,j加1最后返回小的那一个就行 
*/ 
void Get_next(int len){
	int i=0,j=-1;
	next[0]=-1;
	while(str[i]){
		if(j==-1||str[i]==str[j]){
			i++;j++;
			next[i]=j;
		}else
		j=next[j];
	}
}
int min_max_express(char *s,int len,bool flag){//最小表示法和最大表示法写到一块儿了 
	int i=0,j=1,k=0; 
	while(i0)j+=k+1; //+(k+1)相当于直接把相等的跳过 
				else i+=k+1;
			}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",str)!=EOF){
		int len=strlen(str);
		int min_express=min_max_express(str,len,true);
		int max_express=min_max_express(str,len,false);
		Get_next(len);
		int ans=len%(len-next[len])?1:len/(len-next[len]); 
		printf("%d %d %d %d\n",min_express+1,ans,max_express+1,ans);//因为从0开始的,最大最小项+1 
	} 
return 0;
} 


你可能感兴趣的:(模板,字符串匹配)