Hdu1711:number Sequence

Source: Internet
Author: User

Problem Descriptiongiven-sequences of numbers:a[1], a[2], ..., a[n], and b[1], b[2], ..., b[m] (1 <= M &L t;= 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 is more than one K exist, output the smallest one. inputthe first line of input is a number T which indicat E The number of cases. Each case contains three lines. The first line is the 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 is in the range of [ -1000000, 1000000]. outputfor, should, and output one line which only Contain K described above. If No such K exists, output-1 instead. sample Input213 51 2 1 2 3 1 2 3 1 3 2 1 21 2 3 1 313 5 1 2 1 2 3 1 2 3 1 3 2 1 2 3 2 1 sample output6-1 &nbspThe  //low method should be 1.1 points, but the use of KMP algorithm will be very cool. (KMP can also be used in the array!!) (⊙o⊙)//The problem is very interesting, let me know the algorithm is more important is the idea, do not have to limit their own thinking   
#include <iostream>#include<cstdio>using namespacestd;intdata1[1000003],data2[1000003];intnex[1000003],n,m;voidGetNext () {intI=0, j=-1; nex[0]=-1;  while(i<m) {if(j==-1|| data2[i]==Data2[j]) {i++;j++; if(data2[i]==Data2[j]) nex[i]=Nex[j]; ElseNex[i]=J; }        ElseJ=Nex[j]; }}intKMP () {intI=0, j=0;    GetNext ();  while(i<N) {if(j==-1|| data1[i]==Data2[j]) {i++;j++; }        Else{J=NEX[J];//J=nex[i] Here again remember the wrong ....         }        if(j==m)returni-m+1; }    return-1;}intMain () {intl; CIN>>l;  while(l--) {cin>>n>>m;  for(intI=0; i<n;i++) scanf ("%d",&Data1[i]);  for(intI=0; i<m;i++) scanf ("%d",&Data2[i]);        GetNext (); intans=KMP (); cout<<ans<<Endl; }    return 0;}

Hdu1711:number Sequence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.