While exploring the old caves, researchers found a book, or more precisely, a stash of mixed pages from a book. Luckily, all of the original pages are present and each page contains its number. Therefore, the researchers can reconstruct the book.

After taking a deeper look into the contents of these pages, linguists think that this may be some kind of dictionary. What's interesting is that this ancient civilization used an alphabet which is a subset of the English alphabet, however, the order of these letters in the alphabet is not like the one in the English language.

Given the contents of pages that researchers have found, your task is to reconstruct the alphabet of this ancient civilization using the provided pages from the dictionary.


-----Input-----

First-line contains two integers: $n$ and $k$ ($1 \le n, k \le 10^3$) — the number of pages that scientists have found and the number of words present at each page. Following $n$ groups contain a line with a single integer $p_i$ ($0 \le n \lt 10^3$) — the number of $i$-th page, as well as $k$ lines, each line containing one of the strings (up to $100$ characters) written on the page numbered $p_i$.


-----Output-----

Output a string representing the reconstructed alphabet of this ancient civilization. If the book found is not a dictionary, output "IMPOSSIBLE" without quotes. In case there are multiple solutions, output any of them.


-----Example-----
Input
3 3
2
b
b
bbac
0
a
aca
acba
1
ab
c
ccb

Output
acb

Difficulty: interview

Starter code:

Solutions:

from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import defaultdict
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
 
M = mod = 10**9 + 7 
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
 
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
 
 


graph = defaultdict(set)

n, k = li()
l = []
allwords = set()
for i in range(n):
    p = val()
    l1 = []
    for j in range(k):l1.append(st())

    allwords |= set(l1[-1])
    l.append([p, l1[:]])


l.sort(key = lambda x:x[0])
l = [i[1] for i in l]
if n == k == 1:
    print(''.join(set(l[0][0])))
    return


ingraph = defaultdict(int)

def match(a, b):
    for j in range(min(len(a), len(b))):
        if a[j] == b[j]:continue
        elif b[j] in graph[a[j]]:return
        else:
            graph[a[j]].add(b[j])
            ingraph[b[j]] += 1
            return
    if len(a) > len(b):
        print('IMPOSSIBLE')
        return

finl = []
for i in l:finl.extend(i)
l = finl

# for i in l:print(i)

for i in range(1, len(l)):
    match(l[i - 1], l[i])



# print(graph)
# print(ingraph)

if min([ingraph[j] for j in graph]) != 0:
    print('IMPOSSIBLE')
    return

ans = ''


d = deque()

for j in graph:
    if ingraph[j] == 0:
        d.append(j)

while d:
    node = d.popleft()
    ans += node

    for j in graph[node]:
        ingraph[j] -= 1
        if not ingraph[j]:d.append(j)


if len(ans) != len(allwords):
    print('IMPOSSIBLE')
    return
print(ans)


# from collections import deque
import io
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline # 神奇快读，无法运行调试
import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)


def input(): return sys.stdin.readline().rstrip("\r\n")


n, m = map(int, input().split())
# d = {}
inc = {
    # chr(97+i):0 for i in range(26)

}
l = [None for i in range(n*m)]

for i in range(n):
    t = int(input())
    # tmp = []
    for j in range(m):
        # tmp.append(input())
        ipt = input()
        l[t*m+j] = ipt
        if len(inc)==26:continue
        for q in ipt:
            inc.setdefault(q, 0)
    # d[t] = tmp
# l = []
# for i in range(n):
#     for j in d[i]:
#         l.append(j)

d = {}


# f = l[0][0]

def ae(u, v):
    t = d.setdefault(u, set())
    if v not in t:
        t.add(v)
        inc[v] = inc.get(v, 0) + 1


for p, i in enumerate(l[1:]):
    for j in range(min(len(l[p]), len(i))):
        if l[p][j] != i[j]:
            # if len(l[p])-1 != j:
                # ae(l[p][j],i[j])
            ae(i[j], l[p][j])
            break
        if len(i)-1==j and len(l[p])-1 > j:
            print("IMPOSSIBLE")
            return


ans = []
dq = []
# dq = deque()
ptr = 0


ninc = {}

for k, v in inc.items():
    if v == 0:
        dq.append(k)
    else:
        ninc[k] = v


# if ctr>1:
    # print("IMPOSSIBLE")
    # return

inc = ninc


while ptr != len(dq):
    fst = dq[ptr]
    ans.append(fst)

    for i in d.get(fst, []):
        inc[i] -= 1
        if inc[i] == 0:
            dq.append(i)
            inc.pop(i)

    # if ctr>1:
        # print("IMPOSSIBLE")
        # return
    ptr += 1

if len(inc):
    print("IMPOSSIBLE")
    return

print(*reversed(ans), sep='')


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline;M = mod = 10**9 + 7 
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
graph = defaultdict(set);n, k = li();l = [];allwords = set()
for i in range(n):
    p = val();l1 = []
    for j in range(k):l1.append(st())
    allwords |= set(l1[-1]);l.append([p, l1[:]])
l.sort(key = lambda x:x[0]);l = [i[1] for i in l]
if n == k == 1:print(''.join(set(l[0][0])));return
ingraph = defaultdict(int)
def match(a, b):
    for j in range(min(len(a), len(b))):
        if a[j] == b[j]:continue
        elif b[j] in graph[a[j]]:return
        else:graph[a[j]].add(b[j]);ingraph[b[j]] += 1;return
    if len(a) > len(b):print('IMPOSSIBLE');return
finl = []
for i in l:finl.extend(i)
l = finl
for i in range(1, len(l)):match(l[i - 1], l[i])
if min([ingraph[j] for j in graph]) != 0:print('IMPOSSIBLE');return
ans = '';d = deque()
for j in graph:
    if ingraph[j] == 0:d.append(j)
while d:
    node = d.popleft();ans += node
    for j in graph[node]:
        ingraph[j] -= 1
        if not ingraph[j]:d.append(j)
if len(ans) != len(allwords):print('IMPOSSIBLE');return
print(ans)

from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
 
M = mod = 10**9 + 7 
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
 
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
 
 
 
 
graph = defaultdict(set)
 
n, k = li()
l = []
allwords = set()
for i in range(n):
    p = val()
    l1 = []
    for j in range(k):l1.append(st())
 
    allwords |= set(l1[-1])
    l.append([p, l1[:]])
 
 
l.sort(key = lambda x:x[0])
l = [i[1] for i in l]
if n == k == 1:
    print(''.join(set(l[0][0])))
    return
 
 
ingraph = defaultdict(int)
 
def match(a, b):
    for j in range(min(len(a), len(b))):
        if a[j] == b[j]:continue
        elif b[j] in graph[a[j]]:return
        else:
            graph[a[j]].add(b[j])
            ingraph[b[j]] += 1
            return
    if len(a) > len(b):
        print('IMPOSSIBLE')
        return
 
finl = []
for i in l:finl.extend(i)
l = finl
 
# for i in l:print(i)
 
for i in range(1, len(l)):
    match(l[i - 1], l[i])
 
 
 
# print(graph)
# print(ingraph)
 
if min([ingraph[j] for j in graph]) != 0:
    print('IMPOSSIBLE')
    return
 
ans = ''
 
 
d = deque()
 
for j in graph:
    if ingraph[j] == 0:
        d.append(j)
 
while d:
    node = d.popleft()
    ans += node
 
    for j in graph[node]:
        ingraph[j] -= 1
        if not ingraph[j]:d.append(j)
 
 
if len(ans) != len(allwords):
    print('IMPOSSIBLE')
    return
print(ans)

import os
import io
from collections import deque, defaultdict

input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())

# def li():return [int(i) for i in input().rstrip().split()]
# def st():return str(input())
# def val():return int(input())

#Input Reading

n,k = li()

pages = []
abc = set()

for _ in range(n):
    p = val()
    page = []
    for i in range(k):
        word = st()
        page.append(word)
    abc |= set(page[-1])
    pages.append((p,page))

pages.sort(key = lambda x: x[0])
words = []
for _,page in pages:
    words.extend(page)

if n == k == 1:
    print(''.join(abc))
    return

def match(w1,w2):
    for i in range(min(len(w1), len(w2))):
        if w1[i] == w2[i]:
            continue
        else:
            return (w1[i],w2[i])

    if len(w1) > len(w2):
        print("IMPOSSIBLE")
        return    

#Reading the graph and its indegrees
g = defaultdict(set)
indeg = defaultdict(int)

for i in range(len(words) - 1):
    out = match(words[i], words[i+1])
    if out is not None:
        c1,c2 = out
        if c2 not in g[c1]:
            g[c1].add(c2)
            indeg[c2] += 1


#Topsort things
ts = []
zero = deque()
for u in g:
    if indeg[u] == 0:
        zero.append(u)

while len(ts) != len(abc):
    if len(zero) == 0:
        print("IMPOSSIBLE")
        return
    
    u = zero.popleft()
    ts.append(u)
    for v in g[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            zero.append(v)

print("".join(ts))



import os
import io
from collections import deque, defaultdict

input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())

# def li():return [int(i) for i in input().rstrip().split()]
# def st():return str(input())
# def val():return int(input())

#Input Reading

n,k = li()

words = [""] * n * k
abc = set()

for i in range(n):
    p = val()
    page = []
    for j in range(k):
        word = st()
        words[p*k+j] = word
    abc |= set(word)

def match(w1,w2):
    for i in range(min(len(w1), len(w2))):
        if w1[i] == w2[i]:
            continue
        else:
            return (w1[i],w2[i])

    if len(w1) > len(w2):
        print("IMPOSSIBLE")
        return    

#Reading the graph and its indegrees
g = {c: set() for c in abc}
indeg = {c: 0 for c in abc}

for i in range(len(words) - 1):
    out = match(words[i], words[i+1])
    if out is not None:
        c1,c2 = out
        if c2 not in g[c1]:
            g[c1].add(c2)
            indeg[c2] += 1


#Topsort things
ts = []
zero = deque()
for u in g:
    if indeg[u] == 0:
        zero.append(u)

while len(ts) != len(abc):
    if len(zero) == 0:
        print("IMPOSSIBLE")
        return
    
    u = zero.popleft()
    ts.append(u)
    for v in g[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            zero.append(v)

print("".join(ts))

import os
import io
from collections import deque, defaultdict

input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline

def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())

# def li():return [int(i) for i in input().rstrip().split()]
# def st():return str(input())
# def val():return int(input())

#Input Reading

n,k = li()

words = [""] * n * k
indeg = {}

for i in range(n):
    p = val()
    page = []
    for j in range(k):
        word = st()
        words[p*k+j] = word
    for c in word:
        indeg[c] = 0

def match(w1,w2):
    for i in range(min(len(w1), len(w2))):
        if w1[i] == w2[i]:
            continue
        else:
            return (w1[i],w2[i])

    if len(w1) > len(w2):
        print("IMPOSSIBLE")
        return    

#Reading the graph and its indegrees
g = defaultdict(set)

for i in range(len(words) - 1):
    out = match(words[i], words[i+1])
    if out is not None:
        c1,c2 = out
        if c2 not in g[c1]:
            g[c1].add(c2)
            indeg[c2] += 1


#Topsort things
ts = []
zero = deque()
for u in indeg:
    if indeg[u] == 0:
        zero.append(u)

while len(ts) != len(indeg):
    if len(zero) == 0:
        print("IMPOSSIBLE")
        return
    
    u = zero.popleft()
    ts.append(u)
    for v in g[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            zero.append(v)

print("".join(ts))

import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
 
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
 
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
 
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
 
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
 
 
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
 
 
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline()
 
# ------------------------------


def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
    print(' '.join(map(str,l)))
# sys.setrecursionlimit(100000)
# from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow,gcd,log
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc 
# from functools import lru_cache
n,k = RL()
dic = [[] for _ in range(1000)]
for _ in range(n):
    page = N()
    for _ in range(k):
        dic[page].append(input().strip())
dic = [word for page in dic for word in page]
nw = len(dic)
# print(dic)
ingress = dc(int)
edges = dc(list)
chars = set()
chars|=set(dic[0])
F = True
for i in range(1,nw):
    a,b = dic[i-1],dic[i]
    if len(chars)<26: chars|=set(b)
    flag = False
    for i,j in zip(a,b):
        if i!=j:
            ingress[j]+=1
            edges[i].append(j)
            flag = True
            break
    if not flag and len(b)<len(a):
        F = False
        break
if not F:
    print('IMPOSSIBLE')
else:
# print(edges)
    res = ''
    now = []
    for c in chars:
        ingress[c] = max(0,ingress[c])
        if ingress[c]==0:
            now.append(c)
    # print(ingress)
    while now:
        a = now.pop()
        res+=a 
        for b in edges[a]:
            ingress[b]-=1
            if ingress[b]==0:
                now.append(b)

    if len(res)==len(chars):
        print(res)
    else:
        print('IMPOSSIBLE')