Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 49957 Accepted Submission(s): 20117
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
Source
HDU 2007-Spring Programming Contest
题目大意:
给定主串与模式串,求主串的子串中与模式串匹配的第一个子串的最左边字母的位置(即是主串的第几个字母),如果模式串不能与主串的子串匹配,输出-1。
这题可以用hash,暴力枚举所有长度与模式串相同的子串的hash值,与模式串的hash值进行对比,hash的方法可以看我的另一篇博客《兔子与兔子》
当然也可以使用kmp算法,我看的大部分博客都是下标从零开始,当我把它改成从一开始时也出了不少的bug,kmp算法我在这就不在过多赘述,最好自己看代码或视频理解,太多文字描述有时反而会更不易理解,视频我推荐mooc上浙江大学的数据结构,在综合习题选讲中,陈越老师的kmp算法讲的很清晰易懂。下面附上ac的代码。
代码:
hash:
#include <cstdio>
#include <iostream>
using namespace std;
typedef unsigned long long ull;
const int N = 1e6 + 5;
ull f[N], p[N];
int n, m;
int find(ull x){
for (int i = 1; i + m - 1 <= n; i ++){
if (f[i + m - 1] - f[i - 1] * p[m] == x)return i;
}
return -1;
}
int main()
{
int t;
cin >> t;
while(t --){
cin >> n >> m;
p[0] = 1;
int x;
for (int i = 1; i <= n; i ++){
scanf("%d", &x);
f[i] = f[i - 1] * 131 + x + 1;
p[i] = p[i - 1] * 131;
}
ull pattern = 0;
for (int i = 1; i <= m; i ++){
scanf("%d", &x);
pattern = pattern * 131 + x + 1;
}
int ans = find(pattern);
cout << ans << endl;
}
return 0;
}
kmp:
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1e6 + 10;
int nex[10005];
int n, m;
int a[N], b[10005];
void cal_next(){
nex[1] = 0;
int j = 1;
for (int i = 2; i <= m; i ++){
j = nex[i - 1];
while(j > 0 &&( j == n || b[i] != b[j + 1]))j = nex[j];
if (b[i] == b[j + 1])j ++;
nex[i] = j;
}
}
int kmp(){
int i = 1, j = 1;
while(i <= n && j <= m){
if ( a[i] == b[j])i ++, j ++;
else if (j > 1)j = nex[j - 1] + 1;
else i ++;
}
if (j == m + 1)return i - m;
else return -1;
}
int main()
{
int t;
cin >> t;
while (t --){
cin >> n >> m;
for (int i = 1; i <= n; i ++)scanf("%d", &a[i]);
for (int j = 1; j <= m; j ++)scanf("%d", &b[j]);
cal_next();
cout << kmp() << endl;
}
return 0;
}
kmp貌似快一些