HDU1711 Number Sequence
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
题解
题意
在字符串A内寻找字符串B的位置。如果找不到,返回-1;
思路
hash模板题目,通过遍历初始位置,当出现哈希值相等时,证明找到字符串,否则输出-1;
代码
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
#define REP(i,n) for(int i=0;i<(n);i++)
const int MAXN = 1e6+10;
ull xp[MAXN],sav_hash[MAXN];
int a[MAXN],b[MAXN];
void init(){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
xp[0]=1;
for(int i=1;i<MAXN;i++)
xp[i]=xp[i-1]*175;
}
ull get_hash(int l,int r){
return sav_hash[r]-sav_hash[l-1]*xp[r-l+1];
}
int main(){
init();
int T;
scanf("%d",&T);
while(T--){
int n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
for(int j=1;j<=m;j++){
scanf("%d",&b[j]);
}
ull ned,cur;
int ans = -1;
sav_hash[0]=m;
for(int i=1;i<=m;i++){
sav_hash[i] = sav_hash[i-1]*175+b[i];
}
ned = get_hash(1,m);
sav_hash[0]=n;
for(int i=1;i<=n;i++){
sav_hash[i] = sav_hash[i-1]*175+a[i];
}
for(int i=1;i<=n;i++){
cur = get_hash(i,i+m-1);
if(cur==ned){
ans = i;
break;
}
}
printf("%d\n",ans);
}
return 0;
}