E. Compress Words(KMP)

[E. Compress Words](https://codeforces.com/contest/1200/problem/E)
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Input

The first line contains an integer n (1≤n≤105), 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 106.

Output

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

Examples

input

5
I want to order pizza

output

Iwantorderpizza

input

5
sample please ease in out

output

sampleaseinout

代码:


#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll int
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const ll INFF = 2000000;
const ll maxn = 2e6 + 10;
ll Next[maxn];
char a[maxn], b[maxn];
ll lena, lenb;
void GetNext() {
	Next[0] = -1;
	Next[1] = 0;
	ll i = 1, k = 0;
	while (i < lenb) {
		if (k < 0 || b[i] == b[k]) Next[++i] = ++k;
		else k = Next[k];
	}
}
ll KMP(ll flag) {
	GetNext();
	ll k = 0, i = flag;
	while (i < lena) {
		if (k < 0 || a[i] == b[k])++i, ++k;
		else k = Next[k];
		if (k == lenb)return k;
	}
	return k;
}
int main() {
	FAST_IO;
	ll n, m, k, i, j, vb;
	string s;
	while (cin>>n) {
		cin >> a;
		vb = 0;
		lena = strlen(a);
		for (i = 1; i < n; i++) {
			//mes(Next, 0);
			cin >> b;
			lenb = strlen(b);
			m = KMP(max(vb - lenb, 0));
			//	cout<<m<<endl;
			for (j = m; j < lenb; j++) {
				a[lena++] = b[j];
			}
			vb = lena;
		}
		cout << a << endl;
	}


}

发布了148 篇原创文章 · 获赞 7 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44417851/article/details/104429454