Sicily1282(KMP算法)

注意母串的长度要开大一点。

#include <cstdio>
#include <iostream>
using namespace std;
int main()
{
  int n,m;
  while (scanf("%d",&m)!=EOF)
  {
  	int i;
  	int A[1000000],B[100000];
  	for (i=0;i<=m-1;i++)
  		scanf("%d",&B[i]);
  	scanf("%d",&n);
  	for (i=0;i<=n-1;i++)
  		scanf("%d",&A[i]);

  	int next[100000];
  	int j=0,k=-1;
  	next[0]=-1;
  	while (j!=m)
  	{
  		if (k==-1 || B[j]==B[k])
  		{
  			j++;
  			k++;
  			if (B[j]!=B[k])
  				next[j]=k;
  			else
  				next[j]=next[k];
  		}
  		else
  			k=next[k];
  	}

    j=0;
    int bcount=0;
    while (1)
    {
    	if (j==n)
    	{
    		printf("no solution\n");
    		break;
    	}
    	if (A[j]==B[bcount])
    	{
    		j++;
    		bcount++;
    		if (bcount==m)
    		{
    			printf("%d\n",j-m);
    			break;
    		}
    	}
    	else
    	{
    		if (next[bcount]==-1)
    		{
    			j++;
    			bcount=0;
    		}
    		else if (next[bcount]==0)
    		{
    			bcount=0;
    		}
    		else
    		{
    			bcount=next[bcount];
    		}
    	}
    }
  }
	return 0;
}



你可能感兴趣的:(Sicily1282(KMP算法))