Compress Words(Kmp模板题

示例代码展示了如何通过C++实现Amugae的句子压缩问题,涉及前缀和后缀匹配算法,用于合并单词并去除重复部分。
摘要由CSDN通过智能技术生成

Compress Words

题面翻译

Amugae 有 n n n 个单词,他想把这个 n n n 个单词变成一个句子,具体来说就是从左到右依次把两个单词合并成一个单词。合并两个单词的时候,要找到最大的 i ( i ≥ 0 ) i(i\ge 0) i(i0),满足第一个单词的长度为 i i i 的后缀和第二个单词长度为 i i i 的前缀相等,然后把第二个单词第 i i i 位以后的部分接到第一个单词后面。输出最后那个单词。

注:题中的字符串存在大小写字母和数字。

题目描述

Amugae has a sentence consisting of $ n $ words. He want to compress this sentence into one word. Amugae doesn’t like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges “sample” and “please” into “samplease”.

Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.

输入格式

The first line contains an integer $ n $ ( $ 1 \le n \le 10^5 $ ), the number of the words in Amugae’s sentence.

The second line contains $ n $ words separated by single space. Each words is non-empty and consists of uppercase and lowercase English letters and digits (‘A’, ‘B’, …, ‘Z’, ‘a’, ‘b’, …, ‘z’, ‘0’, ‘1’, …, ‘9’). The total length of the words does not exceed $ 10^6 $ .

输出格式

In the only line output the compressed word after the merging process ends as described in the problem.

样例 #1

样例输入 #1

5
I want to order pizza

样例输出 #1

Iwantorderpizza

样例 #2

样例输入 #2

5
sample please ease in out

样例输出 #2

sampleaseinout
#include<iostream>
#include<algorithm>
using namespace std;
const int N=10000010;
int ne[N];
string s1;

void slove(){
	string p;cin>>p;
	int t1=min(s1.size()+1,p.size());
	for(int i=1,j=0;i<t1;i++){
		while(j&&p[i]!=p[j])j=ne[j-1];
		if(p[i]==p[j])j++;
		ne[i]=j;
	} 
	
	int j=0;
	int t2=max(0,(int)s1.size()-(int)p.size());
	for(int i=t2;i<s1.size();i++){
		while(j&&p[j]!=s1[i])j=ne[j-1];
		if(s1[i]==p[j])j++;
		if(j==t1&&i!=(int)s1.size()-1)j=ne[j-1];
	}
	
	
	s1+=p.substr(j);
	
}

int main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	int n;cin>>n;
	n--;
	cin>>s1;

	while(n--)slove(); 
	
	cout<<s1;
    return 0;
}
 

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值