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
    ***********************/


  • 相关阅读:
    学习笔记
    .net $&替换正则查找到的内容
    sql 常用日期函数
    2010学习计划
    优化存储过程
    sql server 标量值函数
    job88数据库操作
    .net 调用有返回值的存储过程
    GridView 18种操作
    SQLite的局限性
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3036432.html
Copyright © 2011-2022 走看看