SDUT-3311-买糖-KMP应用

来源:互联网 发布:远光软件股票 编辑:程序博客网 时间:2024/05/13 08:51

题意: 中文题木啊,

思路:

 找子串在总串中出现的次数;

 次数为1的话就输出串的起始位置

CODE

#include<iostream>#include<string.h>#include<stdlib.h>#include<stdio.h>#include<algorithm>using namespace std;int s[1000100];int t[1000100];int ls, lt;int next[1000100];void getnext(){    int i=0,j=-1;    next[0] = -1;    while(i < lt)    {        if(j == -1 || t[i]==t[j])        {            i++;            j++;            next[i] = j;        }        else            j = next[j];    }}void kmp(){    getnext();    int i=0,j = 0;    int cnt = 0;    int pos;     while(i<ls&&j<lt)    {        if(j==-1||s[i]==t[j])        {            i++;            j++;            if(j==lt)            {                cnt++;                pos=i;                j=next[j];                if(cnt>1)                 break;            }        }        else        j=next[j];    }  if(cnt==1)  {      printf("%d %d\n",pos-lt+1,pos);  }  else    printf("-1\n");}int main(){    while(~scanf("%d",&ls))    {        int i;        for(i = 0; i < ls;i++)            scanf("%d",&s[i]);        scanf("%d",<);        for(i = 0; i < lt;i++)            scanf("%d",&t[i]);        kmp();    }    return 0;}
PS:

 比赛时候数据水,我用暴力加优化水过的,


0 0