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;
	}


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章