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 \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$.


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

Source: codeforces | Difficulty: HARD
Tags: String algorithms

Implementation

Complete search


Solutions:
def prefix_func(s):
	p = [0] * len(s)
	for i in range(1, len(s)):
		j = p[i - 1]
		while j > 0 and s[i] != s[j]:
			j = p[j - 1]
		if s[i] == s[j]:
			j += 1
		p[i] = j
	return p[-1]
n = int(input())
s = input().split()
ans = [*s[0]]
for i in s[1:]:
	c = [*i] + ['$'] + ans[-min(len(i), len(ans)):]
	j = prefix_func(c)
	for _ in range(j):
		ans.pop()
	ans.extend([*i])
print(''.join(ans))


def merge(res, s):
	pi = [0 for i in range(len(s) + 1)]
	pi[0] = -1
	b = -1
	for i in range(1, len(s) + 1):
		while b > -1 and s[i - 1] != s[b]:
			b = pi[b]
		b += 1
		pi[i] = b
	b = 0
	for i in range(max(0, len(res) - len(s)), len(res)):
		while b > -1 and res[i] != s[b]:
			b = pi[b]
		b += 1
	for i in range(b, len(s)):
		res.append(s[i])
n = int(input())
s = input().split()
res = [*s[0]]
for i in range(1, n):
	merge(res, s[i])
print(''.join(res))


def zalgo(s: str):
	l = 0
	r = 0
	n = len(s)
	z = [0] * n
	for i in range(1, n):
		z[i] = 0
		if i <= r:
			z[i] = min(r - i + 1, z[i - l])
		while i + z[i] < n and s[z[i]] == s[i + z[i]]:
			z[i] += 1
		if i + z[i] - 1 > r:
			l = i
			r = i + z[i] - 1
		if i + z[i] == n:
			return z[i]
	return 0
n = int(input())
s = input().split()
txt = []
for i in range(0, n):
	x = len(txt)
	y = len(s[i])
	mn = min(x, y)
	mx = zalgo(s[i] + '#' + ''.join(txt[-mn:]))
	txt.extend(s[i][mx:])
print(''.join(txt))


from sys import stdin, stdout
from sys import setrecursionlimit as SRL
SRL(10 ** 7)
rd = stdin.readline
rrd = lambda : map(int, rd().strip().split())
nxt = [0] * 1000005
n = int(rd())
s = list(rd().split())
ans = []
for i in s[0]:
	ans.append(i)
for i in range(1, n):
	v = s[i]
	t = 0
	for i in range(2, len(v)):
		while t and v[i - 1] != v[t]:
			t = nxt[t]
		if v[i - 1] == v[t]:
			t += 1
		nxt[i] = t
	t = 0
	for i in range(max(0, len(ans) - len(v)), len(ans)):
		while t and ans[i] != v[t]:
			t = nxt[t]
		if ans[i] == v[t]:
			t += 1
	while t < len(v):
		ans.append(v[t])
		t += 1
stdout.write(''.join(ans) + '\n')


from sys import stdin, stdout

def compresswords(n, words):
	a = []
	for c in words[0]:
		a.append(c)
	for i in range(1, len(words)):
		lps = getlps(words[i])
		idx = getsuffixmatchIdx(a, words[i], lps)
		for j in range(idx, len(words[i])):
			a.append(words[i][j])
	return ''.join(a)

def getlps(w):
	lps = []
	lps.append(-1)
	for i in range(1, len(w)):
		c = w[i]
		idx = i - 1
		while idx >= 0 and w[lps[idx] + 1] != c:
			idx = lps[idx]
		if idx >= 0:
			idx = lps[idx] + 1
		lps.append(idx)
	return lps

def getsuffixmatchIdx(a, w, lps):
	widx = 0
	for i in range(max(0, len(a) - len(w)), len(a)):
		c = a[i]
		while widx >= 0 and w[widx] != c:
			widx -= 1
			if widx > 0:
				if lps[widx] >= 0:
					widx = lps[widx] + 1
				else:
					widx = 0
		widx += 1
	return widx

def __starting_point():
	n = int(stdin.readline())
	words = list(stdin.readline().split())
	if n != len(words):
		print('length not match')
	res = compresswords(n, words)
	print(res)
__starting_point()


def compress(words):
	if not words:
		return ''

	def prefix(s):
		table = [0] * len(s)
		j = 0
		for i in range(1, len(s)):
			while 0 < j and s[i] != s[j]:
				j = table[j - 1]
			if s[i] == s[j]:
				j += 1
				table[i] = j
		return table[-1]
	result = [*words[0]]
	for word in words[1:]:
		n = min(len(result), len(word))
		for _ in range(prefix([*word] + ['$'] + result[-n:])):
			result.pop()
		result.extend([*word])
	return ''.join(result)

def solve():
	_ = int(input())
	words = input().split()
	print(compress(words))
solve()


import sys
from sys import stdin

def zalgo(S):
	A = [0] * len(S)
	A[0] = len(S)
	i = 1
	j = 0
	while i < len(S):
		while i + j < len(S) and S[j] == S[i + j]:
			j += 1
		A[i] = j
		if j == 0:
			i += 1
			continue
		k = 1
		while i + k < len(S) and k + A[k] < j:
			A[i + k] = A[k]
			k += 1
		i += k
		j -= k
	return A
N = int(input())
slis = list(input().split())
S = list(slis[0])
for i in range(1, N):
	T = list(slis[i])
	T.append('#')
	if len(S) <= len(T):
		for i in S:
			T.append(i)
	else:
		for i in range(len(S) - len(T), len(S)):
			T.append(S[i])
	A = zalgo(T)
	cut = 0
	for i in range(len(T)):
		if T[len(T) - 1 - i] == '#':
			break
		elif i + 1 == A[len(T) - 1 - i]:
			cut = i + 1
	for i in range(cut, len(T)):
		if T[i] == '#':
			break
		else:
			S.append(T[i])
print(''.join(S))


from sys import stdin, stdout
n = int(input())
s = list(map(str, stdin.readline().split()))
ans = []
mod = 10 ** 9 + 7
for i in range(len(s)):
	(l, l2) = (len(s[i]), len(ans))
	(hash, hash2, ma) = (0, 0, -1)
	for i2 in range(min(l, len(ans))):
		hash *= 75
		hash += ord(s[i][i2]) - 48
		hash2 += (ord(ans[l2 - i2 - 1]) - 48) * pow(75, i2, mod)
		hash %= mod
		hash2 %= mod
		if hash == hash2:
			ma = i2
	for i2 in range(ma + 1, l):
		ans.append(s[i][i2])
for i in range(len(ans)):
	stdout.write(ans[i])


def partial(s):
	(g, pi) = (0, [0] * len(s))
	for i in range(1, len(s)):
		while g and s[g] != s[i]:
			g = pi[g - 1]
		pi[i] = g = g + (s[g] == s[i])
	return pi[-1]
n = int(input())
s = input().split()
ans = [*s[0]]
for i in s[1:]:
	c = [*i] + ['$'] + ans[-min(len(i), len(ans)):]
	j = partial(c)
	for _ in range(j):
		ans.pop()
	ans.extend([*i])
print(''.join(ans))


import sys
input = sys.stdin.readline
n = int(input())
L = list(input().split())
ANS = [L[0]]
LEN2 = len(L[0])
mod0 = 1 << 16
mod1 = (1 << 16) - 3
mod2 = (1 << 16) - 2
p = 75
TABLE0 = [0]
TABLE1 = [0]
TABLE2 = [0]

def hash_ij0(i, j):
	return (TABLE0[j] - TABLE0[i] * pow(p, j - i, mod0)) % mod0

def hash_ij1(i, j):
	return (TABLE1[j] - TABLE1[i] * pow(p, j - i, mod1)) % mod1

def hash_ij2(i, j):
	return (TABLE2[j] - TABLE2[i] * pow(p, j - i, mod2)) % mod2
for s in L[0]:
	TABLE0.append((p * TABLE0[-1] % mod0 + ord(s) - 48) % mod0)
	TABLE1.append((p * TABLE1[-1] % mod1 + ord(s) - 48) % mod1)
	TABLE2.append((p * TABLE2[-1] % mod2 + ord(s) - 48) % mod2)
for i in range(1, n):
	NEXT = L[i]
	LEN = len(NEXT)
	ha0 = 0
	ha1 = 0
	ha2 = 0
	plus = -1
	for j in range(min(LEN, LEN2)):
		ha0 = (p * ha0 % mod0 + ord(NEXT[j]) - 48) % mod0
		ha1 = (p * ha1 % mod1 + ord(NEXT[j]) - 48) % mod1
		ha2 = (p * ha2 % mod2 + ord(NEXT[j]) - 48) % mod2
		if ha0 == hash_ij0(LEN2 - j - 1, LEN2) and ha1 == hash_ij1(LEN2 - j - 1, LEN2) and (ha2 == hash_ij2(LEN2 - j - 1, LEN2)):
			plus = j
	if plus == -1:
		ANS.append(NEXT)
		LEN2 += len(NEXT)
		for s in NEXT:
			TABLE0.append((p * TABLE0[-1] % mod0 + ord(s) - 48) % mod0)
			TABLE1.append((p * TABLE1[-1] % mod1 + ord(s) - 48) % mod1)
			TABLE2.append((p * TABLE2[-1] % mod2 + ord(s) - 48) % mod2)
	else:
		NEXT = NEXT[plus + 1:]
		ANS.append(NEXT)
		LEN2 += len(NEXT)
		for s in NEXT:
			TABLE0.append((p * TABLE0[-1] % mod0 + ord(s) - 48) % mod0)
			TABLE1.append((p * TABLE1[-1] % mod1 + ord(s) - 48) % mod1)
			TABLE2.append((p * TABLE2[-1] % mod2 + ord(s) - 48) % mod2)
sys.stdout.write(''.join(ANS) + '\n')


n = int(input())
words = input().split()[:n]
p_base = 1543
p_mod = 1300199
current = [c for c in words[0]]
for word in words[1:]:
	cur_hash = 0
	word_hash = 0
	cur_base = 1
	i_matches = []
	same_i = 0
	biggest_match = None
	while same_i < len(current) and same_i < len(word):
		cur_hash *= p_base
		cur_hash %= p_mod
		cur_hash += ord(current[len(current) - 1 - same_i])
		cur_hash %= p_mod
		word_hash += ord(word[same_i]) * cur_base
		word_hash %= p_mod
		cur_base *= p_base
		cur_base %= p_mod
		if cur_hash == word_hash:
			i_matches.append(same_i)
		same_i += 1
	for match in reversed(i_matches):
		if ''.join(word[:match + 1]) == ''.join(current[-1 - match:]):
			biggest_match = match
			break
	if biggest_match is None:
		current.extend(list(word))
	else:
		current.extend(list(word[biggest_match + 1:]))
print(*current, sep='')


def zalgo(S):
	L = len(S)
	Z = [0] * L
	l = 0
	for i in range(1, L):
		if i + Z[i - l] < l + Z[l]:
			Z[i] = Z[i - l]
		else:
			cnt = max(0, l + Z[l] - i)
			while i + cnt < L and S[i + cnt] == S[cnt]:
				cnt += 1
			Z[i] = cnt
			l = i
	Z[0] = L
	return Z
N = int(input())
S = [list(map(ord, s)) for s in input().strip().split()]
Ans = [0] * 10 ** 6
for s in S:
	n = len(s)
	Z = zalgo(s + [-1] + Ans[-n:])[n + 1:] + [0]
	for i in range(n + 1):
		if n - i == Z[i]:
			Ans += s[n - i:]
			break
Ans = Ans[10 ** 6:]
print(''.join(map(chr, Ans)))