Description
Brian is an enthusiast of computer games, especially those that simulate virtual reality. Now he is in front of the Star Gate. In order to open the gate he must break the protection as quickly as he can. Breaking the protection means to match a given code (a sequence of numbers) against the gate protection (a very long sequence of numbers). The starting position of the first occurrence of the code within the sequence opens the gate. Can you help him?
The code is a sequence of at most 60000 integer numbers between 0 and 255. The gate protection contains integer numbers between 0 and 255. Your program must find the first match if there is one, or report the absence of a match.
Input
The text input file contains several data sets. Each data set has the following format:
l the length of the code
l the sequence of numbers representing the code
l the number of integers in the gate protection
l the sequence of numbers representing the gate protection
code_dimension
integer1 integer2 … integercode_dimension
protection_dimension
integer1 integer2 … integerprotection_dimension
White spaces may occur freely in the input.
Output
The results must be printed on the standard output. For each given data set, print the result on a separate line. The result is a number that represents the position (starting from zero) of the first occurrence of the code in the gate protection, or the message no solution if there is no match.
Sample Input
Copy sample input to clipboard
3
0 1 2
7
2 3 4 0 1 2 5
2
1 4
6
4 1 4 1 4 4
3
1 2 3
7
3 2 1 3 2 255 7
Sample Output
3
1
no solution
Problem Source: ZSUACM Team Member
思考
本来想用暴力搜索,但是题目的测试数据比较大,那样的方法会超时
后来听说用KMP算法, 但是实在晦涩
在查kmp算法的时候,了解了很多字符串匹配算法
最后我选择了易懂高效的Sunday算法
我的代码
// Problem#: 19152
// Submission#: 4857247
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include<iostream>
#include<vector>
#define max 256
using namespace std;
int main() {
int codeNum = 0, proNum = 0;
int lastAppaer[max]; // 用于记录每个数据在子串中最后出现的位置
vector<int> code, pro;
int d;
while (cin >> codeNum) {
code.clear();
pro.clear();
for (int i = 0; i < max; i++) {
lastAppaer[i] = -1;
}
for (int i = 0; i < codeNum; i++) {
cin >> d;
lastAppaer[d] = i;
code.push_back(d);
}
cin >> proNum;
for (int i = 0; i < proNum; i++) {
cin >> d;
pro.push_back(d);
}
int i = 0, find = 0;
while(i <= proNum - codeNum) {
int j = 0;
while (j < codeNum) {
if (pro[i] == code[j]) {
i++;
j++;
} else {
int n = i + codeNum - j;
i = n;
while (lastAppaer[pro[i]] == -1 && i <= proNum - codeNum) {
i++;
}
i = n - lastAppaer[pro[n]];
break;
}
}
if (j == codeNum) {
cout << i - codeNum << endl;
find = 1;
break;
}
}
if (find == 0) cout << "no solution" <<endl;
}
return 0;
}