Letter Exchange (Codeforces 1786D)
Tags: Others, graphs

A cooperative game is played by $$$m$$$ people. In the game, there are $$$3m$$$ sheets of paper: $$$m$$$ sheets with letter 'w', $$$m$$$ sheets with letter 'i', and $$$m$$$ sheets with letter 'n'.Initially, each person is given three sheets (possibly with equal letters).The goal of the game is to allow each of the $$$m$$$ people to spell the word "win" using their sheets of paper. In other words, everyone should have one sheet with letter 'w', one sheet with letter 'i', and one sheet with letter 'n'.To achieve the goal, people can make exchanges. Two people participate in each exchange. Both of them choose exactly one sheet of paper from the three sheets they own and exchange it with each other.Find the shortest sequence of exchanges after which everyone has one 'w', one 'i', and one 'n'.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows.The first line of each test case contains a single integer $$$m$$$ ($$$2 \le m \le 10^5$$$) — the number of people.The $$$i$$$-th of the next $$$m$$$ lines contains a string $$$s_i$$$ of length $$$3$$$ consisting of lowercase English letters 'w', 'i', and 'n', denoting the letters person $$$i$$$ has on their sheets of paper at the beginning of the game, in arbitrary order.Each of the letters 'w', 'i', and 'n' appears on the sheets of paper exactly $$$m$$$ times in total.It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$10^5$$$.

Output: For each test case, print a non-negative integer $$$k$$$ — the smallest number of exchanges people need to make everyone have one 'w', one 'i', and one 'n'.In each of the next $$$k$$$ lines print four tokens $$$a_1$$$ $$$c_1$$$ $$$a_2$$$ $$$c_2$$$, describing the exchanges in chronological order ($$$1 \le a_1, a_2 \le m$$$; $$$a_1 \ne a_2$$$; $$$c_1, c_2$$$ are one of $$$\{\mathtt{w}, \mathtt{i}, \mathtt{n}\}$$$): person $$$a_1$$$ gives letter $$$c_1$$$ to person $$$a_2$$$, while person $$$a_2$$$ gives letter $$$c_2$$$ to person $$$a_1$$$ at the same time.If there are multiple solutions, print any.


Sample Inputs:
3
2
nwi
inw
3
inn
nww
wii
4
win
www
iii
nnn

Sample Outputs:
0
2
2 w 3 i
3 w 1 n
3
2 w 3 i
2 w 4 n
3 i 4 n

Solution (Python):
import sys

def solve():
    inp = sys.stdin.readline
    m = int(inp())
    a = [None] * m
    d = {'w': 0, 'i': 1, 'n': 2}
    l = [[] for i in range(3)]
    p = [[[] for i in range(3)] for i in range(3)]
    for i in range(1, m + 1):
        c = [0, 0, 0]
        for v in inp().strip():
            c[d[v]] += 1
        mm = max(c)
        if mm == 2:
            p[c.index(mm)][c.index(0)].append(str(i))
        elif mm == 3:
            l[c.index(mm)].append(str(i))
    res = []
    win = list('win')
    q = []
    for i in range(3):
        for j in range(3):
            q.append((i, j))
    while q:
        qq = []
        for (i, j) in q:
            v = p[i][j]
            w = p[j][i]
            while v and w:
                res.append(f'{v.pop()} {win[i]} {w.pop()} {win[j]}')
        for j in range(3):
            w = l[j]
            if w:
                for i in range(3):
                    if i != j:
                        v = p[i][j]
                        if v and w:
                            z = w.pop()
                            res.append(f'{v.pop()} {win[i]} {z} {win[j]}')
                            p[j][3 - i - j].append(z)
                            qq.append((j, 3 - i - j))
        if not qq:
            for i in range(3):
                v = p[i][j]
                if v:
                    z = 3 - i - j
                    w = p[j][z]
                    if w:
                        zz = w.pop()
                        res.append(f'{v.pop()} {win[i]} {zz} {win[j]}')
                        p[i][z].append(zz)
                        qq.append((i, z))
        if not qq:
            for i in range(3):
                v = l[i]
                if v:
                    for j in range(3):
                        if i != j:
                            w = l[j]
                            if v and w:
                                z = v.pop()
                                zz = w.pop()
                                res.append(f'{z} {win[i]} {zz} {win[j]}')
                                p[i][3 - i - j].append(z)
                                p[j][3 - i - j].append(zz)
                                qq.append((i, 3 - i - j))
                                qq.append((j, 3 - i - j))
        q = qq
    for i in range(3):
        for j in range(3):
            if p[i][j]:
                raise Exception('wut')
    for i in range(3):
        if l[i]:
            raise Exception('wut')
    print(len(res))
    if res:
        print('\n'.join(res))

def main():
    for i in range(int(sys.stdin.readline())):
        solve()
if __name__ == '__main__':
    main()

Solution (Python):
import sys
input = sys.stdin.readline

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

def readInt():
    return int(input())

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

def readStr():
    return input().strip()

def solve():
    m = readInt()
    s = {'w': 0, 'i': 1, 'n': 2}
    a = [[s[c] for c in readStr()] for _ in range(m)]
    b = [[] for _ in range(6)]
    for i in range(m):
        tmp = [0, 0, 0]
        (x, y, z) = a[i]
        tmp[x] += 1
        tmp[y] += 1
        tmp[z] += 1
        if max(tmp) == 1:
            continue
        elif max(tmp) == 3:
            j = tmp.index(3) * 2
            b[j].append(i + 1)
            b[j + 1].append(i + 1)
        else:
            j = tmp.index(2) * 2
            k = tmp.index(0)
            if j <= 2:
                b[j + k // 2].append(i + 1)
            else:
                b[j].append(i + 1) if k == 0 else b[j + 1].append(i + 1)
    ans = []
    while True:
        if b[0] and b[2]:
            ans.append((b[0].pop(), 'w', b[2].pop(), 'i'))
        elif b[1] and b[4]:
            ans.append((b[1].pop(), 'w', b[4].pop(), 'n'))
        elif b[3] and b[5]:
            ans.append((b[3].pop(), 'i', b[5].pop(), 'n'))
        elif b[0] and b[3] and b[4]:
            (x, y, z) = (b[0].pop(), b[3].pop(), b[4].pop())
            ans.append((x, 'w', y, 'i'))
            ans.append((y, 'w', z, 'n'))
        elif b[1] and b[5] and b[2]:
            (x, y, z) = (b[1].pop(), b[5].pop(), b[2].pop())
            ans.append((x, 'w', y, 'n'))
            ans.append((y, 'w', z, 'i'))
        else:
            break
    print(len(ans))
    for each in ans:
        print(*each)
    return
for _ in range(int(input())):
    solve()

Solution (Python):
from collections import defaultdict

def others(s):
    return (c for c in 'win' if c not in s)

def compute_swaps(letters):
    w = len([c for c in letters if c == 'w'])
    i = len([c for c in letters if c == 'i'])
    n = len([c for c in letters if c == 'n'])
    inverse = {}
    for (count, char) in ((w, 'w'), (i, 'i'), (n, 'n')):
        if count not in inverse:
            inverse[count] = char
    if w == 3 or i == 3 or n == 3:
        extra = inverse[3]
        rest = others(extra)
        return [(extra, needed) for needed in rest]
    if w == 2 or i == 2 or n == 2:
        extra = inverse[2]
        rest = others(extra + inverse[1])
        return [(extra, r) for r in rest]
    return []

def solution():
    num_people = int(input())
    graph = defaultdict(list)
    for i in range(num_people):
        letters = input()
        needed_swaps = compute_swaps(letters)
        for pair in needed_swaps:
            graph[pair].append(i + 1)
    result = []
    for i in range(3):
        a = 'win'[i]
        b = 'win'[(i + 1) % 3]
        forward = graph[a, b]
        backward = graph[b, a]
        while len(forward) > 0 and len(backward) > 0:
            p1 = forward.pop()
            p2 = backward.pop()
            result.append(f'{p1} {a} {p2} {b}')
    start = graph['w', 'i']
    target = graph['i', 'n']
    other = graph['n', 'w']
    assert len(start) == len(target) and len(target) == len(other)
    while len(start) > 0:
        p1 = start.pop()
        p2 = target.pop()
        p3 = other.pop()
        result.append(f'{p1} w {p2} i')
        result.append(f'{p2} w {p3} n')
    start = graph['w', 'n']
    target = graph['n', 'i']
    other = graph['i', 'w']
    assert len(start) == len(target) and len(target) == len(other)
    while len(start) > 0:
        p1 = start.pop()
        p2 = target.pop()
        p3 = other.pop()
        result.append(f'{p1} w {p2} n')
        result.append(f'{p2} w {p3} i')
    print(len(result))
    for line in result:
        print(line)
if __name__ == '__main__':
    cases = int(input())
    while cases > 0:
        solution()
        cases -= 1