Hduoj 1711【KMP】

/*Number Sequence
Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11778    Accepted Submission(s): 5375


Problem Description
Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000).
 Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, 
 output the smallest one.

Input
The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers 
N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], ...... , a[N]. The third line 
contains M integers which indicate b[1], b[2], ...... , b[M]. All integers are in the range of [-1000000, 1000000].


Output
For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
 

Sample Input
2
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 2 1
 

Sample Output
6
-1
 

Source
HDU 2007-Spring Programming Contest 
*/
#include<stdio.h>
int next[1000010], a[1000010], b[1000010];
int main()
{
	int i, j, k ,m1, m2 , n;
	scanf("%d" , &n);
	while(n--)
	{
		scanf("%d%d", &m1, &m2);
		for(i = 0; i < m1; i++)
		scanf("%d", &a[i]);
		for(i = 0; i < m2; i++)
		scanf("%d", &b[i]);
		next[0] = -1;
		i = 0;
		j = -1;
		while(i < m2)
		{
			if(j == -1 || b[i] == b[j])
			{
				i++;
				j++;
				if(b[i] == b[j])
				next[i] = next[j];
				else
				next[i] = j;
			}
			else
			j = next[j];
		}
		i = 0;
		j = 0;
		while(i < m1 && j < m2)
		{
			if(j == -1 || a[i] == b[j])
			{
				i++;
				j++;
			}
			else
			j = next[j];
		}
		if(j >= m2)
		printf("%d\n", i-m2+1);
		else
		printf("-1\n"); 
	}
	return 0;
} 


题意:给出2个字符串a,b,求b在a中出现的最小的位置,若没有出现则输出-1.

思路:获得b字符串的next数组,以a字符串为主串进行遍历,找到b串即退出。

你可能感兴趣的:(c)