Skip to content

Commit

Permalink
add second solution for NHAY
Browse files Browse the repository at this point in the history
  • Loading branch information
t3nsor committed Oct 9, 2014
1 parent e86ab8f commit aedc1ea
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions nhay-2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// 2011-12-11
// nhay-2.cpp uses KMP. For Rabin-Karp, see nhay-1.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int in()
{
int res=0;
int c;
do
{
c=getchar_unlocked();
if (c==EOF) return 0;
}
while (c<=32);
do
{
res=10*res+(c-'0');
c=getchar_unlocked();
}
while (c>32);
return res;
}
int main()
{
int n,k,i;
char c;
static char needle[1000000];
static int pi[1000000];
while (n=in())
{
gets(needle);
pi[1]=0;
k=0;
for (i=2; i<=n; i++)
{
while (k>0&&needle[k]!=needle[i-1])
k=pi[k];
if (needle[k]==needle[i-1])
k++;
pi[i]=k;
}
k=0;
i=0;
while ((c=getchar_unlocked())!='\n')
{
i++;
while (k>0&&needle[k]!=c)
k=pi[k];
if (needle[k]==c)
k++;
if (k==n)
{
printf("%d\n",i-n);
k=pi[k];
}
}
putchar('\n');
}
return 0;
}

0 comments on commit aedc1ea

Please sign in to comment.