zoukankan      html  css  js  c++  java
  • HDU6135 拓展KMP模板

    emmm...模板,虽然每太搞懂

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <string.h>
     4 #pragma warning ( disable : 4996 )
     5 using namespace std;
     6 
     7 inline int Max(int a,int b) { return a>b?a:b; }
     8 inline int Min(int a,int b) { return a>b?b:a; }
     9 const int inf = 0x3f3f3f3f;
    10 const int maxn = 1e6+5;
    11 
    12 char str[maxn], nstr[maxn];
    13 int nex[maxn], extend[maxn];
    14 int len, nlen;
    15 long long ans, mod = 1000000007;
    16 
    17 void init()
    18 {
    19     ans = 0;
    20     memset( str, 0, sizeof(str) );
    21     memset( nstr, 0, sizeof(nstr) );
    22 
    23     scanf( "%s", str );  len = strlen(str);   reverse(str, str+len);
    24     scanf( "%s", nstr ); nlen = strlen(nstr); reverse(nstr, nstr+nlen);
    25 }
    26 
    27 void getNext()
    28 {
    29     nex[0] = nlen;
    30     int po, far;        //po表示目前匹配的起始点,far表示最远点
    31 
    32     for (int i = 1, j = -1; i < nlen; i++, j-- )
    33     {
    34         if ( j < 0 || i + nex[i-po] >= far )
    35         {
    36             if(j<0) { far=i;j++; }
    37             while(far<nlen&&nstr[far]==nstr[j])
    38             { far++; j++; }
    39 
    40             nex[i] = j;
    41             po = i;
    42         }
    43         else
    44             nex[i] = nex[i-po];
    45     }
    46 }
    47 
    48 void getExtend()
    49 {
    50     int po, far;
    51 
    52     for ( int i = 0, j = -1; i < len; i++, j-- )
    53     {
    54         if ( j < 0 || i + nex[i-po] >= far )
    55         {
    56             if(j<0) { far=i;j++; }
    57             while(far<len && j<nlen && str[far]==nstr[j] )
    58             { far++; j++; }
    59 
    60             extend[i] = j;
    61             po = i;
    62         }
    63         else
    64             extend[i] = nex[i-po];
    65     }
    66 }
    67 
    68 int main()
    69 {
    70     int all; cin >> all;
    71     while (all--)
    72     {
    73         init();
    74         getNext();
    75         getExtend();
    76 
    77         long long tmp;
    78         for ( int i = 0; i < len; i++ )
    79         {
    80             tmp = (long long)extend[i];
    81             ans = ( ans + tmp*(tmp+1)/2 ) % mod;
    82         }
    83         printf( "%lld
    ", ans );
    84     }
    85     return 0;
    86 }
    View Code
  • 相关阅读:
    二叉树中和为某一值的路径
    二叉搜索树的后序遍历序列(important!)
    从上往下打印二叉树
    最小的k个数(important!)
    扑克牌顺子
    栈的压入、弹出序列(important!)
    和为s的连续正数序列(important!)
    数组中只出现一次的数字
    fgets()函数以及fputs()函数
    C语言中的指针
  • 原文地址:https://www.cnblogs.com/chaoswr/p/8634605.html
Copyright © 2011-2022 走看看