URAL 1684 Jack's Last Word

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

input output
abracadabra
abrabracada
No
abr abracad a
abracadabra
arbadacarba
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;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值