Sicily1282——Computer Game

来源:互联网 发布:淘宝助理怎么定时上架 编辑:程序博客网 时间:2024/05/22 12:43

1282. Computer Game

限制条件

时间限制: 1 秒, 内存限制: 32 兆

题目描述

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 most60000 integer numbers between 0 and 255. The gate protection contains integer numbers between0 and 255. Your program must find the first match if there is one, or report the absence of a match.

输入格式

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.

输出格式

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 solutionif there is no match.

样例输入

30 1 272 3 4 0 1 2 521 464 1 4 1 4 431 2 373 2 1 3 2 255 7

样例输出

31no solution
能解这题还真是不容易,硬生生的看kmp,完全起初完全懵逼,好在根据模版还是看懂了,贴在这里方便自己复习!

#include <iostream>#include <cstdio>#include <iomanip>#include <map>#include <vector>#include <cstdlib>#include <queue>#include <string>#include <cstring>#include <sstream>#include <algorithm>#include <set>#include <cmath>#include <list>using namespace std;int a[1000001],num[1000001],next[1000001] = {0};int n,m;void makeNext(int a[],int next[]){next[0] = 0;for(int i = 1,j = 0; i<n; i++){while(j > 0 && a[i] != a[j])j = next[j-1];if(a[i] == a[j])j++;next[i] = j;}}void kmp(int a[],int num[],int next[]){bool bo = 0;makeNext(a,next);for(int i = 0,j = 0; i<m; i++){while(j > 0 && a[j] != num[i])j = next[j-1];if(a[j] == num[i])j++;if(j == n){cout << i-n+1 << endl;bo = 1;break;}}if(bo == 0) cout << "no solution" << endl;}int main(){while(scanf("%d",&n) != EOF){for(int i = 0; i<n; i++)scanf("%d",&a[i]);scanf("%d",&m);for(int i = 0; i<m; i++)scanf("%d",&num[i]);kmp(a,num,next);}return 0;}

顺便把kmp算法的详解贴在下面,这个贴帮了我很大的忙!点击打开链接
0 0