HDOJ1711Number Sequence(kmp)

Xredman posted @ Apr 07, 2010 12:18:12 AM in Algorithm with tags HDU KMP , 1284 阅读

//2305327 2010-04-07 10:46:48 Accepted 1711 2015MS 4308K 846 B C++ Xredman 

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

const int N = 1000002;
int next[N];
int S[N], T[N];
int slen, tlen;
void getNext()
{
	int j, k;
	j = 0; k = -1; next[0] = -1;
	while(j < tlen)
		if(k == -1 || T[j] == T[k])
			next[++j] = ++k;
		else
			k = next[k];

}

int KMP_Index()
{
	int i = 0, j = 0;
	getNext();

	while(i < slen && j < tlen)
	{
		if(j == -1 || S[i] == T[j])
		{
			i++; j++;
		}
		else
			j = next[j];
	}
	if(j == tlen)
		return i - tlen;
	else
		return -1;
}
int main()
{
	
	int TT;
	int i, cc;
	cin>>TT;
	while(TT--)
	{
		cin>>slen>>tlen;
		for(i = 0; i < slen; i++)
			cin>>S[i];
		for(i = 0; i < tlen; i++)
			cin>>T[i];
		cc = KMP_Index();
		if(cc == -1)
			cout<<cc<<endl;
		else
			cout<<cc + 1<<endl;
	}
	return 0;
}





GSEB Model Paper Cla 说:
Sep 04, 2022 12:11:36 AM

Gujarat Board Model Paper 2023 Class 1 Pdf Download with Answers for Gujarati Medium, English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. GSEB Model Paper Class 1 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.


登录 *


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