Sicily 1282 Computer Game
2015-02-17 19:44
225 查看
Constraints
Time Limit: 1 secs, Memory Limit: 32 MBDescription
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 ashe 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 firstoccurrence of the code in the gate protection, or the message no solution
if there is no match.
Sample Input
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 MemberSolution
给出长度la的序列a,长度不超过60000,给出长度lb的序列b,长度不定,求出a序列在b序列的第一次出现的位置,若没有输出no solution。
字符串匹配,暴力会超时,用KMP就ok啦。
#include <cstdio>
#include <cstring>
int a[1000005], b[100005], la, lb, next[100005];
void kmp()
{
int i, j = 0;
for (i = 1; i <= la; ++i)
{
while (j && a[i] != b[j+1]) j = next[j];
if (a[i] == b[j+1]) ++j;
if (j == lb)
{
printf("%d\n", i - lb);
return;
}
}
printf("no solution\n");
return;
}
int main()
{
while (scanf("%d", &lb) != EOF)
{
int i, t = 0;
for (i = 1; i <= lb; ++i) scanf("%d", &b[i]);
scanf("%d", &la);
for (i = 1; i <= la; ++i) scanf("%d", &a[i]);
//初始化next序列
next[1] = t;
for (i = 2; i <= lb; ++i)
{
while (t && b[t+1] != b[i]) t = next[t];
if (b[t+1] == b[i]) ++t;
next[i] = t;
}
kmp();
}
return 0;
}
相关文章推荐
- sicily 1282. Computer Game
- Sicily1282——Computer Game
- sicily 1282 Computer Game
- 1282. Computer Game
- sicily 1282 ——由此引出的KMP算法
- Sicily1282(KMP算法)
- Sicily.1280 Permutation
- Sicily1798. Alice and Bob[策略问题]
- 【Codevs1282】 约瑟夫问题 树状数组 (11/1000)
- Sicily 1004. 拓扑序[Special judge]
- 【HDU】1282 回文数猜想
- Sicily 1018 A Card Trick —— 教你玩一个纸牌魔术
- Sicily 1198 Substring
- Sicily 1029 Rabbit(高精度运算+公式递推)
- Sicily 1696 Flows in Grid(最大流)
- Sicily 1010. Zipper
- sicily 1795
- Sicily 1443 Printer Queue
- sicily 1150 简单魔板 & 1151 魔板 bfs
- sicily 1135 飞越原野 bfs