CF1200E Compress Words

LIsa
只要理解kmp,就会知道应该找前缀和后缀了

把当前输入的串和已知的答案串拼起来,然后中间加上一个小小的不存在字符,跑kmp

#include<cstdio>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<algorithm>
using namespace std;
string s,ans;
string tem;
int ne[1000001];
template<class T>inline void read(T &x)
{
    x=0;register char c=getchar();register bool f=0;
    while(!isdigit(c))f^=c=='-',c=getchar();
    while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar();
    if(f)x=-x;
}
template<class T>inline void print(T x)
{
    if(x<0)putchar('-'),x=-x;
    if(x>9)print(x/10);
    putchar('0'+x%10);
}
int km(string s){
	//cout<<s<<endl;
	int l=s.length();
	int f=0;
	s=' '+s;
	ne[0]=ne[1]=0;
	for(int i=2;i<=l;++i){
		while(f&&s[f+1]!=s[i]) f=ne[f];
		if(s[f+1]==s[i]) f++;
		ne[i]=f;
	}
	return ne[l];
}
int n;
int main(){
	//ios::sync_with_stdio(false);
	read(n);
	cin>>ans;
	n--;
	while(n--){
		cin>>s;
		int l=min(ans.length(),s.length());
	//	cout<<ans.length()<<endl;
		tem=s.substr(0,l)+'#'+ans.substr(ans.length()-l,l);
		int ll=km(tem);
	//	cout<<ll<<endl;
		//int ll=s.length();
		for(int j=ll;j<s.length();++j){
			ans+=s[j];
		}
	}
	cout<<ans;
    return 0;
}

posted @ 2021-10-12 15:53  Simex  阅读(23)  评论(0编辑  收藏  举报