Polycarp and String Transformation (Codeforces 1560E)
Tags: Implement, strings

Polycarp has a string $$$s$$$. Polycarp performs the following actions until the string $$$s$$$ is empty ($$$t$$$ is initially an empty string):  he adds to the right to the string $$$t$$$ the string $$$s$$$, i.e. he does $$$t = t + s$$$, where $$$t + s$$$ is a concatenation of the strings $$$t$$$ and $$$s$$$;  he selects an arbitrary letter of $$$s$$$ and removes from $$$s$$$ all its occurrences (the selected letter must occur in the string $$$s$$$ at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string $$$s$$$ will be empty and the string $$$t$$$ will be equal to some value (that is undefined and depends on the order of removing).E.g. consider $$$s$$$="abacaba" so the actions may be performed as follows:  $$$t$$$="abacaba", the letter 'b' is selected, then $$$s$$$="aacaa";  $$$t$$$="abacabaaacaa", the letter 'a' is selected, then $$$s$$$="c";  $$$t$$$="abacabaaacaac", the letter 'c' is selected, then $$$s$$$="" (the empty string). You need to restore the initial value of the string $$$s$$$ using only the final value of $$$t$$$ and find the order of removing letters from $$$s$$$.

Input: The first line contains one integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Then $$$T$$$ test cases follow.Each test case contains one string $$$t$$$ consisting of lowercase letters of the Latin alphabet. The length of $$$t$$$ doesn't exceed $$$5 \cdot 10^5$$$. The sum of lengths of all strings $$$t$$$ in the test cases doesn't exceed $$$5 \cdot 10^5$$$.

Output: For each test case output in a separate line:  $$$-1$$$, if the answer doesn't exist;  two strings separated by spaces. The first one must contain a possible initial value of $$$s$$$. The second one must contain a sequence of letters — it's in what order one needs to remove letters from $$$s$$$ to make the string $$$t$$$. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one. 

Note: The first test case is considered in the statement.

Sample Inputs:
7
abacabaaacaac
nowyouknowthat
polycarppoycarppoyarppyarppyrpprppp
isi
everywherevrywhrvryhrvrhrvhv
haaha
qweqeewew

Sample Outputs:
abacaba bac
-1
polycarp lcoayrp
is si
everywhere ewyrhv
-1
-1

Solution (Python):
def construct(s, order):
    t = ''
    for x in order:
        t += s
        s = s.replace(x, '')
    return t

def solve(t):
    order = sorted(set(t), key=t.rindex)
    s = t[:sum((t.count(x) // i for (i, x) in enumerate(order, 1)))]
    if construct(s, order) == t:
        print(s, ''.join(order))
    else:
        print(-1)
for _ in range(int(input())):
    solve(input())

Solution (Python):
def construct(s, order):
    t = ''
    for x in order:
        t += s
        s = s.replace(x, '')
    return t
for _ in range(int(input())):
    t = input()
    order = sorted(set(t), key=t.rindex)
    s = t[:sum((t.count(x) // i for (i, x) in enumerate(order, 1)))]
    if construct(s, order) == t:
        print(s, ''.join(order))
    else:
        print(-1)

Solution (Python):
import math
import random
import time
from decimal import *
from collections import defaultdict
from bisect import bisect_left as lower_bound
from bisect import bisect_right as upper_bound

class FenwickTree:

    def __init__(self, x):
        bit = self.bit = list(x)
        size = self.size = len(bit)
        for i in range(size):
            j = i | i + 1
            if j < size:
                bit[j] += bit[i]

    def update(self, idx, x):
        """"""
        while idx < self.size:
            self.bit[idx] += x
            idx |= idx + 1

    def __call__(self, end):
        """"""
        x = 0
        while end:
            x += self.bit[end - 1]
            end &= end - 1
        return x

    def find_kth(self, k):
        """"""
        idx = -1
        for d in reversed(range(self.size.bit_length())):
            right_idx = idx + (1 << d)
            if right_idx < self.size and self.bit[right_idx] <= k:
                idx = right_idx
                k -= self.bit[idx]
        return (idx + 1, k)

class SortedList:
    block_size = 700

    def __init__(self, iterable=()):
        self.macro = []
        self.micros = [[]]
        self.micro_size = [0]
        self.fenwick = FenwickTree([0])
        self.size = 0
        for item in iterable:
            self.insert(item)

    def insert(self, x):
        i = lower_bound(self.macro, x)
        j = upper_bound(self.micros[i], x)
        self.micros[i].insert(j, x)
        self.size += 1
        self.micro_size[i] += 1
        self.fenwick.update(i, 1)
        if len(self.micros[i]) >= self.block_size:
            self.micros[i:i + 1] = (self.micros[i][:self.block_size >> 1], self.micros[i][self.block_size >> 1:])
            self.micro_size[i:i + 1] = (self.block_size >> 1, self.block_size >> 1)
            self.fenwick = FenwickTree(self.micro_size)
            self.macro.insert(i, self.micros[i + 1][0])

    def pop(self, k=-1):
        (i, j) = self._find_kth(k)
        self.size -= 1
        self.micro_size[i] -= 1
        self.fenwick.update(i, -1)
        return self.micros[i].pop(j)

    def __getitem__(self, k):
        (i, j) = self._find_kth(k)
        return self.micros[i][j]

    def count(self, x):
        return self.upper_bound(x) - self.lower_bound(x)

    def __contains__(self, x):
        return self.count(x) > 0

    def lower_bound(self, x):
        i = lower_bound(self.macro, x)
        return self.fenwick(i) + lower_bound(self.micros[i], x)

    def upper_bound(self, x):
        i = upper_bound(self.macro, x)
        return self.fenwick(i) + upper_bound(self.micros[i], x)

    def _find_kth(self, k):
        return self.fenwick.find_kth(k + self.size if k < 0 else k)

    def __len__(self):
        return self.size

    def __iter__(self):
        return (x for micro in self.micros for x in micro)

    def __repr__(self):
        return str(list(self))

def binary_search(vector, valoarea):
    left = 0
    right = len(vector) - 1
    while left <= right:
        centru = (left + right) // 2
        if vector[centru] < valoarea:
            left = centru + 1
        else:
            right = centru - 1
    return left

def main():
    answ = []
    pp = 10 ** 9
    restul = 1000000007
    teste = int(input())
    answ = []
    printare = []
    for gg in range(teste):
        stringul = input()
        n = len(stringul)
        dictionar = {}
        eroare = 0
        answ_doi = ''
        for i in range(n - 1, -1, -1):
            if stringul[i] not in dictionar:
                dictionar[stringul[i]] = 1
                answ_doi += stringul[i]
            else:
                dictionar[stringul[i]] += 1
        answ_doi = answ_doi[::-1]
        real = {}
        for i in range(len(answ_doi)):
            element = answ_doi[i]
            real[element] = dictionar[element] // (i + 1)
        comparatie = {}
        answ_unu = ''
        for i in stringul:
            if i in comparatie:
                comparatie[i] += 1
            else:
                comparatie[i] = 1
            if comparatie[i] <= real[i]:
                answ_unu += i
            else:
                break
        if answ_unu == '' or eroare == 1:
            answ.append('-1')
        else:
            verificare = answ_unu
            copie = answ_unu
            for j in answ_doi:
                copie = copie.replace(j, '')
                verificare += copie
            if verificare != stringul:
                answ.append('-1')
            else:
                answ.append(answ_unu + ' ' + answ_doi)
    print(*answ, sep='\n')
main()