目录
CF1200E Compress Words
题目描述
Amugae has a sentence consisting of nn 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 nn ( 1 \le n \le 10^51≤n≤105 ), the number of the words in Amugae's sentence.
The second line contains nn 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^6106 .
输出格式
In the only line output the compressed word after the merging process ends as described in the problem.
题意翻译
Amugae有n个单词,他想把这个n个单词变成一个句子,具体来说就是从左到右依次把两个单词合并成一个单词.合并两个单词的时候,要找到最大的i(i\ge 0)i(i≥0),满足第一个单词的长度为ii的后缀和第二个单词长度为ii的前缀相等,然后把第二个单词第ii位以后的部分接到第一个单词后面.输出最后那个单词
输入输出样例
输入 #1复制
5 I want to order pizza
输出 #1复制
Iwantorderpizza
输入 #2复制
5 sample please ease in out
输出 #2复制
sampleaseinout
题意
给你n个字符串,相同的地方可以拼接在一起,问你最后能拼成什么东西
思路
1、找第一个串的后缀和第二个串的前缀 ,找到他们最长的公共部分拼在一起
2、所以就可以用kmp的next数组
3、但传统的KMP都是只求一个字符串的前后缀,本题却求的是分别两个字符串的前缀和后缀的最长相等长度
4、将已合并的字符串接到新的待合并字符串的后面,把两个字符串合并成了一个,而且也正好按顺序待合并前缀在前面已合并字符串后缀在后面
5、为了防止时间复杂度过长(会超时),截取已合并字符串和待合并字符串两者中较短的长度
6、并且在待合并字符串和已合并字符串之间还要加一个永远不会输入的字符进行阻隔
代码实现
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define N 1000010
char s[N],a[N];
int next[N],len;
int main()
{
int n;
cin>>n;
cin>>s+1;
len=strlen(s+1);
for(int i=2;i<=n;i++)
{
cin>>a+1;
int lens=len,lena=strlen(a+1),cnt=lena;
int minlen=min(lens,lena);
a[++cnt]='#';
for(int j=1;j<=minlen;j++)
a[++cnt]=s[lens-minlen+j];
next[0]=next[1]=0;
int j=0;
for(int k=2;k<=cnt;k++)
{
while(j>0&&a[k]!=a[j+1]) j=next[j];
if(a[k]==a[j+1]) j++;
next[k]=j;
}
for(int j=next[cnt]+1;j<=lena;j++)
s[++len]=a[j];
}
cout<<s+1;
return 0;
}