Graph Coloring (Codeforces 662B)
Tags: Others, dfs and similar

You are given an undirected graph that consists of n vertices and m edges. Initially, each edge is colored either red or blue. Each turn a player picks a single vertex and switches the color of all edges incident to it. That is, all red edges with an endpoint in this vertex change the color to blue, while all blue edges with an endpoint in this vertex change the color to red.Find the minimum possible number of moves required to make the colors of all edges equal.

Input: The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the number of vertices and edges, respectively.The following m lines provide the description of the edges, as the i-th of them contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the indices of the vertices connected by the i-th edge, and a character ci () providing the initial color of this edge. If ci equals 'R', then this edge is initially colored red. Otherwise, ci is equal to 'B' and this edge is initially colored blue. It's guaranteed that there are no self-loops and multiple edges.

Output: If there is no way to make the colors of all edges equal output  - 1 in the only line of the output. Otherwise first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak, where ai is equal to the index of the vertex that should be used at the i-th move.If there are multiple optimal sequences of moves, output any of them.


Sample Inputs:
3 3
1 2 B
3 1 R
3 2 B

6 5
1 3 R
2 3 R
3 4 B
4 5 R
4 6 R

4 5
1 2 R
1 3 R
2 3 B
3 4 B
1 4 B

Sample Outputs:
1
2

2
3 4

-1

Solution (Python):
from collections import deque
(n, m) = map(int, input().split())
adj = [[] for i in range(n)]
for i in range(m):
    (u, v, c) = input().split()
    (u, v) = (int(u) - 1, int(v) - 1)
    adj[u].append((v, c))
    adj[v].append((u, c))
visited = S = T = None

def bfs(i, k):
    q = deque([(i, 0)])
    while q:
        (u, p) = q.pop()
        if visited[u] >= 0:
            if visited[u] == p:
                continue
            else:
                return False
        visited[u] = p
        if p:
            S.append(u)
        else:
            T.append(u)
        for (v, c) in adj[u]:
            nxt = p if c == k else p ^ 1
            q.appendleft((v, nxt))
    return True

def solve(k):
    global visited, S, T
    visited = [-1] * n
    res = []
    for i in range(n):
        if visited[i] < 0:
            (S, T) = ([], [])
            if not bfs(i, k):
                return [0] * (n + 1)
            else:
                res.extend(S if len(S) < len(T) else T)
    return res
res1 = solve('R')
res2 = solve('B')
if min(len(res1), len(res2)) > n:
    print(-1)
else:
    print(min(len(res1), len(res2)))
    print(' '.join(map(lambda x: str(x + 1), res1 if len(res1) < len(res2) else res2)))

Solution (Python):
import sys
from math import inf
input = lambda : sys.stdin.readline().rstrip()
(n, m) = map(int, input().split())
graph = [[] for _ in range(n)]
for _ in range(m):
    (a, b, c) = input().split()
    a = int(a) - 1
    b = int(b) - 1
    c = 1 if c == 'R' else 0
    graph[a].append((b, c))
    graph[b].append((a, c))
ans = inf
chosen = []

def solve(t):
    global chosen
    global ans
    flips = [-1] * n
    for i in range(n):
        if flips[i] == -1:
            flips[i] = 0
            stack = [i]
            block = []
            while stack:
                u = stack.pop()
                block.append(u)
                for (v, c) in graph[u]:
                    if c == t:
                        if flips[v] == -1:
                            flips[v] = flips[u]
                            stack.append(v)
                        elif flips[v] != flips[u]:
                            return inf
                    elif flips[v] == -1:
                        flips[v] = 1 - flips[u]
                        stack.append(v)
                    elif flips[v] == flips[u]:
                        return inf
            if (tmp := sum((flips[x] for x in block))) > len(block) - tmp:
                for x in block:
                    flips[x] ^= 1
    cur = sum(flips)
    if ans == inf or len(chosen) > cur:
        ans = cur
        chosen = [i for i in range(n) if flips[i]]
    return cur
ans = min(ans, solve(0))
ans = min(ans, solve(1))
if ans != inf:
    print(ans)
    print(' '.join((str(x + 1) for x in chosen)))
else:
    print(-1)

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 1)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

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

        def LI():
            return list(input().split())

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

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        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.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')

def main():
    (n, m) = MII()
    path = [[] for _ in range(n)]
    for _ in range(m):
        (u, v, c) = LI()
        u = int(u) - 1
        v = int(v) - 1
        c = 1 if c == 'R' else 0
        path[u].append((v, c))
        path[v].append((u, c))
    ans = inf
    chosen = []
    for target in range(2):
        flips = [-1] * n
        f = True
        for i in range(n):
            if flips[i] == -1:
                flips[i] = 0
                stack = [i]
                block = []
                while stack:
                    u = stack.pop()
                    block.append(u)
                    for (v, c) in path[u]:
                        if c == target:
                            if flips[v] == -1:
                                flips[v] = flips[u]
                                stack.append(v)
                            elif flips[v] != flips[u]:
                                f = False
                        elif flips[v] == -1:
                            flips[v] = flips[u] ^ 1
                            stack.append(v)
                        elif flips[v] == flips[u]:
                            f = False
                if not f:
                    break
                res = sum((flips[i] for i in block))
                if res > len(block) - res:
                    for x in block:
                        flips[x] ^= 1
        if f and sum(flips) < ans:
            ans = sum(flips)
            chosen = [i for i in range(n) if flips[i]]
    if ans < inf:
        print(ans)
        print(' '.join((str(x + 1) for x in chosen)))
    else:
        print(-1)
t = 1
for _ in range(t):
    main()