zoukankan      html  css  js  c++  java
  • HDOJ_1711_KMP 求匹配位置

    HDOJ_1711_KMP 入门
     /* HDOJ_1711_KMP 求匹配位置
     *  
     * I really like this KMP in door
     *  
     * Author : a_clay  2014/05/06 
     */  
    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <vector>
    #include <algorithm>
    #include <cmath>
    #define Bug cout << "here
    ";
    using namespace std;
    
    const int N = 1000005;
    const int M = 10005;
    
    int s[N];
    int t[M];
    int next[M];
    
    void get_next(int len) {
        int i, j;
        i = 0;
        j = -1;
        next[0] = -1;
        while (i < len - 1) {
            if (j == -1 || t[i] == t[j]) {
                i++; j++; next[i] = j;
            }
            else {
                j = next[j]; // 核心中的核心,KMP中的KMP。
            }
        }
    }
    int kmp(int sl, int tl) {
        int i, j;
        i = 0;
        j = 0;
        while (i < sl && j < tl) {
            if (j == -1 || s[i] == t[j]) { //j == -1  是第一个就没有匹配上,类似于传统方法,i要向后移动,因为-1的巧妙设置,所以j依然很好的移动,i 还是从第一位 开始从 j==0比较
                i++; j++;
            }
            else { j = next[j];}
        }
        if (j == tl) {
            return i-j+1;
        }
        else return -1;
    }
    
     // abcabcababcabcabdef
     // abcabcabd 
    
    int main() {
        int T, n, m, ans;
        cin >> T;
        while (T--) {
            cin >> n >> m;
            int i;
            for (i = 0; i < n; i++) {
                scanf("%d", s+i);
            }
            for (i = 0; i < m; i++) {
                scanf("%d", t+i);
            }
            get_next(m);
            ans = kmp(n, m);
            cout << ans << endl;
        }
        return 0;
    }
    

  • 相关阅读:
    用Keytool和OpenSSL生成和签发数字证书
    Maven 的插件和生命周期的绑定
    MySQL 存储过程基本函数
    MySQL 存储过程游标
    MySQL 存储过程控制语句
    MySQL 存储过程
    Shell 编程基础之 && 与 ||
    Shell 编程基础之 [ 与 [[ 的异同
    Linux 任务控制
    《深入理解Java虚拟机》笔记3
  • 原文地址:https://www.cnblogs.com/robbychan/p/3786777.html
Copyright © 2011-2022 走看看