import sys
from collections import deque
def main():
sys.setrecursionlimit(1 << 25)
n, m = map(int, sys.stdin.readline().split())
edges = []
adj = [[] for _ in range(n + 1)] # nodes are 1-based
for _ in range(m):
parts = sys.stdin.readline().split()
u = int(parts[0])
v = int(parts[1])
c = parts[2].strip()
if c == 'R':
b_red = 0
b_blue = 1
else:
b_red = 1
b_blue = 0
edges.append((u, v, c))
adj[u].append( (v, b_red, b_blue) )
adj[v].append( (u, b_red, b_blue) )
# Find connected components
visited = [False] * (n + 1)
component_id = [0] * (n + 1)
components = []
current_component = 0
for node in range(1, n + 1):
if not visited[node]:
current_component += 1
q = deque()
q.append(node)
visited[node] = True
component = []
while q:
u = q.popleft()
component.append(u)
for (v, _, _) in adj[u]:
if not visited[v]:
visited[v] = True
q.append(v)
components.append(component)
for v in component:
component_id[v] = current_component
# Prepare for each target
solutions = {}
for target in ['R', 'B']:
ok = True
total_steps = 0
chosen = [False] * (n + 1)
T = target
for component in components:
nodes_list = component.copy()
start_node = nodes_list[0]
# Initialize variables for this component
x = [-1] * (n + 1)
q = deque()
x[start_node] = 0
q.append(start_node)
conflict = False
while q and not conflict:
u = q.popleft()
for (v, b_red, b_blue) in adj[u]:
if component_id[v] != component_id[u]:
continue # not in this component
if T == 'R':
target_b = b_red
else:
target_b = b_blue
desired_xv = (target_b - x[u]) % 2
if x[v] == -1:
x[v] = desired_xv
q.append(v)
else:
if x[v] != desired_xv:
conflict = True
break
if conflict:
break
if conflict:
ok = False
break # target T is invalid
else:
s = sum(x[node] for node in nodes_list)
component_size = len(nodes_list)
alt = component_size - s
if alt < s:
effective = alt
flip = True
else:
effective = s
flip = False
total_steps += effective
for node in nodes_list:
val = x[node]
if flip:
val = 1 - val
if val == 1:
chosen[node] = True
if ok:
solutions[target] = (total_steps, chosen.copy())
else:
solutions[target] = None
# Evaluate best among possible targets
best_target = None
min_total = float('inf')
best_chosen = None
for t in ['R', 'B']:
if solutions[t] is not None:
(steps, chosen_arr) = solutions[t]
if steps < min_total:
min_total = steps
best_target = t
best_chosen = chosen_arr.copy()
if best_target is None:
print(-1)
else:
vertices = [i for i in range(1, n+1) if best_chosen[i]]
print(len(vertices))
print(' '.join(map(str, vertices)))
if __name__ == "__main__":
main()
Wait, I just noticed a small mistake in the approach for the components: when building x array for the current component, it's better to clear x only for nodes in the current component? Because the x array is initialized to -1 for all nodes each time, but when running multiple components in a loop, because for each component, variables are separate, the x array can be reused since the BFS is only within the component and not interfering.
Wait, in the code above, for each component's processing (inside the loops for components), the x array is reinitialized as [-1] * (n+1), so previous component nodes have their x set to -1 again. That part is okay. The code should be okay.
Another potential issue is the component_id array. I think the component_id is correctly set during the components finding.
Testing the code against the first example:
Input 3 3:
Edges are:
1-2 B: stored in adj both ways.
3-1 R: so for target R, component R for this edge would be 0 (correct, since original edge is R and target R wants it even).
Third edge is 3-2 B → in target R, equation needs 1 (1's contribution to sum.
The calculation would go as the first example's walk-through, resulting in node 2 being selected, so the code should output that.
Another point: when determining the edges between nodes, we must loop through all edges from u's adjacency list, but since the component is handled via component_id check, it will only process edges within the component.
Thus, the code should handle that correctly.