HDOJ3374String Problem(最小表示法+kmp)

Xredman posted @ Apr 06, 2010 09:35:50 AM in Algorithm with tags KMP HDU 最小表示法 , 1651 阅读

 

/*
tju 3275(Windy's S), zju2006(Glass Beads),
*/
//2302935 2010-04-06 19:52:55 Accepted 3374 468MS 11096K 1800 B C++ Xredman 

#include <iostream>
#include <string>
using namespace std;

const int N = 1000003;
int next[N];

/*
用最小表示法求字符串S的最小字典序
*/
int MaxRepresstation(string S)
{
	int i = 0, j = 1, k = 0;
	int len = S.length();
	S += S;
	while(i < len && j < len)
	{
		k = 0;
		while(k < len && S[i + k] == S[j + k])
			k++;
		if(k >= len)
			break;
		if(S[i + k] < S[j + k])
			i = max(i + k + 1, j + 1);
		else
			j = max(i + 1, j + k + 1);
	}
	return min(i ,j);
}

int MinRepresstation(string S)
{
	int i = 0, j = 1, k = 0;
	int len = S.length();
	S += S;
	while(i < len && j < len)
	{
		k = 0;
		while(k < len && S[i + k] == S[j + k])
			k++;
		if(k >= len)
			break;
		if(S[i + k] > S[j + k])
			i = max(i + k + 1, j + 1);
		else
			j = max(i + 1, j + k + 1);
	}
	return min(i ,j);
}

void getNext(string T)
{
	int j, k;
	int len = T.length();
	j = 0; k = -1; next[0] = -1;
	while(j < len)
		if(k == -1 || T[j] == T[k])
			next[++j] = ++k;
		else
			k = next[k];

}

int KMP_Count(string S, string T)
{
	int ans = 0;
	int slen = S.length(), tlen = T.length();
	int i, j = 0;
	if(slen == 1 && tlen == 1)
	{
		if(S[0] == T[0])
			return 1;
		else
			return 0;
	}
	getNext(T);
	for(i = 0; i < slen; i++)
	{
		while(j > 0 && S[i] != T[j])
			j = next[j];
		if(S[i] == T[j])
			j++;
		if(j == tlen)
		{
			ans++;
			j = next[j];
		}
	}
	return ans;
}
int main()
{
	string S, T;
	int repc;
	int Minbeg, Maxbeg, k, len;
	while(cin>>S)
	{
		Minbeg = MinRepresstation(S);
		Maxbeg = MaxRepresstation(S);
		T = S;
		S += S;
		S[S.length() -1] = '*';
		repc = KMP_Count(S, T);
		cout<<Minbeg + 1<<" "<<repc<<" "<<Maxbeg + 1<<" "<<repc<<endl;
	}
	return 0;
}






KVS 8th Class Sylla 说:
Aug 29, 2023 08:21:00 PM

Students are Studying Must Check Latest KVS 8th Syllabus 2024 before Preparing for Their Examinations. Students can Download Kendriya Vidyalaya Syllabus Various Subject in the form of PDF through This page or Through its KVS 8th Class Syllabus 2024 Official Portal. Kendriya Vidyalaya 9th Class are Strictly Based on Syllabus as Prescribed by Central Board of Secondary Education (CBSE).It is Advisable for Students to Carefully Study the Syllabus and Exam Pattern to crack the Exam. While Students are Required to Thorough the Exam Syllabus, Focusing on some important Questions can also Result in Successful Annual Exam Preparation.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter