URAL 1684 Jack's Last Word

来源:互联网 发布:焊接机械手编程 编辑:程序博客网 时间:2024/06/06 02:39

1684. Jack's Last Word

Time Limit: 0.5 second
Memory Limit: 64 MB
Not long ago Jack read on a fence a word that was new and amusing for him. Jack liked it so much that he wanted to invent another amusing word, but no matter how hard he tried he couldn't do it. All the words he could invent consisted of prefixes of the initial word and therefore didn't please Jack. He continued to invent words that were longer and longer, but none of them was pleasing.
And now the time has come for Jack to have his last word.

Input

The first line contains the amusing word that was written on the fence. The second line contains Jack's last word. The words are nonempty, consist of lower-case English letters, and are no longer than 75000 symbols.

Output

If Jack didn't invent a new amusing word, output “No” in the first line. In this case, show Jack how to decompose his last word into several parts each of which is either the initial word or its nonempty prefix. Output these parts in the second line separating them with a space. If there is no such decomposition, output “Yes” in the only output line.

Samples

inputoutput
abracadabraabrabracada
Noabr abracad a
abracadabraarbadacarba
Yes


分析:可用KMP做

方法1:

#include<cstdio>#include<cstring>const int N=75002;char a[N],b[N],c[N<<1];int p[N],s[N],la,lb;void KMP(char *S,char *T){la=strlen(S+1);lb=strlen(T+1);int i,j;for(j=p[1]=0,i=2;i<=la;i++){while(j&&S[j+1]!=S[i])j=p[j];if(S[j+1]==S[i])++j;p[i]=j;}for(j=0,i=1;i<=lb;i++){while(j&&S[j+1]!=T[i])j=p[j];if(S[j+1]==T[i])++j;s[i]=j;}}int main(){int tol,i,j;while(~scanf("%s%s",a+1,b+1)){KMP(a,b);c[tol=(N<<1)-1]='\0';for(i=lb;i&&s[i];i-=s[i],c[--tol]=' ')for(j=i;j>i-s[i];j--)c[--tol]=b[j];if(i)puts("Yes");else puts("No"),puts(c+tol+1);}return 0;}


方法2:

先将两个字符串连接起来,求出新串的next数组(程序中的p数组),再从后向前扫最大前缀(存下来)

#include<cstdio>#include<iostream>#include<string>#include<cstring>using namespace std;const int N=75002;char a[N<<1],b[N];int p[N<<1],la,lb;string s[N];int main(){int tol,i,j,t;while(~scanf("%s%s",a+1,b+1)){la=strlen(a+1);b[0]='#';t=la+1;strcat(a+1,b);la=la+strlen(b);for(j=p[1]=0,i=2;i<=la;i++){while(j&&a[j+1]!=a[i])j=p[j];if(a[j+1]==a[i])++j;p[i]=j;}tol=-1;for(i=la;i>t&&p[i];i-=p[i]){for(s[++tol]="",j=i-p[i]+1;j<=i;j++)s[tol]+=a[j];}if(i>t)puts("Yes");else {puts("No");for(;tol;tol--)cout<<s[tol]<<" ";cout<<s[0]<<endl;}}return 0;}


 

原创粉丝点击