现在的位置: 首页 > 综合 > 正文

nefu697Similar Word(kmp)

2013年10月02日 ⁄ 综合 ⁄ 共 1634字 ⁄ 字号 评论关闭

Similar Word

Time Limit 1000ms

Memory Limit 65536K

description

  It was a crummy day for Lur. He failed to pass to the CET-6 (College English Test Band-6). Looking back on how it was in last year gone by, he gradually noticed he had fled too many English Lessons. But he determines to memorize words on his bed ,not in the classroom. You know, it is not that easy to pass the test mainly because the large amount of born words. 
     Lur is intelligent on games , never English. He cann't learn the similar words by heart. He 
always choose to select a word to learn from the similar words . For him, two words are similar if and only if one word can equal to the other by multiple cyclic shift(at least 1). For example, "car" and "arc" are similar words, while "car" and "rca" are also similar words . To save more time to play games, 
  Lur want to know wether two words are similar words faster, he asks you to write a program to tell him ,can you help him ? 
							

input

  There are multiple test cases. Each case contains two lines. Each line contains a word, 
W. You can assume that length(W)<=10^5 . Ended by EOF.
							

output

  Output “yes” in a single line if two words are similar,otherwise you should output  “no” in a single line.
							

sample_input

car
arc
car
cra
car
car
							

sample_output

yes
no
no
							

hint


								
							

source

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int mm=1e5+9;
char s[mm],t[mm+mm];
int nex[mm],ls,lt;
void get(char*s,int*nex)
{
  memset(nex,0,sizeof(nex));
  nex[0]=-1;
  int x=-1,y=0;
  while(y<ls)
  {
    if(x==-1||s[x]==s[y])
    {
      nex[++y]=++x;
    }
    else x=nex[x];
  }
}
bool kmp(char*s,char*t)
{ get(s,nex);
  int x=0,y=0;
  while(x<ls&&y<lt)
  {
    if(x==-1||s[x]==t[y])++x,++y;
    else x=nex[x];
  }
  return x==ls&&x^y;
}
int main()
{
  while(~scanf("%s%s",s,t))
  {
    ls=strlen(s);
    lt=strlen(t);
    if(ls^lt){printf("no\n");continue;}
    for(int i=0;i<ls;++i,++lt)
      t[lt]=t[lt-ls];
    t[lt]='\0';
    ///cout<<t<<endl;
    printf("%s\n",kmp(s,t)?"yes":"no");
  }
}

抱歉!评论已关闭.