Let's Play the Words? (Codeforces 1277D)
Tags: Math, hashing

Polycarp has $$$n$$$ different binary words. A word called binary if it contains only characters '0' and '1'. For example, these words are binary: "0001", "11", "0" and "0011100".Polycarp wants to offer his set of $$$n$$$ binary words to play a game "words". In this game, players name words and each next word (starting from the second) must start with the last character of the previous word. The first word can be any. For example, these sequence of words can be named during the game: "0101", "1", "10", "00", "00001".Word reversal is the operation of reversing the order of the characters. For example, the word "0111" after the reversal becomes "1110", the word "11010" after the reversal becomes "01011".Probably, Polycarp has such a set of words that there is no way to put them in the order correspondent to the game rules. In this situation, he wants to reverse some words from his set so that:  the final set of $$$n$$$ words still contains different words (i.e. all words are unique);  there is a way to put all words of the final set of words in the order so that the final sequence of $$$n$$$ words is consistent with the game rules. Polycarp wants to reverse minimal number of words. Please, help him.

Input: The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow.The first line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the number of words in the Polycarp's set. Next $$$n$$$ lines contain these words. All of $$$n$$$ words aren't empty and contains only characters '0' and '1'. The sum of word lengths doesn't exceed $$$4\cdot10^6$$$. All words are different.Guaranteed, that the sum of $$$n$$$ for all test cases in the input doesn't exceed $$$2\cdot10^5$$$. Also, guaranteed that the sum of word lengths for all test cases in the input doesn't exceed $$$4\cdot10^6$$$.

Output: Print answer for all of $$$t$$$ test cases in the order they appear.If there is no answer for the test case, print -1. Otherwise, the first line of the output should contain $$$k$$$ ($$$0 \le k \le n$$$) — the minimal number of words in the set which should be reversed. The second line of the output should contain $$$k$$$ distinct integers — the indexes of the words in the set which should be reversed. Words are numerated from $$$1$$$ to $$$n$$$ in the order they appear. If $$$k=0$$$ you can skip this line (or you can print an empty line). If there are many answers you can print any of them.


Sample Inputs:
4
4
0001
1000
0011
0111
3
010
101
0
2
00000
00001
4
01
001
0001
00001

Sample Outputs:
1
3 
-1
0

2
1 2

Solution (Python):
def solve():
    n = int(input())
    can_not = set()
    can_swap = []
    wait = {}
    flg_0 = False
    flg_2 = False
    for i in range(n):
        s = input()
        if s[0] == s[-1] and s[0] == '1':
            flg_2 = True
            can_not.add(2)
        elif s[0] == s[-1] and s[0] == '0':
            flg_0 = True
            can_not.add(0)
        elif s[0] != s[-1]:
            wait[s] = i
    num_0_1 = 0
    num_1_0 = 0
    type_ = [[], []]
    for s in wait:
        if s[::-1] in wait:
            can_not.add(1)
        elif s[0] == '0':
            num_0_1 += 1
            type_[0].append(wait[s])
        else:
            num_1_0 += 1
            type_[1].append(wait[s])
    if num_0_1 + num_1_0 == 0:
        if len(can_not) == 3:
            return (0, '')
        if 0 in can_not and 2 in can_not:
            return (-1, None)
        return (0, '')
    num = abs(num_0_1 - num_1_0) // 2
    if num == 0:
        return (0, '')
    else:
        typ = 0 if num_0_1 > num_1_0 else 1
        select = []
        for x in type_[typ][:num]:
            select.append(str(x + 1))
        return (num, ' '.join([x for x in select]))
for _ in range(int(input())):
    (num, ans) = solve()
    print(num)
    if ans is not None:
        print(ans)

Solution (Python):
t = int(input())
for _ in range(t):
    n = int(input())
    words = []
    for i in range(n):
        words.append(input())
    same_1 = []
    same_0 = []
    zero_1 = []
    one_0 = []
    index_zero_1 = []
    index_one_0 = []
    for (index, w) in enumerate(words):
        if w[0] == w[-1]:
            if w[0] == '0':
                same_0.append(w)
            elif w[0] == '1':
                same_1.append(w)
        elif w[0] == '0' and w[-1] == '1':
            zero_1.append(w)
            index_zero_1.append(index)
        elif w[0] == '1' and w[-1] == '0':
            one_0.append(w)
            index_one_0.append(index)
    if len(same_1) > 0 and len(same_0) == 0 and (len(zero_1) == 0) and (len(one_0) == 0):
        print(0)
        continue
    elif len(same_0) > 0 and len(same_1) == 0 and (len(zero_1) == 0) and (len(one_0) == 0):
        print(0)
        continue
    elif len(same_0) > 0 and len(same_1) > 0 and (len(zero_1) == 0) and (len(one_0) == 0):
        print(-1)
        continue
    elif len(one_0) == len(zero_1) or len(one_0) == len(zero_1) - 1 or len(one_0) == len(zero_1) + 1 or (len(one_0) - 1 == zero_1) or (len(one_0) + 1 == zero_1):
        print(0)
    else:
        if len(zero_1) >= len(one_0):
            words_to_reverse = zero_1
            words_set = set(one_0)
            index_map = index_zero_1
            required = (len(zero_1) - len(one_0)) // 2
        elif len(one_0) > len(zero_1):
            words_to_reverse = one_0
            words_set = set(zero_1)
            index_map = index_one_0
            required = (len(one_0) - len(zero_1)) // 2
        indices = []
        for (index, w) in enumerate(words_to_reverse):
            if w[::-1] in words_set:
                continue
            else:
                indices.append(index_map[index] + 1)
                if len(indices) >= required:
                    break
                else:
                    continue
        print(len(indices))
        print(*indices, sep=' ')

Solution (Python):
import sys
import collections
from collections import Counter
import itertools
import math
import timeit

def sieve(n):
    if n < 2:
        return list()
    prime = [True for _ in range(n + 1)]
    p = 3
    while p * p <= n:
        if prime[p]:
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 2
    r = [2]
    for p in range(3, n + 1, 2):
        if prime[p]:
            r.append(p)
    return r

def divs(n, start=1):
    divisors = []
    for i in range(start, int(math.sqrt(n) + 1)):
        if n % i == 0:
            if n / i == i:
                divisors.append(i)
            else:
                divisors.extend([i, n // i])
    return divisors

def divn(n, primes):
    divs_number = 1
    for i in primes:
        if n == 1:
            return divs_number
        t = 1
        while n % i == 0:
            t += 1
            n //= i
        divs_number *= t

def flin(d, x, default=-1):
    left = right = -1
    for i in range(len(d)):
        if d[i] == x:
            if left == -1:
                left = i
            right = i
    if left == -1:
        return (default, default)
    else:
        return (left, right)

def ceil(n, k):
    return n // k + (n % k != 0)

def ii():
    return int(input())

def mi():
    return map(int, input().split())

def li():
    return list(map(int, input().split()))

def lcm(a, b):
    return abs(a * b) // math.gcd(a, b)

def prr(a, sep=' '):
    print(sep.join(map(str, a)))

def dd():
    return collections.defaultdict(int)

def ddl():
    return collections.defaultdict(list)
t = ii()
for _ in range(t):
    oz = zo = oo = zz = 0
    n = ii()
    pool = set()
    st = []
    pos01 = []
    pos10 = []
    for i in range(n):
        s = input()
        pool.add(s)
        st.append(s)
        if s[0] != s[-1]:
            if s[0] == '1':
                oz += 1
                pos10.append(i)
            else:
                zo += 1
                pos01.append(i)
        elif s[0] == '1':
            oo += 1
        else:
            zz += 1
    if min(zz, oo) > 0 and max(zo, oz) == 0:
        print(-1)
        continue
    if abs(zo - oz) <= 1:
        print('0\n')
        continue
    (a, b) = (zo, oz)
    ar = pos01
    if b > a:
        (a, b) = (b, a)
        ar = pos10
    r = 0
    res = []
    for i in ar:
        if st[i][::-1] not in pool:
            r += 1
            a -= 1
            b += 1
            res.append(i + 1)
        if abs(a - b) <= 1:
            break
    if abs(a - b) <= 1:
        print(r)
        prr(res, ' ')
    else:
        print(-1)