zoukankan      html  css  js  c++  java
  • hdu 1711 Number Sequence

    Number Sequence

    Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 7731    Accepted Submission(s): 3520


    Problem Description
    Given two sequences of numbers : a[1], a[2], ...... , a[N], and b[1], b[2], ...... , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], ...... , a[K + M - 1] = b[M]. If there are more than one K exist, output the smallest one.
     
    Input
    The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], ...... , a[N]. The third line contains M integers which indicate b[1], b[2], ...... , b[M]. All integers are in the range of [-1000000, 1000000].
     
    Output
    For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.
     
    Sample Input
    2 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
     
    Sample Output
    6 -1
    想不明白,利用G++提交超时,而利用c++确accpet
    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <cstring>
    #include <cstdlib>
    
    using namespace std;
    
    const int MAX = 10000+2;
    int next[MAX] = {0};
    
    void getNext(const vector<int> &b){
        memset(next,0,sizeof(next));
        int j = 0;
        next[1] = 0;
        for(int i = 2; i < b.size(); i ++){
            while( j > 0 && b[j+1] != b[i] ) j = next[j];
            if( b[j+1] == b[i]) j++;
            next[i] = j;
        }
    }
    
    int kmp(const vector<int> &a, const vector<int> &b){
        int j = 0;
        for(int i = 1; i < a.size(); i ++ ){
            while( j > 0 && a[i] != b[j+1]) j=next[j];
            if( a[i] == b[j+1]) j++;
            if( j == b.size()-1 ) return i-b.size()+2;
        }
        return -1;
    }
    
    int main(){
        int T;
        cin  >> T;
        while(T--){
            int n,m;
            cin >> n >> m ;
            vector <int> a(n+1),b(m+1);
            for(int i = 1; i <= n ; i ++ ) cin >> a[i];
            for(int i = 1; i <= m ; i ++ ) cin >> b[i];
            if( n < m) cout<<-1<<endl;
            else{
                getNext(b);
                cout<<kmp(a,b)<<endl;
            }
        }
        return 0;
    }
    

      

     
  • 相关阅读:
    项目测试与部署
    使用技术及部分代码截选
    校园电子设备报修回收系统需求分析
    java lambda expression
    Domain logic approaches
    Spring AOP Capabilities ang goals
    CDI Features
    JAVA DESIGN PATTERN
    LDAP & Implementation
    spring ref &history&design philosophy
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3082491.html
Copyright © 2011-2022 走看看