We need to analyze the problem: Given an undirected graph with edges colored red or blue. Each move: pick a vertex, flip colors of all incident edges. Goal: make all edges same color (either all red or all blue). Find min moves, output sequence.
Observation: This is a classic "switching" problem on graphs. Flipping incident edges on a vertex corresponds to toggling the state of edges. We can model each edge's color as a binary variable (say 0 for red, 1 for blue, or vice versa). Flipping a vertex toggles all edges incident to it. This is similar to edge coloring/graph parity. Typically, we consider variables x_v ∈ {0,1} indicating whether we flip vertex v (1 if we flip, 0 if not). Then the resulting color of edge (u,v) becomes initial_color(u,v) XOR (x_u XOR x_v) because flipping both endpoints toggles the edge twice? Let's verify: initial color c_e ∈ {0,1}. Flipping a vertex toggles all incident edges. If we flip u, edge e toggles. If we flip v, also toggles. So total toggles = x_u + x_v mod 2 (since toggling twice cancels). So final color = c_e XOR (x_u XOR x_v). Because if exactly one of x_u, x_v is 1, toggles once; if both 0 or both 1, toggles 0 or 2 times (i.e., no net change). So yes, final = c_e ⊕ (x_u ⊕ x_v).
Goal: final colors all equal. So either all 0 (all red) or all 1 (all blue). So we want for all edges e, c_e ⊕ (x_u ⊕ x_v) = T, where T is target (0 or 1). Rearranged: (x_u ⊕ x_v) = c_e ⊕ T.
Thus we have constraints on vertex variables: For each edge (u,v), we require x_u XOR x_v = d_e, where d_e = c_e ⊕ T.
So it's a system of equations over GF(2) on the graph: x variables for vertices, each edge gives linear equation: x_u + x_v = d_e (mod 2). This is a classic 2-XOR-SAT problem. The graph is undirected, each equation involves two variables. The system may be consistent or not. If consistent, we can find a solution assigning x_v ∈ {0,1}. The number of moves = number of vertices with x_v = 1 (since each vertex flipped at most once? But can we flip a vertex more than once? Flipping twice cancels, so in minimal sequence we never need to flip a vertex more than once because flipping twice is equivalent to not flipping; also order doesn't matter. So we can consider that we either flip a vertex once or not at all. So indeed, the number of moves is the Hamming weight of solution x.
We need the minimum number of 1's among all solutions that satisfy either target T=0 or T=1. So we need to check consistency for each target, and find solution with minimum weight. Among both targets, choose smaller weight.
If neither consistent, output -1.
Now, the system is essentially determining a labeling of vertices with bits such that for each edge, the parity equals given d_e. This is like an edge-labeling that defines vertex label differences. This is similar to checking if a graph is bipartite with respect to these constraints? Actually, it's like we want a vertex labeling x such that for each edge, x_u XOR x_v equals given value. This is possible if and only if for every cycle, the XOR of d_e along the cycle is 0 (since going around cycle, XOR of (x_u XOR x_v) telescopes to 0). So we need to check each connected component: if we treat d_e as edge weight, we require the graph with those weights to be "consistent" (i.e., no odd cycles with sum 1?). Actually, condition: For any cycle, the XOR (sum mod 2) of the d_e along the cycle must be 0. Because if we walk around cycle: x_u1 XOR x_u2 XOR x_u2 XOR x_u3 ... XOR x_uk XOR x_u1 = 0. So sum of d_e along cycle mod 2 must be 0. So it's equivalent to saying that the edge labels d_e define a potential difference that is consistent.
If we assign arbitrarily a root and set x_root = 0, then for each vertex we compute x_v = XOR of d_e along any path from root to v; the value is well-defined if and only if for any cycle the XOR of d_e is 0. So essentially we need to check if the graph with edge weights d_e is "bipartite" in the sense that d_e indicate which partition? Actually, if d_e=0 means we require x_u = x_v; if d_e=1 means x_u ≠ x_v. This is like a graph with constraints: some edges enforce equality, others enforce inequality. This is exactly a 2-coloring problem with some edges requiring same color or opposite color. The condition for consistency is that there is no cycle with an odd number of inequality edges? Let's derive: For a cycle, if we go around, the parity of the number of inequality edges (d_e=1) determines whether we can assign consistently: we require that the number of 1's on cycle is even. Because starting from a vertex and traversing, each inequality flips the color, each equality keeps it; after full cycle we must return to original color, so flips must be even. So condition: in each cycle, the number of edges with d_e=1 is even. This is exactly that the graph with "type" edges is bipartite? Actually, treat each edge with d_e=0 as same side, d_e=1 as cross side. The constraints say: the graph formed by considering only equality edges connects vertices that must have same x; we can contract them? Another approach: treat the constraints as a system of linear equations. The solution space dimension = number of connected components (since each component can have two possible assignments if no constraints force a parity? Actually, if we pick a root, we set x_root=0 yields a unique assignment if consistent. But we could also flip all vertices in a component (since if x is a solution, then complementing all bits in a connected component? Let's check: If we flip all x_v in a component (i.e., x_v' = x_v ⊕ 1 for all v in component), then for any edge within component, (x_u' XOR x_v') = (x_u ⊕ 1) XOR (x_v ⊕ 1) = x_u XOR x_v, because 1⊕1=0. So the XOR remains unchanged. So if x satisfies constraints, then complementing all vertices in a component also yields a solution (since constraints are only about differences). However, if we complement only a subset? That would break edges across the subset boundary unless that edge has d_e=0? Actually, the system is linear homogeneous? Wait, the equation is x_u ⊕ x_v = d_e, so it's inhomogeneous. If we add a constant vector a (mod2) to all x, then new LHS: (x_u⊕a) ⊕ (x_v⊕a) = x_u⊕x_v. So indeed adding the same constant to both u and v does not change XOR. So if we add the same constant to all vertices in a connected component (i.e., flip all bits), the constraints remain satisfied. But we cannot add different constants to different vertices within same component because that would affect edges between them? Actually, if we add a constant a to all vertices in the entire component, that's fine; but adding constant to only a subset changes edges crossing the cut: for an edge between flipped and unflipped vertices, XOR becomes (x_u⊕1)⊕x_v = (x_u⊕x_v)⊕1, which would change d_e unless d_e flips, which is not allowed. So the only global degrees of freedom are: For each connected component, we can either keep the assignment derived from root=0, or flip the whole component (i.e., set root=1). So there are 2^{#components} possible solutions, but they differ by flipping entire components.
Thus to minimize number of flipped vertices (moves), for each component we can choose either assignment (the one with smaller number of 1's among the two possibilities). Because if a component has an assignment derived from some root value (0 or 1), the alternative is complementing all bits, which changes the count from k to (size - k). So we choose min(k, size - k) for each component, sum over components. This yields minimum weight solution for given target T.
So overall algorithm:
- Parse input: n, m, edges (u_i, v_i, color). Convert color to binary: say 0 for 'R', 1 for 'B' (or vice versa, but consistent). Actually, final goal is either all 0 or all 1; we need to treat both targets. However, note that flipping the target is equivalent to complementing d_e? Because d_e = c_e XOR T. If we choose T=0, d_e = c_e; if T=1, d_e = NOT c_e. So the constraints for T=1 are the complement of those for T=0. Consistency condition: For each cycle, XOR of d_e must be 0. XOR of complements: complementing each d_e is like adding 1 mod2 for each edge. So XOR over cycle of (1⊕c_e) = (length of cycle mod2) XOR (XOR of c_e). So consistency for T=1 requires that for each cycle, (cycle length mod2) XOR (XOR of c_e) = 0 => XOR of c_e = (cycle length mod2). That's a different condition. So we need to check both separately.
We could also note that the problem is symmetric: flipping all vertices results in complementing edge colors? Not exactly. But anyway.
Thus we need to, for each target T, construct the constraint graph (with edges labeled d_e) and check if it's consistent. Then if consistent, compute minimal flips per component.
But we also need to output an actual sequence of vertices (the vertices we flip) achieving the min, not just count. So we need to find actual assignment x: for each vertex, whether we flip.
Thus steps:
-
For each T in {0,1}:
a. Build the graph's constraint system: For each edge (u,v) with color c (0/1), set d = c XOR T.
b. For each connected component (graph may be disconnected), we need to check if there's an assignment to x (binary) such that for all edges in component, x_u XOR x_v = d. Condition: For any cycle, XOR of d around cycle = 0. This is equivalent to the graph being bipartite if we consider d as "color difference" constraints? Actually we can perform DFS from an arbitrary root in each component, assign x values according to path XOR, and check for conflicts. That will automatically detect any cycle inconsistency. So we don't need to pre-check cycles; we just run DFS and see if we encounter an edge where the computed x_u XOR x_v does not match d. If conflict occurs, system inconsistent.
c. If no conflict, we have a particular assignment (based on root=0). Let for component, we have assignment A: each vertex gets a value x_v (0 or 1). The alternative assignment is complement: x_v' = 1 - x_v. For minimizing flips (moves count), we choose the assignment with fewer ones (since each vertex with x=1 is flipped). So we can compute count_ones under A, and under complement (size - count_ones). Choose the one with min count. Also store which vertices are flipped: For the chosen assignment, the vertices with x=1 (if we choose A) or with x'=1 (i.e., vertices with A=0 if we choose complement) are the vertices we need to flip.
d. Sum counts across components, get total moves for target T. Also store the list of vertices to flip.
-
After processing both targets, if both inconsistent, output -1. Else choose target with smaller total moves (if tie, any). Output k and list of vertices (any order? The problem outputs list in the order of moves? The moves are applied sequentially; but flipping a vertex twice is not needed, and order doesn't matter because flipping vertices commutes (since flipping two vertices toggles incident edges; the final color depends only on parity of flips per vertex). So any order is fine. So we just output the vertex indices (the ones we flip) in any order. However, note: The example outputs "2\n3 4" (with space separation). So we can output list.
Now, complexity: n,m up to 100k. Need to do two passes (T=0 and T=1) maybe. But we can combine? We could treat the problem as solving two separate linear systems. Doing DFS for each target independently will be O(n+m) each, total O(2*(n+m)) which is fine.
But careful: The graph might have many components. We need to process for each target: For each component, run DFS to assign and check consistency. However, note that for T=0, d=c; for T=1, d=1⊕c. This means that if we run DFS for T=0, we get x assignment based on root=0. For T=1, we can simply take the complement of d, which is equivalent to flipping the parity of each edge? Actually, we could reuse results: Because if we assign for T=0 a labeling y such that y_u XOR y_v = c. Then for T=1, we need x such that x_u XOR x_v = 1⊕c = (y_u XOR y_v) ⊕ 1? Not exactly. Let's denote for T=0 we have assignment y that satisfies y_u XOR y_v = c. Then consider x = y (or complement)? Check: If we take x = y, then x_u XOR x_v = c, not 1⊕c. If we take x = 1⊕y, then (1⊕y_u) XOR (1⊕y_v) = y_u XOR y_v = c. So still not 1⊕c. So that doesn't work. What if we set x = y ⊕ something per component? Actually, if we set x = y, then we get d = c, not needed. So we need a different assignment. However, note that the consistency condition for T=1 is equivalent to checking that for each component, the parity of cycles with c? It's easier to just run DFS again with d' = c⊕1.
But we could also note that if we have an assignment for T=0, we can derive an assignment for T=1 by flipping the root assignment? No, because the constraints differ.
So independent DFS is fine.
Now, we need to output the list of vertices with minimal moves. Implementation details:
- Represent graph: adjacency list storing for each edge: neighbor and bit d for current target. We can pre-store edges with color, then during DFS for a target we compute d on the fly.
We can create adjacency list for edges with their color (0/1). Then during DFS for target T, for each neighbor, we compute d = color XOR T. Then we assign the child's x as x_current XOR d.
We'll need arrays: visited, x_val (assignment). For each component, we'll run DFS from unvisited vertex, set x[root]=0 (or some base). Then DFS: for each neighbor (u,v,color) compute d = color XOR T; child x = x[u] XOR d; if child already visited, check if x[child] matches expected; if conflict => inconsistent.
At the same time, we can count number of ones in this component for this assignment (cnt1). After DFS finishes for component, we have size comp_size (number of vertices visited). Then we can compute cnt1 and comp_size - cnt1; choose min. Also we need to record which vertices are flipped according to the chosen assignment. So we need to know for each vertex whether we flip it under the chosen assignment. For the component, if we choose original assignment (with root 0), then vertices with x=1 are flipped. If we choose complement, then vertices with x=0 are flipped (since we flip the whole component, effectively flipping the assignment, but then the vertices to flip are those with x=0 in the original assignment? Wait careful: The solution x indicates which vertices we flip. Under the assignment A from DFS (with root 0), we have a candidate solution where we flip vertices with x=1. Under the alternative solution (complement of A), we flip vertices with x=0 (because complement flips all bits: x' = 1 - x, so vertices with x'=1 are those with x=0). So for each component, we can decide to either flip set S1 = {v in comp: x[v]=1} or S2 = {v in comp: x[v]=0}. Choose the smaller set. So we need to know for each vertex its x value from DFS.
Thus after DFS we can, based on choice, collect vertices into global list.
Edge cases: Graph may have isolated vertices (no edges). For isolated vertex, there are no constraints. For a component with no edges (size=1), the equations are vacuous. Then any x is possible? Actually, there are no edges, so there is no constraint. Then we have a free variable: we can choose to flip it or not. So the minimal number of moves from this component is 0 (by not flipping). But wait, does flipping an isolated vertex affect any edge? No edges, so it does nothing. So we would never flip it, because flipping it would increase moves without changing anything. So indeed minimal is 0. In the DFS: an isolated vertex is a component with no edges. In our DFS, we would start from it, set x=0, and count ones=0, size=1, min=0, choose not to flip. So fine.
Now, check consistency: For components with no edges, always consistent. So overall.
Now, we must output -1 only if neither target yields consistency.
Now, let's test with examples.
Example 1:
n=3, edges:
1-2 B (c=1 if B=1)
3-1 R (c=0)
3-2 B (c=1)
We need to test T=0 (all red) and T=1 (all blue).
T=0: d = c. So edges:
1-2: d=1 => x1 xor x2 =1
3-1: d=0 => x1 xor x3 =0 => x1=x3
3-2: d=1 => x3 xor x2 =1 => x1 xor x2 =1 consistent with first? Actually from x1=x3, then x3 xor x2 = x1 xor x2 =1, matches. So consistent. Assign root 1? Let's DFS from 1 set x1=0. Then x2 = x1 xor d12 = 0 xor 1 =1. x3 = x1 xor d13 = 0 xor 0 =0. Check edge 2-3: x2 xor x3 =1 xor 0=1, matches d23=1. So assignment: x=[0,1,0]. Ones count=1 (vertex 2). Size=3, alternative count=2. So min moves=1. So choose flip vertex 2.
T=1: d = 1⊕c: edges: 1-2: 0, 3-1:1, 3-2:0. Constraints: x1=x2, x1≠x3, x3=x2? Actually x1=x2, x3=x2? From 1-2 d=0: x1=x2. 3-2 d=0: x3=x2 => x1=x3. But 3-1 d=1: x1≠x3 => conflict. So inconsistent. So best is T=0 with moves=1. Output matches.
Example 2:
n=6, m=5 edges:
1-3 R (c=0)
2-3 R (c=0)
3-4 B (c=1)
4-5 R (c=0)
4-6 R (c=0)
Let's test T=0 (all red): d = c.
Edges:
1-3:0 => x1=x3
2-3:0 => x2=x3 => so x1=x2=x3
3-4:1 => x3 xor x4 =1 => x4 = not x3
4-5:0 => x4=x5 => x5 = x4
4-6:0 => x4=x6 => x6 = x4
So consistent. Let's assign root? Choose component containing all? Check if all vertices are connected? Graph: edges connect 1-3,2-3,3-4,4-5,4-6 => all 6 vertices in one component. So do DFS from 1 set x1=0 => x3=0, x2=0, x4=1 (since d=1 on 3-4), x5=1, x6=1. So x: [0,0,0,1,1,1]. Ones count=3 (vertices 4,5,6). Size=6, alternative count=3 (complement would give ones=3 as well). So min moves=3? But example output says 2 moves: 3 4. So T=0 yields 3 moves, not minimal? Let's check T=1 (all blue): d = 1⊕c.
Edges:
1-3:1 => x1 xor x3 =1
2-3:1 => x2 xor x3 =1
3-4:0 => x3 xor x4 =0 => x3=x4
4-5:1 => x4 xor x5 =1 => x5 = not x4
4-6:1 => x4 xor x6 =1 => x6 = not x4
Now, constraints: from 1-3: x1 = not x3; 2-3: x2 = not x3; 3-4: x3=x4. So all x1,x2,x3,x4 related. Let's assign x3=0 then x4=0, x1=1, x2=1; then x5=1 (since x4=0 => x5=1), x6=1. So assignment: [1,1,0,0,1,1] ones count=4? vertices 1,2,5,6 ->4 ones. Complement gives 2 ones (flip all: [0,0,1,1,0,0] -> ones=2). So min moves=2 (vertices 3 and 4). That matches output (3,4). So indeed T=1 gives 2 moves, better than T=0's 3.
Thus algorithm picks min across targets.
Example 3: given, outputs -1. So both inconsistent.
Thus algorithm seems correct.
Now we need to implement:
- Input: n,m up to 100k, edges.
We'll store edges in adjacency list: for each vertex, list of (neighbor, color). color as int 0 for 'R', 1 for 'B'.
Now, we need to perform two passes. However, note that the DFS for each target will need to compute d based on color and T. We can reuse the visited array if we clear it, or just use separate visited array for each pass, but that's fine.
Implementation steps:
Define function solve_for_target(T) returning (is_possible, total_moves, flip_vertices_list) or maybe just the best result.
Pseudo:
def solve(T):
visited = [False] * (n+1)
x = [0] * (n+1) # assignment from DFS with root=0
possible = True
flips = [] # list of vertices to flip (minimum for this T)
total_moves = 0
for v in 1..n:
if not visited[v]:
# start DFS
stack = [v]
visited[v] = True
x[v] = 0
comp_vertices = [] # store vertices in this component
while stack:
u = stack.pop()
comp_vertices.append(u)
for (nei, col) in adj[u]:
d = col ^ T
expected = x[u] ^ d
if not visited[nei]:
visited[nei] = True
x[nei] = expected
stack.append(nei)
else:
if x[nei] != expected:
possible = False
# could break but need to maybe continue to check all? But we can return false directly.
# Since inconsistent, we can abort and return (False, ...)
# Actually, we need to exit the whole solve, but we may also early return.
if not possible: break
# After DFS component, compute count ones in x for this component
cnt1 = sum(1 for u in comp_vertices if x[u] == 1)
size = len(comp_vertices)
if cnt1 <= size - cnt1:
# choose original assignment (flip ones)
moves_comp = cnt1
for u in comp_vertices:
if x[u] == 1:
flips.append(u)
else:
moves_comp = size - cnt1
for u in comp_vertices:
if x[u] == 0:
flips.append(u)
total_moves += moves_comp
if not possible:
return (False, None, None)
else:
return (True, total_moves, flips)
Then in main:
result0 = solve(0)
result1 = solve(1)
if both False: print(-1)
else:
choose the one with smaller total_moves (if tie any; if only one true, choose that)
print(k)
print(*flips) # space separated
Potential issue: The list of flips may be unsorted, but order doesn't matter. However, it's convenient to keep in the order we add (DFS order). The problem says output any optimal sequence.
Now, complexity: O(n+m) per target => O(2*(n+m)) which is fine.
Edge Cases:
-
Graph with multiple edges? Problem says no multiple edges. So fine.
-
Large components: recursion depth might be an issue if using recursion. We'll use iterative DFS (stack) to avoid recursion depth limit.
-
Memory: adjacency list for up to 200k edges (since undirected, we store both directions). So store each edge twice.
Now, one nuance: In the DFS, we used d = col ^ T. This works because col is stored as integer 0/1. Good.
Now, we must ensure that we consider both targets independently. However, we might be able to optimize by noticing that for T=1, we can simply take the assignment from T=0 and then flip every vertex? Not correct as seen earlier. But we can also compute both simultaneously? But not needed.
Now, let's test with example 2 to confirm we get moves=2.
Simulate quickly: For T=1, d=col^1. Edges: as above. DFS from 1 (maybe start at 1). visited[1]=True, x1=0. Then process neighbors: (3,0) -> d=0^1=1, expected x3 = x1 ^ 1 = 1. So set x3=1, push. Also neighbor maybe? 1 only connects to 3. Continue: pop 3, comp_vertices includes 1,3. For vertex 3: neighbors: 1 (col 0) => d=1, but 1 visited: check x1=0, expected = x3^1 = 1^1=0, matches -> OK. neighbor 2 (col 0) => d=1, expected for 2 = x3 ^ 1 = 1^1=0, if not visited then set visited and push; neighbor 4 (col 1) => d=1^1=0, expected for 4 = x3^0 =1, set visited and push. So we get x2=0, x4=1. Then process 2: neighbor 3 (col 0) => d=1, check: x3=1, expected = x2^1 = 0^1=1, matches. No other. Process 4: neighbors: 3 (col 1) => d=0, check: x3=1, expected = x4^0=1, matches; neighbor 5 (col 0) => d=1, expected x5 = x4^1 =1^1=0, push; neighbor 6 (col 0) => d=1, expected x6 = x4^1=0, push. Process 5: neighbor 4 (col 0) => d=1, check: x4=1, expected = x5^1 =0^1=1, matches. Process 6: similar. So after DFS, comp_vertices = all 6. x: 1:0, 2:0, 3:1, 4:1, 5:0, 6:0. So cnt1 = 2 (vertices 3,4). size=6, alternative cnt0 =4. min=2, choose flip vertices 3 and 4. That matches.
Now, is there any case where flipping a vertex more than once could be beneficial? The model assumes each vertex flipped at most once because flipping twice cancels and order doesn't matter. So minimal sequence will not have repeats.
But wait: Could there be a scenario where the minimal number of moves is not representable by a set of vertices flipped exactly once? Suppose we have a solution where some vertices are flipped an odd number of times (1,3,5,...). Since flipping multiple times is equivalent to flipping once if odd, and zero if even. So we can always reduce to parity. So the set of vertices flipped (those with odd count) is a solution with at most that many moves. So any optimal solution can be represented as set of vertices flipped exactly once. So our model is correct.
Now, what about the possibility of flipping vertices in a particular order to achieve some intermediate states that allow reaching all same color even if the parity condition fails? No, because final color depends only on parity of flips per vertex, as we derived. Indeed, after a sequence of flips, the net effect on each edge is toggled number of times equal to (number of times its endpoints were flipped) mod 2 = (x_u + x_v) mod 2, where x_v is number of flips on vertex v mod 2. So the final state is determined solely by x_v mod 2. Thus any sequence is equivalent to choosing a set of vertices to flip odd number of times. So the problem reduces to existence of binary vector x.
Thus our solution is sound.
Now, we need to output the moves. The problem expects the vertices to be output in the order they are applied. Since we just output the set, we can output them in any order. However, must we output them in increasing order? Not required, examples show any order: first example output "2" (vertex 2) single number; second output "3 4". It's fine.
Now, confirm that we handle components correctly: For each component, we have two possible assignments (x or its complement). So we pick min. But wait: Could there be more degrees of freedom? The linear system over a connected graph: The nullspace (solutions to homogeneous system x_u XOR x_v = 0 for all edges) is the set of vectors that are constant on each component? Actually, homogeneous system: x_u XOR x_v = 0 for all edges, which forces all x equal within component, so solution space dimension = #components. For inhomogeneous system, if a particular solution exists, the general solution is particular solution plus any homogeneous solution. So indeed we can add constant to component. So only two possibilities per component: add 0 or add 1 to all vertices in that component. So we covered.
Thus algorithm is complete.
Now, test with a simple case: n=1, m=0. No edges. T=0: consistent, assignment x[1]=0, cnt1=0, min=0, flips none. T=1: also consistent? With no edges, any x works. So from DFS we set x[1]=0, cnt1=0. But for T=1, we need to check consistency: There are no constraints, so always consistent. However, what about the goal: all edges equal? Since no edges, vacuously true. So both T possible. Moves count: 0 for both. Output 0 and maybe blank line? But the output format: first line k, then second line with k integers. If k=0, we probably should output just "0" and then maybe an empty line? Usually, in such problems, if k=0, output 0 and then maybe nothing or a newline. But check typical Codeforces style: they often output "0" on first line and then second line maybe empty? But to be safe, we can output "0\n" (just 0 and newline). Or output "0\n\n"? The problem statement: "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." So if k=0, then we output just k? Usually they'd output "0" and then nothing else. But to be safe, we can output "0" and then newline. Or output "0\n\n" maybe acceptable. We can test by checking typical CF outputs: Many problems require outputting a line with k and then next line with the sequence if k>0; if k=0, just output "0" (maybe without extra line). I'd output "0" followed by newline, and that's it. But sometimes they expect an empty line? Let's see examples: They have k=1, then next line with integer. For k=0, it's ambiguous. Since n,m up to 100000, but it could happen. To be safe, we can output "0\n" and then maybe no extra line. Or output "0" and then newline and that's all. I think it's fine.
Now, consider case where graph is connected and consistent but both assignments give same count (size even and cnt1=size/2). Then we can pick any. Our algorithm picks original if cnt1 <= size - cnt1, so ties go to original.
Now, ensure we handle large input reading efficiently.
Implementation details in Python: Use sys.stdin.read() to read all. n,m up to 100k, edges m lines. Python should be fine with O(n+m) and recursion? But we use iterative DFS.
Memory: adjacency list as list of lists for each vertex (1-indexed). For each edge, we append (neighbor, col) to both ends.
Now, possible pitfalls:
-
The graph may have self-loops? Input says no self-loops. So ignore.
-
Multi-edges? None.
-
However, there might be parallel edges? Not allowed, but it could be present? It's guaranteed no multiple edges, so fine.
Now, check: In DFS, we used stack, but we also need to handle the case where the graph is disconnected. Our loop for v in 1..n works.
Now, for each component, we collect comp_vertices during DFS. That is fine. However, note that if the component is large, storing comp_vertices list may use extra memory but total across components is O(n). Fine.
Now, we need to perform this twice. We could reuse adjacency list but need separate visited and x arrays per pass. We'll just allocate fresh lists each time. Since n up to 100k, 2 passes okay.
But careful: The DFS for T=1 may fail early due to inconsistency; we can break and return. However, we must also free? Not needed.
Now, we also need to handle case where both targets give same min moves; we can pick any; but maybe we need to output any sequence. So tie break arbitrarily.
Now, test a scenario that might cause bug: In DFS, when we encounter a visited neighbor, we check if x[nei] matches expected. This checks consistency. However, there is a subtle point: The edge we are traversing may be visited from both ends as we process. That's fine.
Now, consider components with no edges: In DFS, we start at vertex, no neighbors, so we just add it to comp_vertices, x[v]=0, cnt1=0, min=0. Good.
Now, time complexity: O(2*(n+m)). With n,m=100k, that's trivial.
Now, does the algorithm always produce minimal total moves across both targets? Yes, because we evaluate each target separately and take min.
Now, let's think about potential pitfalls: The derived condition for consistency is that for each component, after DFS, we don't get conflict. But is this sufficient? Yes.
Now, confirm that the target T corresponds to final color. But wait: In our formulation, final color = c_e XOR (x_u XOR x_v) = T for all e. So T is the target color. So we cover both all-red and all-blue.
Now, test with example 3:
n=4, m=5 edges:
1-2 R (c=0)
1-3 R (c=0)
2-3 B (c=1)
3-4 B (c=1)
1-4 B (c=1)
Check T=0 (all red): d=c.
Constraints:
1-2:0 => x1=x2
1-3:0 => x1=x3 => so x1=x2=x3
2-3:1 => x2 xor x3 =1, but if x2=x3 then should be 0 -> conflict. So inconsistent.
T=1 (all blue): d=1⊕c:
1-2:1 => x1≠x2
1-3:1 => x1≠x3
2-3:0 => x2=x3
3-4:0? c=1, so d=0 => x3=x4
1-4:0? c=1, so d=0 => x1=x4
Now check consistency: From x1=x4, x3=x4 so x1=x3. But from 1-3: x1≠x3 -> conflict. So inconsistent. So -1. Good.
Now, what about a graph that is bipartite with d constraints? It will be consistent.
Now, any tricky cases where both targets are consistent but one yields less moves? Our algorithm handles.
Now, we must output the moves in any order. But ensure that we don't accidentally output duplicate vertices? In our method, for each component we either flip ones or zeros, and each vertex appears exactly once. So set is fine.
Now, we must confirm that the moves sequence length is k, and we output them.
Now, potential issues: The graph may have up to 100,000 vertices and edges, recursion depth may be an issue if we use recursion. We'll use iterative.
Now, could there be a scenario where the minimal number of moves is not achievable by flipping each vertex at most once because flipping a vertex twice could lead to a better number? No, because flipping twice is wasteful. So our binary x representation is minimal.
Now, check possibility of flipping vertices more than once to achieve same final state but with fewer flips? That's impossible because flipping a vertex an even number of times is equivalent to not flipping, and flipping odd number is equivalent to flipping once. So the parity is all that matters.
Now, final steps.
Now, confirm that we haven't overlooked the possibility of flipping vertices in a sequence where intermediate states may matter? The problem asks to make all edges equal color. The operation is deterministic and final state depends only on parity. So no.
Thus solution is correct.
Now, consider if there are multiple components: each component's assignment can be chosen independently, as there are no edges between components. So min sum is sum of min per component.
Now, what about constraints across components? There are none, because edges only within components.
So algorithm stands.
Now, we'll code in Python.
Implementation details:
- Read input: Use sys.stdin.buffer.read().split() to get tokens. But we have characters 'R' or 'B' among tokens. So we can parse accordingly.
Parsing:
data = sys.stdin.buffer.read().split()
First two tokens: n, m = int(data[0]), int(data[1])
Then for i in range(m): u = int(data[2+3i]), v = int(data[2+3i+1]), col_char = data[2+3*i+2].decode()? Actually split returns bytes, so we can compare to b'R' and b'B'. col = 0 if col_char == b'R' else 1.
Build adjacency list: adj = [[] for _ in range(n+1)]
For each edge: adj[u].append((v, col)); adj[v].append((u, col))
Now define solve(T):
visited = [False]*(n+1)
x = [0]*(n+1)
possible = True
total_moves = 0
flip_list = []
for v in range(1, n+1):
if not visited[v]:
# BFS/DFS
stack = [v]
visited[v] = True
x[v] = 0
comp_vertices = [v]
while stack:
u = stack.pop()
for (w, col) in adj[u]:
d = col ^ T
expected = x[u] ^ d
if not visited[w]:
visited[w] = True
x[w] = expected
stack.append(w)
comp_vertices.append(w)
else:
if x[w] != expected:
possible = False
# break out early, but we need to stop processing maybe
# Could set flag and break loops, but easiest: return (False,0,[])
# However we need to return early to save time.
# But we also need to handle that we may have multiple components, but if any inconsistent, whole target impossible.
# So we can just return (False,0,None)
if not possible: # but we need to detect within loop; we can break out of loops and then return.
# Actually we can early return.
# Let's structure: if we detect conflict, we can immediately return (False, 0, None)
# but careful: we are inside for loop and while loop; we can just return.
# So inside the check, we can return (False,0,None)
pass
But if we detect conflict inside while, we need to break out of all loops and return false. In Python, we can raise an exception or use a function that returns. I'd encapsulate the DFS part in a function that returns boolean and updates flip_list? But simpler: we can use a variable and after detection set possible=False and break loops. However breaking nested loops can be messy. I can use a try-except? Not needed.
Alternatively, we can structure the solve function to perform DFS for each component, but if conflict occurs, we set possible=False and break out of the outer loop. Since we have to return anyway, we can just set possible=False and then after the DFS loops we check possible and if false, we return (False,0,None) from solve. However, we still need to exit the for loop early, but we can break out and then after the for, if possible is false, return. But we need to break out of the while and then the for, so we can use a flag and break appropriately.
Pseudo:
def solve(T):
visited = [False](n+1)
x = [0](n+1)
total_moves = 0
flip_list = []
for v in range(1, n+1):
if not visited[v]:
# DFS
stack = [v]
visited[v] = True
x[v] = 0
comp_vertices = [v]
while stack:
u = stack.pop()
for (w, col) in adj[u]:
d = col ^ T
exp = x[u] ^ d
if not visited[w]:
visited[w] = True
x[w] = exp
stack.append(w)
comp_vertices.append(w)
else:
if x[w] != exp:
# inconsistency
return (False, 0, None)
# after DFS, component done
cnt1 = sum(1 for node in comp_vertices if x[node] == 1)
sz = len(comp_vertices)
if cnt1 <= sz - cnt1:
total_moves += cnt1
for node in comp_vertices:
if x[node] == 1:
flip_list.append(node)
else:
total_moves += sz - cnt1
for node in comp_vertices:
if x[node] == 0:
flip_list.append(node)
return (True, total_moves, flip_list)
This is clean: As soon as conflict detected, we return false. This works because we are inside a function; we can just return.
Now, ensure that we don't have any leftover state.
Now, potential issue: In the else branch for visited neighbor, we check x[w] != exp. But what about the case where w is the same as u? Not possible because no self-loops.
Edge case: multiple edges? Not present.
Now, note that we might revisit an edge from both ends; the check ensures consistency.
Now, time complexity: In the DFS, each edge processed twice (once from each endpoint) but that's fine.
Now, we must ensure we don't exceed recursion depth; we use stack.
Now, after we get results for both targets, we compare.
Now, one more nuance: The target T=0 and T=1 might both be consistent. But there is a possibility that we could combine assignments from both? No, each is independent.
Now, what about the possibility of flipping vertices in a component to achieve all edges red, but maybe we could also achieve all edges blue with fewer flips? Already considered.
Now, confirm correctness with more tests.
Test 1: n=2, m=1, edge 1-2 R. T=0: d=0 => x1=x2. Assignment: if root 1=0, then x2=0. cnt1=0, min=0. So 0 moves. T=1: d=1 => x1≠x2. Assignment: x1=0 -> x2=1. cnt1=1, min(1,1)=1 (since size=2, alternative cnt1=1 as well). So moves=1. So min is 0, output 0. Indeed, we can do nothing and all edges are red already? Edge is red, so all edges red already. So correct.
Test 2: n=2, m=1, edge 1-2 B. T=0: d=1 => x1≠x2. cnt1=1 min(1,1)=1. T=1: d=0 => x1=x2, cnt1=0 min=0. So min 0 (all blue already). Good.
Now, test a more complex scenario: cycle of odd length with all edges red. n=3, triangle all red? But no multiple edges, triangle with edges: (1-2 R), (2-3 R), (3-1 R). For T=0: d=0 on all edges, so constraints x1=x2, x2=x3, x3=x1 -> consistent, all equal. cnt1=0 or 1? From root 1=0: all 0, cnt1=0. So moves 0. For T=1: d=1 on all edges, constraints: x1≠x2, x2≠x3, x3≠x1. Check cycle: if x1=0, x2=1, then x3 must be ≠ x2 => 0, but then x3≠x1? 0≠0 false. So inconsistent. So min=0. Good.
Now, odd cycle with mix of colors maybe consistent for T=1? Example: triangle: edges: R,R,B. Let's compute: c:0,0,1. T=0: d=0,0,1. Constraints: x1=x2, x2=x3? from 0,0 => x1=x2 and x2=x3? Actually edge 2-3 is B so d=1: x2≠x3. So x1=x2 and x2≠x3 => x1≠x3. But edge 3-1 is R, d=0 => x3=x1. Contradiction. So T=0 inconsistent. T=1: d=1,1,0. Constraints: x1≠x2, x2≠x3, x3=x1. From x1≠x2 and x3=x1 => x3≠x2, which matches x2≠x3. So consistent. Solve: choose x1=0, then x3=0, x2=1. So assignment: x1=0, x2=1, x3=0. cnt1=1, size=3, alt=2, min=1. So moves=1. So output 1 and flip vertex 2 (or maybe 1 and 3? But min=1). Good.
Thus algorithm works.
Now, is there any case where both T are consistent but the minimal moves might be achieved by a solution that is not a combination of per-component choices? Since the solution space is exactly the union of assignments from picking either original or complement per component, the minimal Hamming weight solution is indeed the sum of per-component minima. Because the objective is separable: sum over components of number of ones. Since we can independently decide to complement each component, the total weight is sum over components of either cnt1 or size-cnt1. There's no cross-component coupling because no edges between components. So the global minimum is the sum of per-component minima. So our method yields global optimum.
Thus we are done.
Now, implementation in Python.
Potential performance: For each component we do a sum over comp_vertices to count ones. That's O(comp size). Total O(n). Good.
Now, we need to be careful that for large n, recursion depth not used.
Now, what about memory for adjacency list? It's fine.
Now, we also need to consider that we might run DFS twice, each time building visited and x arrays. That's okay.
Now, final step: Output. If both false, print -1. Else choose best. If best_k=0, print 0 and maybe nothing else? The problem's output format: "first output k — the minimum number of moves required to achieve the goal, then output k integers a1, a2, ..., ak". Usually they expect a newline after k, and then the list on the same or next line? The examples: they have "1\n2 " (with a space after 2? Actually example 1:
Output
1
2
So they printed 1 on first line, then second line "2 "? Actually likely they printed "1\n2". But they show "1\n2 " with a trailing space maybe. So we can just print k, then print the vertices separated by spaces. If k=0, maybe just print 0. I'll do: print(k) and if k>0: print(' '.join(map(str, flips))). That's standard.
Now, ensure we use sys.stdout.write for speed if needed, but print is fine.
Now, one more nuance: In the DFS, we used comp_vertices list built by appending each new vertex when visited. However, we might be adding vertices multiple times? We add when we set visited = True and push to stack, but also we added the root manually. In the while loop, when we pop, we might add neighbors to comp_vertices when we set visited. But ensure we don't double-add root. We added root initially before while. For each neighbor discovered, we add to comp_vertices. That's fine. But what about if a vertex is visited again via another path? It won't happen because we check visited before adding. So it's fine.
Alternatively, we could collect vertices by scanning the visited array later? But we need x values per vertex; we have them.
Now, let's test with a random small case by reasoning.
Now, think about isolated vertices: They are visited, comp_vertices has just that vertex, x=0, cnt1=0, min=0, no flips.
Now, another edge case: Graph with 2 vertices and 2 edges? But multiple edges not allowed. So not.
Now, what about components that are trees? The consistency is always satisfied for any d? Actually, on a tree, there is no cycle, so always consistent. Because we can assign root arbitrarily and propagate. So for trees, system always solvable for any T. But that doesn't guarantee all edges can be made same color? Wait, but we derived that for a tree, always consistent? Let's test: A tree with an edge of red and another edge? For T=0, d=c, we can assign x to satisfy all edge equations? In a tree, there is exactly one assignment (up to complement) that satisfies given d values, because you can set root=0, then propagate; there is no cycle to cause conflict. So indeed, for any tree, there is always a solution for any T? But is that always true? Let's test: For a tree, the equations are independent? They are not independent but always consistent because we can always assign. Actually, consider a tree with vertices and edges, the system x_u XOR x_v = d_e for all edges. If we assign root = 0, then for each neighbor we set x_v = d_e. This determines uniquely all x. There is no consistency condition because no cycles to check. So yes, always consistent. So for any tree, we can always make all edges either color? That seems plausible: You can always flip vertices to force all edges to become same color? Let's test with a simple tree: two vertices, edge red. To make all edges blue: we need x1 XOR x2 = 1 (since c=0, T=1 gives d=1). That is possible (x1=0, x2=1). So yes. For a path of length 2: three vertices 1-2 red, 2-3 blue. Want all red: T=0: d = c = (0,1). Need x1 XOR x2=0, x2 XOR x3=1. Solve: set x1=0 => x2=0, then x3=1. So works. Want all blue: T=1: d = (1,0) => x1 XOR x2=1, x2 XOR x3=0 => x1=0 => x2=1, x3=1. Works. So indeed, trees always have solutions. So the only impossible cases are when there is a cycle with odd number of 1's for given T. That is typical.
Now, we should also consider that if graph is disconnected, each component must be consistent independently. So overall.
Now, implementation is straightforward.
Now, I'll produce final Python code.
But before finalizing, think about large recursion depth: We'll use iterative stack.
Now, confirm that the adjacency list index from 1 to n inclusive.
Now, possible improvement: We can run DFS once and compute both solutions? Actually, we can compute for T=0 and T=1 simultaneously? Because the DFS for T=0 gives assignment A0; for T=1 we can compute from A0 by noting that d' = 1⊕c, and we might be able to derive assignment as A1 = A0 ⊕ something? Let's check: If we have a particular solution for T=0, that is vector y such that y_u XOR y_v = c. For T=1, we need x such that x_u XOR x_v = 1⊕c = (y_u XOR y_v) XOR 1. That is equivalent to (x_u XOR x_v) XOR (y_u XOR y_v) = 1, or (x_u XOR y_u) XOR (x_v XOR y_v) = 1. Define z_v = x_v XOR y_v. Then we need z_u XOR z_v = 1 for all edges. That means for each edge, z_u and z_v must differ. So z is a labeling such that adjacent vertices have different z. That's exactly a proper 2-coloring of the graph. So the existence of such z (i.e., a valid proper 2-coloring) is equivalent to the graph being bipartite. Moreover, if such z exists, then x = y XOR z. But note that the consistency condition for T=1 is that for every cycle, XOR of d' = 0, which is equivalent to the graph being bipartite? Actually, we can derive: T=1 system solvable iff graph is bipartite? Let's analyze: For T=1, we need x_u XOR x_v = 1⊕c. Given that y solves T=0, then the condition reduces to existence of z such that z_u XOR z_v = 1 for all edges. This is possible iff the graph is bipartite (since z is a proper 2-coloring). So T=1 solvable iff graph is bipartite, regardless of c? Wait, is that always true? Let's check: The condition for existence of z (with z_u XOR z_v = 1 for all edges) is that the graph has no odd cycles. That is bipartite. So if the graph is bipartite, then there exists a labeling z that makes all adjacent vertices opposite. Then x = y XOR z yields a solution for T=1. If the graph is not bipartite, then no such z exists, so T=1 may still be solvable? But earlier example 2, graph is actually a tree? Actually example 2 graph is a tree? Let's see: edges: 1-3,2-3,3-4,4-5,4-6. That's a tree (no cycles). It's bipartite. So T=1 is solvable (and we got solution). For a non-bipartite graph, is T=1 always unsolvable? Not necessarily. Example: triangle with edges: R,R,B gave T=1 solvable, but triangle is odd cycle, not bipartite. Wait, triangle is not bipartite. But we found a solution for T=1 earlier. So our derived equivalence is flawed? Let's re-express:
We have y satisfying y_u XOR y_v = c_e.
We want x satisfying x_u XOR x_v = 1⊕c_e.
Set z_v = x_v XOR y_v. Then x_u XOR x_v = (y_u XOR z_u) XOR (y_v XOR z_v) = (y_u XOR y_v) XOR (z_u XOR z_v) = c_e XOR (z_u XOR z_v). We need this equal to 1⊕c_e => c_e XOR (z_u XOR z_v) = 1⊕c_e => (z_u XOR z_v) = 1. So indeed, z must satisfy z_u XOR z_v = 1 for every edge. This is independent of c_e. So for any solution x to exist, we need a labeling z (binary) such that for all edges, z_u XOR z_v = 1. That is exactly a proper 2-coloring of the graph (i.e., graph must be bipartite). But earlier we found a non-bipartite graph (triangle) that had a solution for T=1. Let's re-check that example:
Triangle edges: (1-2) R (c=0), (2-3) R (c=0), (3-1) B (c=1). For T=1, we found a solution: x1=0, x2=1, x3=0. Check: x1 xor x2 =1 matches d=1 (since c=0, T=1 -> d=1). x2 xor x3 =1 matches d=1 (c=0 -> d=1). x3 xor x1 =0 matches d=0 (c=1 -> d=0). So indeed solution exists.
Now, is the graph bipartite? Triangle is not bipartite. So how can we have z with z_u xor z_v =1 for all edges? Let's compute y for T=0: For T=0, we need y such that y_u xor y_v = c. Is there a solution for T=0? We earlier found T=0 inconsistent for that triangle. So there is no y that satisfies T=0. Therefore our derivation "if there exists y solution for T=0" is not valid when T=0 is inconsistent. So the reduction only works if T=0 is solvable. But in the triangle case, T=0 is unsolvable. So we cannot use that transformation. So the condition for T=1 is not simply bipartiteness of the graph. It's the cycle condition with d' values. So we must treat each target independently.
Thus we can't simplify; we need two DFS runs.
Now, implement.
Now, let's think about potential pitfalls in the DFS: For a component, we start with x[v]=0. However, the choice of root value (0) is arbitrary; the resulting assignment A gives a particular solution. The alternative is complement. Both are valid. The min count per component is min(cnt1, size-cnt1). But is it guaranteed that the global minimum is sum of per-component minima? Yes, because there is no interaction between components: flipping all vertices in one component does not affect edges in other components. So total flips = sum of flips in each component. Since we can independently choose the orientation for each component, the minimum total is sum of minima.
Now, ensure that in the case where a component is inconsistent, the whole target fails.
Now, the order of flipping vertices: after we decide which vertices to flip, we output them in any order. Our algorithm will output them in the order of components processed, and within component, in the order of comp_vertices (which is the order of DFS). That's fine.
Now, we must also consider that the moves sequence length k may be large (up to n). Output all.
Now, test with a bigger case mentally.
Now, let's try a scenario with two components:
Component A: a tree, assignment yields cnt1=5, size=10 => min=5 (or 5? Actually min(5,5)=5). Component B: another tree, cnt1=2, size=7 => min(2,5)=2. Total 7. That's fine.
Now, think about the possibility that the graph may have up to 100k vertices, but we do two passes. The recursion stack? We use iterative, okay.
Now, also note that the input might have m=0. Then all vertices isolated. For T=0: all components size 1, cnt1=0, min=0. So total moves=0. For T=1: similarly, moves=0. So output 0. That's fine.
Now, check if there is any scenario where we need to output -1 when both targets are consistent but no solution? No, if consistent, there is solution.
Now, final code.
Potential micro-optimizations: Because we need to run DFS twice, we can define a function that takes T and returns a tuple. Use adjacency list built once.
Now, I'll implement.
Edge case: n=1, m=0: both passes consistent, moves=0. Output 0.
Now, consider n=1, m=??? but can't have edge because no self-loops. So m=0.
Now, code.
But I want to test with a random small graph using brute force to ensure algorithm gives correct minimal moves. Could do mental but fine.
Now, I realize one more nuance: In our DFS, we assign x based on root=0. But for components with no edges, x[v]=0; cnt1=0; min=0. Good.
Now, what about components where the root value choice matters? Actually, we set root=0; that yields one particular solution. The alternative complement yields the other. So we cover both.
Now, ensure that for components with no edges, both assignments are possible (x=0 or x=1). Our method only considered x=0 (since we set root=0) and its complement (x=1). That's both possibilities. So we have considered all.
Now, let's test with a component that has no edges but we might want to flip it? But flipping does nothing, so we would not. So min=0. Good.
Now, one more nuance: In the DFS, we detect conflict if an edge condition fails when neighbor already visited. But what about edges that are not traversed because of DFS order? All edges will be examined when processing endpoints, so all constraints checked.
Now, regarding performance: The inner loop for each vertex processes its adjacency list. For each edge, we compute d and check. That's fine.
Now, I think it's correct.
Now, let's write final code.
But before finalizing, let's consider if we need to worry about integer overflow? No.
Now, output: The problem might require the second line even if k=0? Usually they just output "0". But to be safe, we can output "0" and then newline and not print extra line. But the problem says "then output k integers". If k=0, there are no integers to output, so only the first line with 0 is sufficient. In Codeforces, it's typical to output "0" and maybe a blank line? But I think it's fine.
I'll implement:
if best_k == 0:
print(0)
else:
print(best_k)
print(' '.join(map(str, best_flips)))
Alternatively, always print best_k, then if best_k>0 print the list. But printing an empty line might be considered extra whitespace, but usually it's okay? However, some judges may expect no extra blank line. Safer: if best_k > 0: print list; else just print 0.
Now, sample 1: k=1, list=[2]; output "1\n2". That's fine.
Now, sample 2: k=2, list=[3,4]; output "2\n3 4". Good.
Now, sample 3: -1.
Now, implement solve function with adjacency list.
One more thing: Since we run two solves, we need to copy adjacency? It's read-only.
Now, I'll write code.
But wait, there might be a nuance: The graph may be large; but we might run out of recursion if we use recursion, but we use iterative stack.
Now, final code:
import sys
def solve(n, adj, T):
visited = [False]*(n+1)
x = [0]*(n+1)
total_moves = 0
flip_list = []
for v in range(1, n+1):
if not visited[v]:
# DFS
stack = [v]
visited[v] = True
x[v] = 0
comp_vertices = [v]
while stack:
u = stack.pop()
for (w, col) in adj[u]:
d = col ^ T
exp = x[u] ^ d
if not visited[w]:
visited[w] = True
x[w] = exp
stack.append(w)
comp_vertices.append(w)
else:
if x[w] != exp:
# inconsistency
return (False, 0, None)
cnt1 = 0
for node in comp_vertices:
if x[node] == 1:
cnt1 += 1
sz = len(comp_vertices)
if cnt1 <= sz - cnt1:
total_moves += cnt1
for node in comp_vertices:
if x[node] == 1:
flip_list.append(node)
else:
total_moves += sz - cnt1
for node in comp_vertices:
if x[node] == 0:
flip_list.append(node)
return (True, total_moves, flip_list)
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
adj = [[] for _ in range(n+1)]
for _ in range(m):
u = int(next(it))
v = int(next(it))
col = next(it)
# col is b'R' or b'B'
c = 0 if col == b'R' else 1
adj[u].append((v, c))
adj[v].append((u, c))
ok0, moves0, flips0 = solve(n, adj, 0)
ok1, moves1, flips1 = solve(n, adj, 1)
if not ok0 and not ok1:
print(-1)
return
# Choose best
if ok0 and (not ok1 or moves0 <= moves1):
best_moves = moves0
best_flips = flips0
else:
best_moves = moves1
best_flips = flips1
print(best_moves)
if best_moves > 0:
print(' '.join(map(str, best_flips)))
if __name__ == "__main__":
main()
Now, test with sample inputs.
Example1:
Input:
3 3
1 2 B
3 1 R
3 2 B
Parse: adj built. T=0: DFS component: start 1? Let's simulate: visited[1]=False; start v=1; stack=[1], x[1]=0, comp=[1]; pop 1: neighbors: (2,1) d=1^0=1, exp=0^1=1; 2 not visited -> visited, x[2]=1, push, comp add; (3,0) d=0^0=0, exp=0^0=0 -> 3 not visited -> x[3]=0, push, comp add. Next pop 3: neighbors: (1,0) d=0, exp=0^0=0, visited 1 x1=0 ok; (2,1) d=1, exp=0^1=1, visited 2 x2=1 ok. Pop 2: neighbors: (1,1) d=1, exp=1^1=0, visited 1 x1=0 ok; (3,1) d=1, exp=1^1=0, visited 3 x3=0 ok. comp vertices = [1,2,3]. cnt1 = 1 (vertex2). sz=3, cnt1 <= 2? yes. total_moves=1, flips=[2]. T=1: start 1, x1=0. Process: neighbor (2,1) d=1^1=0, exp=0^0=0 -> 2 not visited => x2=0; neighbor (3,0) d=0^1=1, exp=0^1=1 -> x3=1. Then from 3: neighbor (1,0) d=1, exp=1^1=0, x1=0 ok; neighbor (2,1) d=0? Wait (2,1) col=1 -> d=1^1=0? Actually col=1 for edge 3-2? But we have edge 3-2 with col=B => 1, so d=1^1=0, exp=1^0=1, but visited 2 x2=0 -> conflict (0 != 1). So inconsistency, return false. So best is T=0 with moves=1, flips=[2]. Output matches.
Example2:
We already reasoned.
Now, test with code mentally: should output 2\n3 4.
But note: our DFS order for T=1 might give flips list order as [3,4]? Let's simulate quickly:
For T=1, start v=1? We'll start from 1 because that's the first vertex unvisited. Process component: start 1, set x1=0. Then process as earlier, we got x: 1:0, 2:0, 3:1, 4:1, 5:0, 6:0. comp_vertices order depends on DFS order (stack LIFO). In our code, we push neighbors onto stack, order depends on adjacency list order. Let's assume adjacency list for vertex 1: [(3,0)]; vertex 3: [(1,0),(2,0),(4,1)]; vertex 2: [(3,0)]; vertex 4: [(3,1),(5,0),(6,0)]; etc. The DFS: start 1, push 1; pop 1, process (3,0) -> push 3 (stack=[3]); then pop 3, process its neighbors: say order (1,0) visited; (2,0) -> push 2; (4,1) -> push 4. The order of pushing may be order in adjacency list; assume we iterate in order given: maybe (1,0) first, then (2,0), then (4,1). So stack becomes [2,4] (since after pop 1, we pushed 3, then pop 3, push 2 then 4, so stack top is 4 if we append? Actually we are using list as stack: we append neighbors, then pop from end. So if we process neighbors in order, we first push 2, then push 4. So stack = [2,4]; then pop 4, process neighbors of 4: maybe (3,1),(5,0),(6,0). Push 5,6. Stack becomes [2,5,6] (since we push 5 then 6). Then pop 6, process; then pop 5; then pop 2; etc. So comp_vertices order may be [1,3,2,4,6,5] or something. But we collect vertices in order of discovery: we add root manually, then when we discover a neighbor, we append to comp_vertices. So order may be: start comp=[1]; discover 3 -> comp=[1,3]; discover 2 -> comp=[1,3,2]; discover 4 -> comp=[1,3,2,4]; discover 5 -> comp=...; discover 6 -> ... So comp_vertices will include 5 and 6 as discovered after 4. So after DFS, cnt1=2 (vertices 3 and 4 are ones). We check cnt1 <= sz-cnt1? 2 <= 4? Actually sz=6, cnt1=2, sz-cnt1=4, so we choose original (flip ones). So we add vertices with x=1: that is 3 and 4. So flips list = [3,4] (since they are in comp_vertices order, but we only add those with x=1; both are present and will be added in order they appear in comp_vertices. So likely 3 before 4, because 3 discovered before 4. So output "3 4". Good.
Now, example3: both inconsistent, output -1.
Now, test n=2,m=1 edge R: T=0 yields moves=0, T=1 yields moves=1. Choose moves=0, output 0. That's acceptable.
Now, we might want to ensure that if both targets have same moves but one is impossible? Already covered.
Now, what about if both are possible and moves equal, we choose arbitrarily. Good.
Now, we must be careful about reading input: We used sys.stdin.buffer.read().split() which splits on whitespace, returning list of bytes. For color, it will be like b'R' or b'B'. So comparison works.
Now, possible large output: we need to print up to 100k integers, which is fine.
Now, memory: adjacency list: each edge stored twice, each as tuple (neighbor, col). That's fine. But note that Python tuples overhead can be large. For 100k edges, 200k entries, each tuple maybe 56 bytes? That could be ~11 MB, plus list overhead, still within typical limits (256 MB). However, to be more memory efficient, we could store as two parallel lists or use arrays, but not necessary.
But note: m up to 100k, so adjacency list size about 200k entries. Each tuple of two ints (neighbor int, col int) may be about 56 bytes? Actually Python ints are objects, each 28 bytes? That could blow up. However, 200k * (tuple overhead + 2 ints) could be ~200k * (56 + 228) = 200k112 = 22.4 MB, plus list overhead. That's acceptable for typical Codeforces memory limit (256 MB). But Python may have more overhead. However, we can reduce by storing neighbor and col as a single integer encoded? We could store adjacency as list of (neighbor, col) using small tuple; it's usually okay. But to be safe, we could store as two separate adjacency lists: neighbors and colors. However, I think it's fine.
Alternatively, we could use arrays of edges and for each vertex keep list of indices; but that's more complex.
Given limits 100k, Python should manage.
But we also run two passes, each with visited and x arrays of size n+1, each about 100k booleans/ints. That's fine.
Now, one more nuance: When we do if x[w] != exp: return (False, 0, None), we are returning from the solve function immediately. This is fine. But we need to ensure that the function is not called from a loop where we need to clean up? Not needed.
Now, check: In the DFS, we might have recursion if we use iterative, but it's fine.
Now, confirm that we treat color conversion correctly: 'R' -> 0, 'B' -> 1. But note that in the problem, colors are 'R' and 'B'. I'll map 0 to red, 1 to blue. The final target T: 0 meaning all red, 1 meaning all blue.
But is there any ambiguity? Our derivation used c as initial color (0 for red, 1 for blue) and final T as target (0 for red, 1 for blue). So it's consistent.
Now, double-check with example 1: B is blue -> c=1. T=0 (all red) gave solution. So we got flip vertex 2. Good.
Now, test another: Edge B, want all blue (T=1). T=1: d = 1⊕1=0, so need x1=x2. Solution: x1=0,x2=0 => no flips. So output 0. That matches intuition.
Now, all good.
Now, potential bug: In our DFS, we start each component with x[v]=0. But what if the component is isolated (no edges)? Then we have assignment x[v]=0. The alternative is x[v]=1. But both are valid. Our method chooses min(0,1)=0, so no flip. That's minimal. Good.
But what if the component has edges but is consistent, but the assignment from root=0 yields cnt1 = some number. However, is it possible that the global optimum requires not taking per-component minima independently? Suppose we have two components, and we need to achieve a specific global target T. There's no coupling, so independent. So yes.
Now, consider the case where the graph has multiple components but each component's two possible assignments yield different sets of flips. Since flipping a vertex in one component doesn't affect edges in other, the total flips is sum. So independent.
Now, final code.
But we should also consider the possibility that the solution requires flipping vertices from both components in a specific order? No.
Now, it's done.
Now, let's think about performance: Python recursion might not be used, but we used stack list; however, we also used comp_vertices list to store all vertices in component. That's okay.
Now, I will produce final answer with code.
But before finalizing, test with a random small case where both T consistent but one yields lower moves, but maybe we can combine assignments across components in a non-independent way? No.
Now, let's also consider the possibility that the graph is disconnected and some components have no solution for a given T. Then overall impossible for that T.
Now, done.
Now, finalize.
But wait, there is a nuance: When we compute the alternative assignment by complementing the whole component, is that always a valid solution? Yes, because if x satisfies x_u XOR x_v = d_e for all edges, then for any constant a (0 or 1), x'_v = x_v ⊕ a also satisfies? Let's check: x'_u XOR x'_v = (x_u⊕a) XOR (x_v⊕a) = x_u XOR x_v. So it's still d_e. So it's a solution as well. So complementing whole component yields another solution.
Now, note: This relies on complementing all vertices in the component. If we complement only a subset, it's not necessarily a solution. So only two possibilities per component.
Thus good.
Now, we also need to ensure that in our DFS, the assignment we get from root=0 is indeed a solution. Since we propagate along edges ensuring each edge condition satisfied, and we also check for conflicts, if no conflict, it's a valid solution.
Now, one more nuance: In the DFS, when we encounter a visited neighbor, we check x[w] == exp. If it's not, we return inconsistent. But what if the edge is visited from both sides? That's fine. Also, what if the edge has d such that both sides produce same condition? Already.
Now, we should also consider the possibility of parallel edges? Not allowed.
Now, answer ready.
But I recall a known Codeforces problem: "Switching the Graph" maybe? Actually it's "Ehab and a component choosing problem"? Not sure. But it's similar to CF Round #1462 F? Not exactly.
Anyway.
Now, produce final answer with explanation and code.
Given the instructions: "You are ChatGPT..." I need to output a final answer. The final answer should include the solution explanation and the code. However, the user asked: "Find the minimum possible number of moves required ..." and input/output examples. So they likely want a solution code. The conversation indicates I'm to provide a solution. So I'll output the code.
But the prompt says "You are given an undirected graph...". It seems like a typical problem statement. The user likely expects the solution implementation. I'll produce the code and maybe a brief explanation? The final output should be the code? The instructions say: "You are ChatGPT, a large language model... Write a response..." Possibly they want the solution. I'll produce a detailed explanation and then the code.
Given it's a typical coding problem, I'll provide a solution in Python.
Now, finalize. We need to find the minimum number of vertex flips to make all edges the same color.
Each flip toggles the color of all incident edges.
If we denote by (x_v \in {0,1}) whether we flip vertex (v) (1 = flip), then the final color of edge ((u,v)) is
[
c_{uv} \oplus (x_u \oplus x_v).
]
We want this to be the same for all edges – say (T) (0 = red, 1 = blue).
Thus for every edge we require
[
x_u \oplus x_v = c_{uv} \oplus T.
]
This is a system of linear equations over GF(2).
For each connected component we can run a DFS assigning values starting from some root.
If at any time an edge contradicts the already assigned values, the system is inconsistent for that (T).
If consistent, we obtain one particular solution; another is obtained by flipping all bits in the component.
The number of moves is the number of vertices with (x_v=1).
For each component we choose the orientation (original or complement) that gives fewer flips, and sum over components.
We try both targets (T = 0) (all red) and (T = 1) (all blue).
If neither works output (-1); otherwise output the smaller total and the corresponding vertices.
Complexities: (O(n+m)) per target, total (O(n+m)).
import sys
def solve(n, adj, T):
visited = [False] * (n + 1)
x = [0] * (n + 1)
moves = 0
flip_list = []
for start in range(1, n + 1):
if visited[start]:
continue
# DFS
stack = [start]
visited[start] = True
x[start] = 0
comp_vertices = [start]
while stack:
u = stack.pop()
for v, col in adj[u]:
d = col ^ T
exp = x[u] ^ d
if not visited[v]:
visited[v] = True
x[v] = exp
stack.append(v)
comp_vertices.append(v)
else:
if x[v] != exp:
# inconsistency
return False, 0, None
cnt1 = sum(1 for v in comp_vertices if x[v] == 1)
sz = len(comp_vertices)
if cnt1 <= sz - cnt1:
moves += cnt1
for v in comp_vertices:
if x[v] == 1:
flip_list.append(v)
else:
moves += sz - cnt1
for v in comp_vertices:
if x[v] == 0:
flip_list.append(v)
return True, moves, flip_list
def main():
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
n = int(next(it))
m = int(next(it))
adj = [[] for _ in range(n + 1)]
for _ in range(m):
u = int(next(it))
v = int(next(it))
col = next(it) # b'R' or b'B'
c = 0 if col == b'R' else 1
adj[u].append((v, c))
adj[v].append((u, c))
ok0, moves0, flips0 = solve(n, adj, 0)
ok1, moves1, flips1 = solve(n, adj, 1)
if not ok0 and not ok1:
print(-1)
return
if ok0 and (not ok1 or moves0 <= moves1):
best_moves, best_flips = moves0, flips0
else:
best_moves, best_flips = moves1, flips1
print(best_moves)
if best_moves > 0:
print(' '.join(map(str, best_flips)))
if __name__ == "__main__":
main()