zoukankan      html  css  js  c++  java
  • HDU5918(KMP)

    Sequence I

    Time Limit: 3000/1500 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
    Total Submission(s): 729    Accepted Submission(s): 277


    Problem Description

    Mr. Frog has two sequences a1,a2,,an and b1,b2,,bm and a number p. He wants to know the number of positions q such that sequence b1,b2,,bm is exactly the sequence aq,aq+p,aq+2p,,aq+(m1)p where q+(m1)pn and q1.
     

    Input

    The first line contains only one integer T100, which indicates the number of test cases.

    Each test case contains three lines.

    The first line contains three space-separated integers 1n106,1m106 and 1p106.

    The second line contains n integers a1,a2,,an(1ai109).

    the third line contains m integers b1,b2,,bm(1bi109).
     

    Output

    For each test case, output one line “Case #x: y”, where x is the case number (starting from 1) and y is the number of valid q’s.
     

    Sample Input

    2
    6 3 1
    1 2 3 1 2 3
    1 2 3
    6 3 2
    1 3 2 2 3 1
    1 2 3
     

    Sample Output

    Case #1: 2
    Case #2: 1
     

    Source

     
     题意:问从a串中每隔p取字,有多少个可与b串匹配
    思路:用kmp可计算连续的a串中有多少个b串,可将每p个数字取出组成连续的新串,共可取出p条新串,对每条新串kmp再求和即可
     1 //2016.10.08
     2 #include <iostream>
     3 #include <cstdio>
     4 #include <cstring>
     5 
     6 using namespace std;
     7 const int N = 1000005;
     8 const int inf = 0x3f3f3f3f;
     9 int a[N], b[N], nex[N],n, m, p;
    10 
    11 void pre_kmp(int b[], int m)//得到next数组
    12 {
    13     int i, j;
    14     j = nex[0] = -1;
    15     i = 0;
    16     while(i < m)
    17     {
    18         while(j != -1 && b[i]!= b[j])j = nex[j];
    19         nex[++i] = ++j;
    20     }
    21 }
    22 
    23 int kmp(int a[], int n, int b[], int m)
    24 {
    25     int ans = 0;
    26     pre_kmp(b, m);
    27     for(int pos = 0; pos < p; pos++)
    28     {
    29         int i = pos, j = 0;
    30         while(i < n)
    31         {
    32             while(j != -1 && a[i] != b[j])j = nex[j];
    33             i += p; j++;
    34             if(j >= m){ans++; j = nex[j];}
    35         }
    36     }
    37     return ans;
    38 }
    39 
    40 int main()
    41 {
    42     int T, kase = 0;
    43     scanf("%d", &T);
    44     while(T--)
    45     {
    46         scanf("%d%d%d", &n, &m, &p);
    47         for(int i = 0; i < n; i++)scanf("%d", &a[i]);
    48         for(int i = 0; i < m; i++)scanf("%d", &b[i]);
    49         printf("Case #%d: %d
    ", ++kase, kmp(a,n,b,m));
    50     }
    51 
    52     return 0;
    53 }
  • 相关阅读:
    Day10
    Python pyspider 安装与开发
    深入理解ES6之《块级作用域绑定》
    深入理解ES6之《扩展对象》
    这些特效对于学习前端我们很有用
    算法之旅 | 选择排序法
    JavaScript读取剪贴板中的表格生成图片
    深入理解ES6之《ES7》
    深入理解ES6之《用模块封装代码》
    php://input,$_POST,$HTTP_RAW_POST_DATA区别
  • 原文地址:https://www.cnblogs.com/Penn000/p/5940268.html
Copyright © 2011-2022 走看看