不知道为啥,最近根本就A不了题,也不知道哪错了......Orz~
学密码学一定得学程序
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
曾经,ZYJ同学非常喜欢密码学。有一天,他发现了一个很长很长的字符串S1。他很好奇那代表着什么,于是神奇的WL给了他另一个字符串S2。但是很不幸的是,WL忘记跟他说是什么意思了。这个时候,ZYJ不得不求助与伟大的ZP。ZP笑了笑说,这个很神奇的,WL的意思是只要你找到她给你的字符串在那个神奇的字符串的位置,你就会有神奇的发现。ZYJ恍然大悟,原来如此,但是悲剧来了,他竟然不知道怎么找。。。。是的,很囧是不是。所以这时候就需要化身为超级玛丽亚的你现身了,告诉他吧。。。。。。
Input
首先输入一个n。表示有n组测试数据。
每组测试数据有两行。
第一行为字符串S1,长度不大于1000000。
第二行为字符串S2,长度不大于10000,并且长度不小于2。
Output
输出S2在S1的位置。如果有多个位置,只输出第一个位置。
如果找不到,就输出“::>_<::“(不输出双引号)。
Sample Input
1
ASDFGDF
DF
Sample Output
3
这是AC的:
#include<stdio.h>
#include<string.h>
char str1[1000010], str2[1000010];
int next[1000010];
void get_next(char s[])
{
int i, j, len = strlen(s);
next[0] = 0;
for(i = 1; i < len; i++)
{
j = next[i-1];
while(j > 0 && s[j] != s[i])
{
j = next[j - 1];
}
if(s[i] == s[j])
{
next[i] = j + 1;
}
else
{
next[i] = 0;
}
}
}
int KMP(char str1[], char str2[])
{
int i = 0, j = 0;
while(i < strlen(str1) && j < strlen(str2))
{
if(str1[i] == str2[j])
{
i++;
j++;
}
else
{
if(j == 0)
{
i++;
}
else
{
j = next[j - 1];
}
}
}
if(j >= strlen(str2)) return i - strlen(str2) + 1;
else return -1;
}
int main()
{
int n,l;
scanf("%d",&n);
while(n--)
{
scanf("%s %s", str1, str2);
get_next(str2);
l = KMP(str1, str2);
if(l == -1)printf("::>_<::\n");
else printf("%d\n",l);
}
return 0;
}
这是我不知道错在哪里的.....
WA:
#include<stdio.h>
#include<string.h>
char s1[1000050], s2[10010];
int next[1000050];
void get_nex(char s[])
{
int i = 0, j=0, len = strlen(s);
next[0] = 0;
for(i = 1; i < len; i++)
{
j = next[i - 1];
while(j > 0 && s[j] != s[i])
{
j = next[j - 1];
}
if(s[i] == s[j])
{
next[i] = j + 1;
}
else
{
next[i] = 0;
}
}
}
void Kmp(char s1[],char s2[])
{
int i = 0, j = 0,len1 = strlen(s1),len2 = strlen(s2);
while(i < len1 &&j < len2)
{
if(s1[i] == s2[j])
{
i++;
j++;
}
else
{
if(j == 0)i++;
else j = next[j - i];
}
}
// printf("%s\n%s\n",s1,s2);
if(j >= len2)printf("%d\n",i - j + 1);
else printf("::>_<::\n");
}
int main()
{
int n;
scanf("%d",&n);
getchar();
while(n--)
{
gets(s1);
gets(s2);
Kmp(s1,s2);
}
return 0;
}