hdu 1711

   感觉到了算法的伟大,虽然是用了最基本的kmp算法,不过代码写的比较乱,因为数组是从0开始,如果数组时从1开始的话估计就会清晰了。

#include<iostream>
#include<stdio.h>
using namespace std;
int s1[1000005],s2[10005];
int p[10005];
int main()
{
    int total_case,iii;
    scanf("%d",&total_case);
    for(iii=0;iii<total_case;iii++)
    {
          int n1,n2,i;
          scanf("%d%d",&n1,&n2);
          for(i=0;i<n1;i++)
             scanf("%d",&s1[i]);
          for(i=0;i<n2;i++)
             scanf("%d",&s2[i]);
          int j=-1;
          p[0]=-1;
          for(i=1;i<n2;i++)        //初始化数组p的值
          {
              while(j>-1&&s2[j+1]!=s2[i])
                   j=p[j];                //若不相等的话就等于其下最短首尾相等字符创的长度(字符串的长度从零开始)
              if(s2[j+1]==s2[i])
                   j++;
              p[i]=j;
          }
         
          j=-1;
          for(i=0;i<n1;i++)
          {
              while(j>-1&&s2[j+1]!=s1[i])
                  j=p[j];
              if(s2[j+1]==s1[i])
                  j++;
              if(j==n2-1)
              {
                  printf("%d\n",i-j+1);
                  break;
              }
          }
          if(i==n1)
              printf("-1\n");
      }
}

 

posted @ 2011-10-13 09:33  DChipNau  阅读(101)  评论(0编辑  收藏  举报