Number Sequence(C++版)
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
不需要什么思路,使用KMP算法找到,出现的位置就行
#include <iostream> #include <vector> using namespace std; const vector<int> getNext(const vector<int>& temp) { int i = 1, k = 0; vector<int> next(temp.size() + 1); next[0] = 0; for (; i < temp.size(); ++i) { while (k > 0 && temp[k] != temp[i]) k = next[k - 1]; if (temp[k] == temp[i]) ++k; next[i] = k; } return next; } int KMP(vector<int> & val1, vector<int> & val2) { int k = 0; vector<int> next(val2.size() + 1); next = getNext(val2); for (int i = 0; i < val1.size(); ++i) { while (k > 0 && val1[i] != val2[k]) k = next[k - 1]; if (val1[i] == val2[k]) ++k; if (k == val2.size()) return i - k + 2; } return -1; } int main() { int n, i, j; cin >> n; for (int t = 0; t < n; ++t) { cin >> i >> j; vector<int> vec1(i), vec2(j); for (int m = 0; m < i; ++m) { cin >> vec1[m]; } for (int r = 0; r < j; ++r) { cin >> vec2[r]; } cout << KMP(vec1, vec2) << endl; } system("PAUSE"); return 0; }

浙公网安备 33010602011771号