zoukankan      html  css  js  c++  java
  • hdu1711(ac自动机思想)

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <string>
    #include <algorithm>
    using namespace std;
    const int maxn = 1000010;
    const int maxm = 10010;
    //Accepted 1711 484MS 4260K 1569 B C++ Achiberx 
    int a[maxn], b[maxn];
    int n, m;
    int next[maxm];
    
    void getNext(){
        next[0] = 0;
        next[1] = 0;
        if(m<3) return;
        int j = 0;
        for(int i = 1; i < m; i++) {
            j = next[i];
            if(b[i]==b[j]) {
                next[i+1] = j+1;
                continue;
            }
            else {
                while(j>0) {
                    j = next[j];
                    if(b[i]==b[j]) {
                        next[i+1] = j+1;
                        break;
                    }
                }
            }
        }
    }
    
    int match() {
        int j = 0;
        for(int i =0; i < n; i++) {
            while(j && a[i]!=b[j])  {
                j = next[j];
            }
            if(a[i]==b[j]) j++;
            if(j==m) {
                return i-m+2;
            }
        }
        return 0;
    }
    
    int main()
    {
        int T;
        scanf("%d", &T);
        for(int v = 0; v < T; v++) {
            scanf("%d%d", &n, &m);
            for(int i = 0; i < n; i++) {
                scanf("%d", &a[i]);
            }
            for(int j = 0; j < m; j++) {
                scanf("%d", &b[j]);
            }
            getNext();
            int res = match();
            if(res) {
                printf("%d\n", res);
            }
            else{
                printf("-1\n");
            }
        }
        return 0;
    }
    /***********************
    5
    13 5
    1 2 1 2 3 1 2 3 1 3 2 1 2
    1 2 3 1 3
    13 5
    1 2 1 2 3 1 2 3 1 3 2 1 2
    1 2 3 2 1
    ***********************/


  • 相关阅读:
    NCBI SRA数据库使用详解
    自相关分析
    RandomAccessFile java
    手动安装R包
    ubuntu 设置环境变量
    Shell:Day09-2.笔记
    Shell:Day09.笔记
    Shell:Day08.笔记
    Shell:Day07.笔记
    Shell:Day06.笔记
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3036432.html
Copyright © 2011-2022 走看看