HDU-1711 Number Sequence(裸KMP板子)

题目链接

题意:

模式串匹配,匹配成功输出第一个字符的位置,匹配失败输出-1

思路:
KMP 板子

不会戳这里

AC:

#include<cstring>
#include<stdio.h>
#include<math.h>
#include<algorithm>
const int maxn = 1e6 + 10;
const int maxm = 1e4 + 10;
int s[maxn], p[maxm];
int next[maxm];
int n, m;
void GetNextval() {
	int j = 0;
	int k = -1;
	next[0] = -1;
	int pLen = m;
	while(j < pLen - 1) {
		if(k == -1 || p[k] == p[j]){
			++j;
			++k;
			if(p[k] != p[j])
				next[j] = k;
			else
				next[j] = next[k];
		} else {
			k = next[k];
		} 
	} 
}
int KmpSearch() {
	int i = 0, j = 0;
	int sLen = n;
	int pLen = m;
	
	while(i < sLen && j < pLen) {
		if(s[i] == p[j] || j == -1) {
			++i;
			++j;
		} else {
			j = next[j];
		}
	}
	if(j == pLen)
		return i - j + 1;
	else 
		return -1;
}

int main(){
	int T;
	scanf("%d", &T);
	while(T--) {
		scanf("%d%d", &n, &m);
		for(int i = 0; i < n; ++i) {
			scanf("%d", &s[i]);
		}
		//cout << s << endl;
		for(int j = 0; j < m; ++j) {
			scanf("%d", &p[j]);
		}
		//cout << p << endl;
		GetNextval();
		int Ans = 0;
		Ans = KmpSearch();
		printf("%d\n", Ans);
	}
	return 0;
}
发布了199 篇原创文章 · 获赞 156 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Harington/article/details/99682844