码迷,mamicode.com
首页 > 其他好文 > 详细

G - Number Sequence( 查找子字符串 )

时间:2017-08-01 20:53:23      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:ase   code   ons   com   kmp   each   void   一个   find   

Given two sequences of numbers : a11, a22, ...... , aNN, and b11, b22, ...... , bMM (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make aKK = b11, aK+1K+1 = b22, ...... , aK+M?1K+M?1 = bMM. If there are more than one K exist, output the smallest one. 

InputThe 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 a11, a22, ...... , aNN. The third line contains M integers which indicate b11, b22, ...... , bMM. All integers are in the range of ?1000000,1000000?1000000,1000000. 
OutputFor 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

题目意思:在一个长的字符串中找到一串短的字符串
解法:用KMP,有个大牛讲的很好:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
 1 #include <iostream>
 2 #include <string.h>
 3 
 4 using namespace std;
 5 
 6 const int MAX = 1000000 + 50;
 7 int a[MAX],b[MAX];
 8 int visit[MAX];
 9 int an,bm;
10 
11 void DP_2()
12 {
13     int ai = 0;
14     int bi = 0;
15     while(ai < an )
16     {
17        // cout<<ai<<" "<<bi<<endl;
18         //cout<<a[ai]<<" "<<b[bi]<<endl;
19         if(bi==-1||a[ai] == b[bi])
20         {
21             ai++;
22             bi++;
23         }
24         else
25         {
26             bi = visit[bi];
27         }
28         if(bi==bm)
29         {
30             cout<<ai - bm+1<<endl;
31             return;
32         }
33 
34     }
35     cout<<-1<<endl;
36 
37 
38 
39 }
40 
41 void DP()
42 {
43     int j = 0;
44     int k = -1;
45     visit[0] = -1;
46     while(j < bm)
47     {
48         if(k==-1||b[j]==b[k]  )
49             {
50                 k++;
51                 j++;
52                 visit[j] = k;
53             }
54         else
55             k = visit[k];
56     }
57 
58  }
59 
60 int main()
61 {
62     int N;
63     cin>>N;
64     while(N--)
65     {
66         memset(visit,0,sizeof(visit));
67         memset(a,0,sizeof(a));
68         memset(b,0,sizeof(b));
69 
70         cin>>an>>bm;
71         for(int i = 0;i <an;i++)
72            cin>>a[i];
73         for(int i = 0;i <bm;i++)
74             cin>>b[i];
75 
76         DP();
77 
78         DP_2();
79 
80     }
81 
82     return 0;
83 }

 

G - Number Sequence( 查找子字符串 )

标签:ase   code   ons   com   kmp   each   void   一个   find   

原文地址:http://www.cnblogs.com/a2985812043/p/7270229.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!