题目
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.
题意
输入n个词,希望将它们从左往右压缩成一个词(首先合并前两个单词,然后将结果与第三个单词合并,依此类推)
两个单词合并时要求删除第二个单词中与第一个单词后缀重合的最长前缀
思路
典型的字符串前后缀匹配问题,我们可以直接代入kmp模板求解.注意每次匹配结束后要更新被匹配的字符串
代码如下
#include <iostream>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;
char b[1000005], a[1000005]; int n, m, x,nex[1000005];
int main()
{
cin >> x;
cin >> b; cout << b; m = strlen(b);
while (x--) {
cin >> a;
n = strlen(a);
nex[1] = 0;
int N ;
//字符串a的自匹配
for (int i = 2, j = 0; i <= n; i++) {
while (j > 0 && a[i-1] != a[j]) j = nex[j];
if (a[i-1] == a[j]) j++;
nex[i] = j;
}
//匹配字符串a与b
for (int i = max(1,m-n+1), j = 0; i <= m; i++) {
while (j > 0 && (j == n || b[i-1] != a[j])) j = nex[j];
if (b[i-1] == a[j]) j++;
//最后所得的N值即为前后缀最大匹配长度
N = j;
}
//输出非字符串a的"重复"部分,并将字符串a,b进行去"重复"的合并
for (int i = N; i < n; i++) cout << a[i], b[m + i - N] = a[i];
//更新新字符串长度
m += n - N;
}
return 0;
}