A - Number Sequence
Crawling in process... Crawling failed Time Limit:5000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
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 -1kmp问题,输入两组数据,在第一组数据中寻找第二个数据是否和第一个数据重复,在哪个位置上重复。才开始学习KMP一些东西都不懂,在网上搜索了一些答案,最后才看懂的怎么做。也是WA了好几次才AC的。最重要的还是套模板。代码:#include<stdio.h> #include<string.h> int a[1000010]; int next[10010]; void getNext(int *b,int m) { int i, j; for(i = 1; i < m; i ++) { next[0] = next[1] = 0; j = next[i]; while(j && b[i] != b[j]) j = next[j]; next[i + 1] = b[i] == b[j] ? j + 1 : 0; } } int main() { int i, j, n, m, t; int b[100000]; scanf("%d",&t); while(t --) { int flag = 0; int s = -1; scanf("%d%d",&n,&m); for(i = 0; i < n; i ++) { scanf("%d",&a[i]); } for(j = 0; j < m; j ++) { scanf("%d",&b[j]); } getNext(b,m); int j = 0; int i; for(i = 0; i < n; i ++) { while(j && a[i] != b[j]) j = next[j]; if(a[i] == b[j]) j ++; if(j == m) { flag = 1; break; } } if(flag) printf("%d\n",i - m + 2); else printf("%d\n",s); } return 0; }