• hdu kmp 2594


    题目求P的前缀与S2的后缀相同的最长字符串,那么把P和S2连接起来,然后求next[n+m] 。

    注意两种数据:

    abcabcabc

    abcabc

    6

    abc

    abcabc

    3

    即需要讨论 next[n+m]>len(P) next=next[next[n + m]]  和   next[n+m]>len(S2) next=next[next[n + m]] 。

    代码如下:

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<string>
     4 #include<string.h>
     5 #define N 50005
     6 using namespace std;
     7 char P[N*2];
     8 char S2[N];
     9 int m;
    10 int next[N*2];
    11  void Prefix_Func()
    12  {
    13      int i,k;
    14      k=0;
    15      next[1]=0;
    16      for(i=2;i<=m;i++)
    17      {
    18         while(k>0 && P[k+1]!= P[i])
    19             k=next[k];
    20         if(P[k+1] == P[i])
    21             k++;
    22         next[i]=k;
    23      }
    24  }
    25 int main()
    26 {
    27 
    28     int n1,n2,k;
    29     while(scanf("%s%s",P+1,S2+1)!=EOF)
    30     {
    31         n1=strlen(P+1);
    32         n2=strlen(S2+1);
    33         strcat(P+1,S2+1);
    34         m=n1+n2;
    35         Prefix_Func();
    36         k=next[m];
    37         while(k>n1 || k>n2)
    38         {
    39             k=next[k];
    40         }
    41         if(k)
    42         {
    43             for(int i=1;i<=k;i++)
    44                 cout<<P[i];
    45             cout<<" "<<k<<endl;
    46         }
    47         else
    48             cout<<"0"<<endl;
    49     }
    50     return 0 ;
    51 }
  • 相关阅读:
    Tinyhttpd 代码学习
    Windows noinstall zip 安装MySQL。
    Java 优先队列
    Java Comparable 和 Comparator
    Centos6.6下安装Python3.5
    对象的实现
    对象接口
    适配器模式
    java基础学习(一)
    【MongoDB】如何注册windows服务
  • 原文地址:https://www.cnblogs.com/zn505119020/p/3571757.html
Copyright © 2020-2023  润新知