Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not.
The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home.
Unfortunately, not everything is as great as Valera II would like. The main part of the group were gastarbeiters — illegal immigrants who are enthusiastic but not exactly good at understanding orders in Berlandian. Therefore, having received orders to asphalt the roads coming from some of the city, the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it.
Upon learning of this progress, Valera II was very upset, but since it was too late to change anything, he asked you to make a program that determines whether you can in some way asphalt Berlandian roads in at most n days. Help the king.
Input
The first line contains two space-separated integers n, m — the number of cities and roads in Berland, correspondingly. Next m lines contain the descriptions of roads in Berland: the i-th line contains three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n; ai ≠ bi; 0 ≤ ci ≤ 1). The first two integers (ai, bi) are indexes of the cities that are connected by the i-th road, the third integer (ci) equals 1, if the road was initially asphalted, and 0 otherwise.
Consider the cities in Berland indexed from 1 to n, and the roads indexed from 1 to m. It is guaranteed that between two Berlandian cities there is not more than one road.
Output
In the first line print a single integer x (0 ≤ x ≤ n) — the number of days needed to asphalt all roads. In the second line print x space-separated integers — the indexes of the cities to send the workers to. Print the cities in the order, in which Valera send the workers to asphalt roads. If there are multiple solutions, print any of them.
If there's no way to asphalt all roads, print "Impossible" (without the quotes).
Examples
Input
4 4
1 2 1
2 4 0
4 3 1
3 2 0
Output
4
3 2 1 3
Input
3 3
1 2 0
2 3 0
3 1 0
Output
Impossible
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are given a graph with n vertices, m edges, each edge has initial state: 1 = asphalted, 0 = not asphalted. Each day, we pick a city v, and the crew toggles all edges incident to v (i.e., if an edge is asphalted, they remove asphalt; if not, they add asphalt). Actually, the description: "the group asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it." That's exactly toggling the state of each incident edge. So operation on vertex v flips the state of all edges adjacent to v.
Goal: after a sequence of operations (at most n days, i.e., at most n vertex selections, repetitions allowed) all edges become asphalted (state 1). We need to output a sequence of at most n vertices achieving this, or say impossible.
We have constraints: n up to? Not specified, but likely up to some reasonable. But we need an algorithm.
This is reminiscent of toggling edges via vertex operations. The operation on vertex v toggles all incident edges. This is like a linear algebra problem over GF(2). Let's denote the state of each edge e as 0 or 1 (1 means asphalted). Initially we have a vector b (of length m) representing initial states. Each operation on vertex v toggles all edges incident to v. So after a set of operations (each applied once, since applying twice cancels? Actually sequence matters if we apply same vertex multiple times? Since toggling twice restores original, so we can assume each vertex is used at most once in an optimal solution? But since we can have at most n days, it's not necessarily that we use each at most once; we could use some vertex twice, but that would be wasteful as two toggles cancel, so we could remove both occurrences to shorten sequence. However, we are allowed up to n days, not necessarily minimal. So we could simplify to a set of vertices to toggle (each either toggled odd or even times). So effectively we are looking for a subset S of vertices such that after toggling all edges incident to vertices in S (each exactly once, order irrelevant), all edges become 1.
But the problem asks for a sequence of length at most n, not necessarily minimal. So we can just find any subset S with size <= n? Actually size of S could be as large as n, because we have up to n operations. So we need to find any subset S (possibly with repetitions? But as argued, we can compress multiple toggles to parity, so we can assume each vertex toggled at most once; if we need to output a sequence with length up to n, we could output S if |S| <= n, which it will be because n is max number of vertices, so |S| <= n. But if solution requires toggling more than n vertices? That can't happen because there are only n vertices, so at most n distinct vertices. So the maximum distinct vertices used is n. Thus we can always represent solution as a set of vertices toggled odd number of times (i.e., characteristic vector x ∈ GF(2)^n). The resulting edge state for each edge e = (u,v) is initial state b_e + x_u + x_v (mod 2). We want this to be 1 for all edges. So we have linear equations: For each edge e = (u,v), x_u + x_v = 1 + b_e (mod 2). That is: x_u + x_v = c_e where c_e = 1 - b_e? Wait: We want final state = b_e + x_u + x_v = 1 → x_u + x_v = 1 - b_e (mod 2). Let's denote required parity r_e = 1 - b_e (mod 2). So equation: x_u + x_v = r_e.
Thus we have a system over GF(2) of m equations in n variables. This is a classic problem: For a graph, we need to assign each vertex a bit such that for each edge (u,v) the XOR of endpoints equals some given value r_e. This is possible if and only if for every cycle, the sum of r_e around the cycle is 0 mod 2. Because traversing a cycle, the sum of (x_u + x_v) over edges equals 2 * sum of x_i over vertices visited, which is 0 mod 2. So the condition is that for each cycle, the XOR (sum mod 2) of r_e over edges in the cycle must be 0.
Equivalently, we can treat it as: Let each edge have a desired parity. Then we want to assign potentials x_i to vertices such that for each edge (u,v), x_u XOR x_v = r_e. This is like a graph 2-coloring with given edge parity constraints. If the graph is connected, we can pick an arbitrary root, set its value arbitrarily (say 0), then propagate along edges: For each edge (u,v) with known x_u, we set x_v = x_u XOR r_e. This will be consistent if and only if for every cycle the constraints hold. So we can check consistency.
If the graph is disconnected, we can treat each component independently; each component can have a free variable (the root value) because there is no global constraint linking components. Actually, for a component, if we assign root value 0, we get a candidate solution; but we can also flip all x in that component (i.e., add 1 to all vertices in component) and the parity on edges remains the same because both endpoints flip, so x_u+x_v unchanged. So each connected component gives one degree of freedom: either we set all bits as determined up to global flip. So the system may have solutions.
Now, given that we need to output a sequence of vertices to toggle (the subset S = {v: x_v = 1}) of length at most n. The length will be exactly the number of ones in x. That's ≤ n. So if solution exists, we can output any solution vector x (any assignment satisfying equations). But the problem also says we need to output a sequence of cities (order) of length x (number of days). So we just output the vertices where x_v = 1, in any order. But careful: The sequence length is exactly the number of days, which is number of operations. In our model, we toggled each vertex exactly once if x_v=1. But could we have a solution where some vertex toggled an odd number of times more than once? That would be same as toggling once. So the minimal number of toggles is the Hamming weight of some solution. But we are not required to be minimal; any sequence length up to n. So we can just output a solution x with weight ≤ n, which is fine.
However, there is a nuance: The system may have multiple solutions; but do we need to ensure that the number of toggles (i.e., number of 1's) is ≤ n? It's automatically ≤ n. So if a solution exists, we can output it. The problem asks to output exactly x numbers, where x is the number of days needed. So we need to output the length and then the sequence. So we can compute x as the number of vertices with x_v=1.
But wait: The problem statement says: "determines whether you can in some way asphalt Berlandian roads in at most n days." So they require at most n days. That's why we need ≤ n. Since any solution using each vertex at most once already has ≤ n days. But if we need to output a solution that uses some vertices more than once, we could compress. So all good.
Thus the main task reduces to solving the system x_u XOR x_v = r_e for each edge. And output any satisfying assignment.
Edge case: What about isolated vertices? They have no edges, so no constraints; they can be either 0 or 1. However, we need to asphalt all roads; isolated vertices don't affect anything, so any assignment for them is fine. Since we want to output a sequence of vertices to toggle, we could leave them untoggled (x=0) to minimize length. But we can also choose any. So we can set them to 0.
But careful: The operation toggles edges incident to the city. If a city is isolated, toggling it does nothing; but we could still toggle it, but we don't need to. So we set x=0 for them.
Now, complexity: n, m up to maybe 10^5? Need O(n+m).
So algorithm:
Read n, m.
Build adjacency list with edges and r_e = 1 - c_i (mod 2). For each edge, store neighbor and parity.
For each connected component:
Do a BFS/DFS starting from any node.
Assign value x[root] = 0 (or arbitrary).
For each edge (u,v) with parity r, when visiting v from u, set x[v] = x[u] XOR r.
If v already visited, check consistency: x[v] should equal x[u] XOR r. If not, impossible.
If all components consistent, we have a solution vector x (bits 0/1). But note: For each component, we have two possible assignments: the one we got with root=0, and its complement (flip all bits). Both satisfy equations because flipping all bits in component adds 1 to each x, so x_u+x_v unchanged mod 2. So we have freedom. We can choose whichever yields lower number of toggles? Not necessary; any is fine. But maybe we need to ensure that the number of toggles is ≤ n, which both satisfy. So we could just take root=0 assignment.
But is there any reason we might need to use the complement? Possibly if the root=0 assignment yields all zeros? That's fine; no toggles needed? Could it be that all edges already are asphalted initially? Then b_e = 1 for all edges, so r_e = 0. The equations are x_u + x_v = 0, which means x_u = x_v for each edge. So each component all vertices same. With root=0, we get all zeros; that yields no toggles. That's correct: we don't need to do anything. But the problem expects to output 0 days? The output format: first line print a single integer x (0 ≤ x ≤ n) — the number of days needed. Then second line print x space-separated integers — the indexes of the cities. For x=0, presumably we don't print a second line? In examples, no such case but typical Codeforces output for 0 days: they'd print 0 and maybe an empty line? The statement says: In the second line print x space-separated integers — the indexes... So if x=0, the second line would be empty? Usually they still print a newline after the first line, and maybe a blank second line. But we can handle by printing "0\n" and then just newline? To be safe, we can print "0\n" and maybe nothing else. Usually in Codeforces problems, if x=0, you print just the first line with 0, and that's it; but statement says "In the second line print x space-separated integers". If x=0, then there are zero integers, so the second line is empty. Possibly they expect to print a blank line or just not print. To avoid presentation error, we can print "0" and then a newline and then maybe nothing else, but that would be two newlines? Actually printing "0\n" is just one line. But they want two lines? If x=0, the second line should be there but empty. Many solutions print "0" and then just end. I'll check typical CF output: Usually they say: "If there are multiple solutions, print any of them." For zero days, they'd output "0" and maybe that's it. However, I recall some problems where they require a second line even if empty, but they often say "if x>0 then print second line". Not here. I'd output "0\n" and not print an extra line. But to be safe, we can output "0\n" and then nothing else, or output "0\n\n". Usually Codeforces judges accept either as long as there is no extra spaces. Since they say "In the second line print x space-separated integers", if x=0, printing nothing (i.e., just a newline after the first line) is effectively printing an empty second line. But if we only print "0\n", that's one line; the newline ends the first line, but there is no second line. However, the output is considered as lines: after printing "0\n", we have one line. The judge expects two lines? Possibly they expect two lines, with second line possibly empty. But if they read using typical input methods, they might read the first integer and then try to read the next line; if it doesn't exist, they might error. So better to output an empty second line. The typical approach: print "0\n" (line1) then if x==0, maybe print nothing else? Many solutions output "0\n" only and get accepted. Let's check: I've seen problems like this; they often output "0" and then exit. But I'm not certain. To avoid risk, I'll output an extra newline after the first line if x==0? Actually printing "0\n" yields one line. If we want two lines, we need "0\n\n". That's two newlines: first line empty? Let's reason: The first line content is "0". After that \n, line1 ends. Then another \n gives an empty line as line2. That's two lines total. So that would satisfy "second line" (even if empty). So I'll output "0\n\n". However, some judges might treat trailing empty lines as ignored? But often they don't mind. I'd rather follow accepted solutions: many people output "0" alone. Let's search memory: There is a known Codeforces problem: "Berland roads" or something? I recall a problem "King's Path?" Not sure. I'd adopt the safe approach: if x==0, print "0" and then end the program. Usually the checker uses reading like: read integer x; then if x>0, read list of ints; else ignore. So reading after that would just see EOF, but it's fine. So I'll just print "0\n".
Ok.
Now the main challenge: The system might have multiple components; each component yields two possibilities. But we also have the requirement that total number of toggles <= n, which is always true. However, we could also try to minimize the number of toggles? Not required. So any assignment works.
But we should be careful: The assignment derived from BFS with root=0 may not always be valid because of the consistency check. If consistent, it's a solution.
But is there any case where there is a solution but root=0 assignment fails? No, because if the system is consistent, any propagation from a root with arbitrary value yields a consistent assignment. If we set root=0, we get one particular assignment; that assignment must satisfy all equations because we verified consistency when encountering visited nodes. So it's a solution.
Thus algorithm is straightforward.
But wait: The problem statement: "The King of Berland Valera II wants to asphalt all roads of Berland, for that he gathered a group of workers. Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. ... they toggle ... Help the king." So we need to output the cities in order. Order doesn't matter because toggles are commutative (since XOR). So any order is fine.
Thus solution: If impossible, print "Impossible". Else, compute x bits and output.
Graph is connected. Do BFS from 1: set x1=0. Then from edge (1,2) with r=0 → x2 = x1 XOR 0 = 0. From (2,4) with r=1 → x4 = x2 XOR 1 = 1. From (4,3) with r=0 → x3 = x4 XOR 0 = 1. Check consistency: (3,2): x3+x2 = 1+0=1, should be 1, OK. So x = [0,0,1,1]. Toggle vertices 3 and 4? Actually x3=1, x4=1. But the output example shows days=4, sequence 3 2 1 3. That's length 4, not 2. So they output a longer sequence, not minimal toggles. So our solution would output a different sequence (maybe 2 toggles) which is also valid because it uses ≤ n days? n=4, 2 ≤ 4, so should be acceptable. But does our solution actually work? Let's simulate: initial states: 1-2:1, 2-4:0, 4-3:1, 3-2:0. If we toggle vertices 3 and 4 (order e.g., 3,4). Toggle 3: edges 4-3 (1->0), 3-2 (0->1). After toggling 3: edges: 1-2:1, 2-4:0, 4-3:0, 3-2:1. Then toggle 4: edges incident to 4: 2-4 (0->1), 4-3 (0->1). After: 1-2:1, 2-4:1, 4-3:1, 3-2:1. All 1. So yes. So our solution (2 days) would be valid and at most 4 days. But the example output is 4 days. So any solution with ≤ n days is acceptable. So our algorithm would output something different, but that's allowed per problem statement. So our solution is correct.
Thus we can implement.
But caution: There is nuance: The sequence length must be at most n. Our solution's length (number of 1's) is at most n. However, could it be that the number of 1's exceeds n? No, because each vertex can be toggled at most once in our model, and there are n vertices, so at most n. So fine.
Now consider possibility of no solution: Example2:
3 3
1-2 0
2-3 0
3-1 0
So all initial states 0, we want all 1. r_e = 1 for all edges. Equations: x1+x2=1, x2+x3=1, x3+x1=1. Sum all three: 2(x1+x2+x3)=1+1+1=3 mod2 = 1, but left side 0 mod2 → inconsistency. So impossible. Output "Impossible". That matches.
Thus solution is simple.
But wait, is there any nuance regarding multiple edges? The problem says there is at most one road between any two cities. So simple graph.
Now implementation details: We'll store adjacency list: for each edge, we need neighbor and parity r = 1 - c. We can store as (neighbor, r). We'll use vector of vectors.
We'll also maintain array x of int (-1 for unvisited, else 0/1). Then for each component, do BFS/DFS.
Pseudo:
int n,m;
cin>>n>>m;
vector<vector<pair<int,int>>> adj(n+1); // (to, r)
for i=1..m:
int a,b,c;
cin>>a>>b>>c;
int r = 1 - c; // because we want final=1, so need parity r.
adj[a].push_back({b,r});
adj[b].push_back({a,r});
But wait: There is a subtle point: The parity r = 1 - c? Let's double-check equation: final state f_e = c_e XOR x_u XOR x_v? Actually toggling edges incident to v means flipping each edge's state. If we apply toggles set S (characteristic vector x where x_v=1 means we toggle v), then for edge (u,v), the number of times it's toggled is x_u + x_v (mod 2) because each endpoint toggles it. So final state = initial_state XOR (x_u XOR x_v?) Since addition mod2 is XOR. So final = c_e XOR (x_u XOR x_v). We want final = 1. So c_e XOR (x_u XOR x_v) = 1 => x_u XOR x_v = 1 XOR c_e. So r_e = 1 XOR c_e. That is exactly 1 - c_e mod 2 if c_e is 0/1. So correct: r_e = 1 XOR c_e.
Thus r_e = 1 - c_e (since subtraction mod2 same as XOR). So fine.
Now consider if there is a solution but the BFS assignment yields some vertices set to 1? Fine.
But what about components that are isolated? In loop for i=1..n, if x[i]==-1 and adj[i] empty, we can set x[i]=0 (or 1) arbitrarily. In our code, we treat them as separate components: we will still go into the BFS loop, set x[i]=0, but since no adjacency, queue is empty, we just set it to 0. That's fine.
Now about the requirement "at most n days". If ans.size() is 0, output 0. That's ≤ n. If ans.size() is n, also ≤ n.
Thus solution appears trivial. But is it always possible to have solution with at most n days if the system is solvable? Yes because we can choose solution vector of size ≤ n.
But is there any scenario where we need to use more than n operations because we need to toggle some vertex more than once? No, because toggling twice cancels, so any optimal parity solution uses each vertex at most once. So minimum number of toggles ≤ n. So at most n days is always satisfied by any parity solution.
Thus the problem reduces to checking if the graph can be 2-colored with given edge parity constraints.
But wait, is there any twist? The problem says "in at most n days". Could there be a scenario where the system has a solution but only with a sequence longer than n? That would be impossible because we can compress any sequence to parity. Suppose we have a sequence of length L > n. Since each vertex toggles each day, we can group toggles per vertex mod 2. The parity of number of times each vertex appears is what matters. So we can reduce to a set S of vertices toggled odd number of times, and the length of the reduced sequence is |S| (if we order them arbitrarily). Since |S| ≤ n, we get a sequence of length ≤ n. So any solution can be transformed to one of length ≤ n (unless the sequence uses a vertex more than twice, but we can cancel pairs). So existence of any solution (of any length) is equivalent to existence of a parity solution with size ≤ n. So indeed we just need to check the parity constraints.
Therefore the problem is simply solving the linear system.
But hold on: There might be a catch: The operation toggles all roads coming from the city, but if we apply multiple operations, the order matters? Since toggling is commutative and associative (XOR), order doesn't affect final state. So no.
Thus solution is straightforward.
But before concluding, let's double-check with some tricky cases: Graph with multiple components. Suppose component has a solution where all x are forced (i.e., no degree of freedom) because constraints force a unique assignment. BFS with root=0 will yield that assignment if consistent; but if root=0 leads to inconsistency? Actually if the constraints are consistent, any choice of root yields a consistent assignment. If we set root=0 and propagate, we get an assignment; if we set root=1, we get the complement. So both are consistent. So BFS with root=0 works if system consistent.
But what if the graph has odd cycle constraints that force all x to be something? For a tree, root=0 yields unique assignment; that assignment satisfies because equations are linear and tree has no cycles to check consistency, but we must also check any extra edges (non-tree) for consistency. BFS will check those as we go; if any back edge conflicts, we flag impossible.
So algorithm correct.
Now, about output format: In the example, they output "4\n3 2 1 3\n". That's length 4, includes repetition. Our output would be different but acceptable. However, we need to ensure that we output the vertices indices in the order we send workers. Since order doesn't matter, we can output the vertices where x_v=1 in any order, maybe ascending.
One potential nuance: The problem states "in at most n days". Our sequence length is the number of vertices with x=1. Could it be that this number is 0? Yes, if initial already all asphalted. Then we output 0 and maybe nothing else. That should be acceptable.
Now, consider the possibility that the graph is disconnected and we have free choice for each component. Could it be that picking root=0 yields many ones, but we could choose complements to reduce total ones? That might be desirable to keep length small, but not necessary. But there is no restriction on length except ≤ n. So it's fine.
Thus answer.
But wait: The problem title might be from Codeforces Round? I recall a problem "Asphalting Roads" maybe? Let's think: There is a known problem: "Berland Roads" where you have to toggle edges. Actually I remember a problem "King's Path?" Not sure. However, I'm concerned that there might be a twist: The crew toggles all roads from the city, but if a road is asphalted initially, they take the asphalt away. So after toggling, that road becomes un-asphalted. So final goal is all asphalted. Yes.
But what about the constraint "at most n days"? Could there be a scenario where the parity solution exists but requires toggling all n vertices, which is fine, but maybe we could also output a shorter sequence. That's fine.
Thus solution seems trivial, but why would the example output a longer sequence? Possibly they wanted to demonstrate that repetitions are allowed, but any solution is accepted.
Now, before finalizing, I want to verify with some random tests. Let's brute force small n to confirm.
But also, is there any chance that the system is overdetermined but still solvable? Yes.
Now, think about a graph with multiple components: For each component, there are two solutions. So if there are k components, there are 2^k solutions. Our BFS with root=0 for each component gives one particular solution.
Now, what about isolated vertices? They are components of size 1, with no edges. Both assignments work. We set to 0.
All good.
Now, what about graph with no edges? m=0. Then there are no roads to asphalt, so vacuously all roads are asphalted? Actually if there are no roads, then condition "asphalt all roads" is trivially satisfied initially. So we need 0 days. Our algorithm: x[i] all set to 0 (since each vertex visited, set to 0). ans.size()=0, output 0. That's correct.
Edge case: n=1, m=0: output 0.
If n=1, but there could be a self-loop? Not allowed because ai ≠ bi, so no self-loop.
Thus fine.
Now, implementation details: We need to be careful with large input, use fast I/O.
Now, are there any pitfalls? The parity r = 1 - c. But note: c is 0 or 1. So r = 1 XOR c, which is same as 1-c. So using ^ operator.
Now, maybe we need to consider the possibility of multiple edges? Not allowed.
Thus solution is ready.
But wait: There's something else: The problem statement: "Every day Valera chooses exactly one city and orders the crew to asphalt all roads that come from the city. The valiant crew fulfilled the King's order in a day, then workers went home." So they do one operation per day. So our sequence length is the number of days. So we output the cities in the order they are chosen. That's fine.
Now, think about the requirement "in at most n days". Could it be that we are required to use exactly at most n days, but our solution might use 0 days if no roads? That's ≤ n, so okay.
Thus algorithm is correct.
Now, before concluding, I want to double-check the reasoning about the system: x_u XOR x_v = 1 XOR c_e. That's derived from final = c_e XOR (x_u XOR x_v) = 1 => x_u XOR x_v = 1 XOR c_e. So yes.
Let's test on example1: c for (1,2)=1 => r=0, (2,4)=0 => r=1, (4,3)=1 => r=0, (3,2)=0 => r=1. So x1=0 => x2=0, x4=1, x3=1. So toggles set = {3,4}. That works as we simulated.
Now test on example1 output: they toggled 3,2,1,3. That's toggling 3 twice (cancels), 2 once, 1 once. So net toggles: 2,1,3? Actually 3 toggled twice -> net 0, 2 once, 1 once. So net set = {1,2}. Let's test that: initial states; toggling 1,2 (order whatever). After toggling 1: flips edges (1,2):1->0. After toggling 2: flips edges (1,2):0->1, (2,4):0->1, (3,2):0->1. After toggling? Wait they also toggled 3 twice, but those cancel. So final: (1,2)=1, (2,4)=1, (3,2)=1, (4,3) unchanged (1). So all 1. So net set {1,2} works. Check equations: x1=1, x2=1, x3=0, x4=0. Then x1+x2=0? Actually 1 XOR 1 =0, but required r=0 for (1,2) -> ok. x2+x4=1 XOR 0 =1, required 1 -> ok. x4+x3=0 XOR 0 =0, required 0 -> ok. x3+x2=0 XOR 1 =1, required 1 -> ok. So that's another solution. So indeed there are multiple solutions. So our solution is fine.
Thus the problem is essentially a graph parity constraints problem.
Now, we should also think about possibility of solution existence but with the requirement that we output a sequence of at most n days; but if our solution uses exactly n days, it's okay. So all good.
Given the simplicity, maybe there is a catch: The problem might be from an Olympiad where they expect some more clever reasoning, but it's fine.
Now, let's consider if there could be any scenario where the system has a solution but we cannot output a sequence because we must output exactly the cities to send workers, and the sequence length must be at most n. That's fine.
But wait: The problem states: "determines whether you can in some way asphalt Berlandian roads in at most n days." It doesn't ask for minimal days, just any way with ≤ n days. So we can output any valid set of vertices to toggle (size ≤ n). So our solution qualifies.
Now, I'm thinking: Is there any scenario where the only valid sequences have length > n? That would be if every solution in terms of parity uses more than n toggles? But parity solution is a set of vertices (since each vertex appears at most once). The size of that set can be at most n. So no.
Thus the solution is straightforward.
Now, consider if the graph is not connected, we can choose independently per component. Our BFS sets each component root=0, so we get some assignment. That assignment might have many ones. But it's okay.
Potential issue: For a component, the BFS might fail because of inconsistency, but if the system is consistent overall, it won't.
Now, I'll think about implementation in C++.
We'll use:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> g(n+1);
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
int r = 1 - c;
g[a].emplace_back(b, r);
g[b].emplace_back(a, r);
}
vector<int> x(n+1, -1);
bool ok = true;
for (int i = 1; i <= n; ++i) {
if (x[i] == -1) {
// BFS/DFS
x[i] = 0;
queue<int> q;
q.push(i);
while (!q.empty() && ok) {
int u = q.front(); q.pop();
for (auto [v, r] : g[u]) {
if (x[v] == -1) {
x[v] = x[u] ^ r;
q.push(v);
} else if ((x[u] ^ r) != x[v]) {
ok = false;
break;
}
}
}
}
}
if (!ok) {
cout << "Impossible\n";
} else {
vector<int> ans;
for (int i = 1; i <= n; ++i) {
if (x[i] == 1) ans.push_back(i);
}
cout << ans.size() << '\n';
if (!ans.empty()) {
for (int i = 0; i < (int)ans.size(); ++i) {
if (i) cout << ' ';
cout << ans[i];
}
cout << '\n';
}
}
return 0;
}
Now, complexity O(n+m). Works.
But before finalizing, let's think about potential integer overflow? No.
Now, could there be a tricky case where the graph has multiple components and we set root=0, but that leads to an assignment where some isolated vertex set to 0? That's fine.
Now, what about the case where we have n=0? Not possible because n ≥ 1? The problem doesn't specify lower bound, but n is number of cities, so at least 1.
Now, also note that there might be a possibility that we need to output the sequence of cities such that the number of days is exactly x, and x ≤ n. If we output 0, we should not output a second line. In many Codeforces problems, they require to print nothing for second line if x=0. I'll check example: They didn't provide an example with 0. To be safe, I'll follow typical pattern: print "0\n" and then no second line. I think that's acceptable. In the problem statement: "In the first line print a single integer x ... In the second line print x space-separated integers — the indexes of the cities to send the workers to." So if x=0, the second line would contain 0 integers, i.e., an empty line. Usually they expect a blank line or nothing. Some judges parse by reading line by line; if we output only one line, they might try to read the next line and fail. However, many solutions for similar problems output just "0\n" and get accepted. I can recall Codeforces problem "Xor Tree" etc. I'll try to search memory: There is problem "Road Improvement" maybe? Not sure.
To avoid any issue, I'll output an empty line after the 0. That is, cout << "0\n\n"; But then there will be two newlines, second empty. This could be interpreted as an extra blank line, but it's still a line (empty). That should be fine. However, some judges might consider that an extra line is acceptable as long as it's empty. But sometimes they compare output exactly; if expected output has exactly one line "0", then "0\n\n" would be two lines, which might cause WA. In many Codeforces problems, the checker compares output token by token or line by line ignoring extra whitespace? Typically, they compare as sequences of tokens, ignoring extra whitespace? Actually Codeforces uses strict comparison? Usually they compare exactly, but they ignore trailing spaces and empty lines? Not sure. In many problems, they say "If there are multiple solutions, print any of them." So the output format is not rigid except for the numbers. Usually they read the first integer, then read that many numbers from the next line(s). If x=0, they might not read anything else. So an extra blank line might cause a read error if they use line-based parsing? But the checker is not parsing; it's comparing output to expected. The expected output for x=0 might be just "0" (no newline after?) Actually standard output always ends with newline. So "0\n" is typical. If they expect "0\n", and we output "0\n\n", that's an extra newline, so it's different. But could it be accepted? I doubt it; they usually require exact match except perhaps for spaces at end of lines? Typically, Codeforces checks exactly, but allows trailing spaces? Usually they trim trailing spaces but not blank lines? I'm not fully sure.
Let's recall typical solution in Codeforces for problems where output x and then list: if x>0, print list; else just print x. Many participants print:
That prints a newline after the first line always, and if ans.size()>0 prints a second line. If ans.size()==0, it prints only the first line (with endl). That's "0\n". No extra blank line. I've seen that accepted many times. So I'll do that.
Thus code as above is fine.
Now, one more nuance: We need to ensure we don't have a memory issue: n up to maybe 2e5, m up to 2e5. Adj list works.
Now, are we absolutely sure that the system is correct? Let's derive more formally:
Let initial state for edge e be s_e (0 or 1). After toggling vertices according to vector x (where x_v = 1 if toggled odd times), final state f_e = s_e ⊕ (x_u ⊕ x_v). Requirement f_e = 1 => x_u ⊕ x_v = 1 ⊕ s_e.
So that's the equation.
Now, if graph is not connected, each component can have independent parity for flipping all vertices? Actually if we flip all vertices in a component (add 1 to each x in that component), then for any edge inside component, both endpoints flip, so x_u ⊕ x_v unchanged. For edges between components? There are none because graph is partitioned. So flipping all bits in a component yields another solution. So indeed each component gives a binary degree of freedom.
Thus BFS with root=0 gives one solution; we could also flip components to reduce total toggles. But not necessary.
Now, what if graph has isolated vertices? They are components of size 1, flipping them changes nothing? Actually flipping an isolated vertex toggles no edges, so it doesn't affect final state; thus any assignment works. So they can be 0 or 1 arbitrarily. So BFS sets them to 0.
Thus algorithm correct.
Now, check a tricky case: Graph with a single edge (1-2) with c=1 (asphalted). Then r=0. Equation: x1 XOR x2 = 0 => x1 = x2. Both 0 or both 1 works. Our BFS: start at 1, x1=0, then edge to 2 gives x2 = 0. So set = {}. That's 0 toggles, final state = 1 already? initial c=1, so final =1, yes. So output 0. Another solution: both 1 would require toggling both vertices, which also works: toggling both flips edge twice, so remains 1. But 0 is fine.
Now, consider edge c=0. Then r=1: x1 XOR x2 = 1. BFS from 1 with x1=0 gives x2=1. So toggles {2}. That works. Alternative: x1=1, x2=0 yields toggles {1}. So either works.
Now, consider a triangle all c=0: earlier impossible. BFS from 1: x1=0, edge (1,2) r=1 => x2=1; edge (1,3) r=1 => x3=1; now check edge (2,3): x2 XOR x3 = 0, but r=1 => conflict -> impossible.
Now, consider a square (cycle of 4) with alternating? Example: 1-2 c=0, 2-3 c=0, 3-4 c=0, 4-1 c=0. All r=1. Equations: x1⊕x2=1, x2⊕x3=1, x3⊕x4=1, x4⊕x1=1. Summing all: 2(x1+x2+x3+x4)=0=4 mod2? Actually left 0, right 1+1+1+1=0 mod2, so consistent? 1+1+1+1=0 mod2, so it may be consistent. Let's solve: from first: x2 = x1⊕1. second: x3 = x2⊕1 = x1⊕1⊕1 = x1. third: x4 = x3⊕1 = x1⊕1. fourth: x1 = x4⊕1 = x1⊕1⊕1 = x1. So consistent. So solution exists. BFS from 1: x1=0 => x2=1, x3=0, x4=1. Toggles {2,4}. Works.
Now, check that total toggles =2 ≤ 4, ok.
Now, consider graph with isolated vertices and edges. Works.
Thus algorithm seems correct.
Now, I'm going to write the solution.
But wait: The problem statement: "n, m — the number of cities and roads in Berland, correspondingly." They used notation "n, m " which is probably "n, m (1 ≤ n, m ≤ 10^5)"? The image likely denotes constraints. But not shown in text. Typically constraints could be up to 2e5. So we must handle large.
Now, think about recursion depth if using DFS; we'll use BFS to avoid stack overflow.
Now, we should also note that if the graph is disconnected and we have large components, BFS works.
Now, one more nuance: In the BFS, we set x[i]=0 for the root. But what if the root has no edges? That's fine.
Now, we need to handle the case where the BFS finds inconsistency. At that point, we can break loops and output "Impossible".
Now, regarding output: print "Impossible" exactly as per statement.
Now, test with sample:
Input1:
4 4
1 2 1
2 4 0
4 3 1
3 2 0
Our program: compute r as described. BFS from 1? Actually we iterate i=1..n, i=1 visited? Initially x[1]==-1, so start BFS from 1, set x1=0. Then process adjacency: for (2,0) => x2=0; push 2. Then process 2: edges: (1,0) already visited check consistency: x1=0, r=0 => 0^0=0 matches x2=0 okay; (4,1): x4 unvisited => x4=0^1=1; push 4; (3,1): from 2? Actually edge (3,2) with r=1: check neighbor 3 unvisited => x3 = 0^1=1; push 3. Then process 4: edges: (2,1): visited x2=0, check: x4=1, r=1, 1^1? Actually check: (x4 ^ r) should equal x2? Wait condition: when processing u, for each edge (v,r), we check if v visited: then we need x[u] ^ r == x[v]. For u=4, edge (2,1): x4=1, r=1 => 1^1=0 matches x2=0. Good. Edge (3,0): x3 visited? x3=1, need 1^0=1 matches x3=1. Good. Then process 3: edges: (4,0): check x4=1, 1^0=1 matches x3=1; (2,1): check x2=0, 1^1=0 matches. So consistent. So ans = {i | x[i]=1} = {3,4}. Output "2\n3 4\n". That's valid.
But the sample output was "4\n3 2 1 3\n". So it's different but acceptable. However, the problem might expect any solution; so our output is correct.
But wait: Could there be a scenario where our solution uses exactly n days? That's fine.
Now, is there any scenario where solution exists but BFS root=0 yields an assignment that toggles all vertices? Possibly if the system forces all x=1? For a graph where each edge requires x_u XOR x_v = 0 (i.e., all vertices same) and the root=0 yields all 0; but if we choose root=0, we get all 0, not all 1. So that doesn't yield all 1. So if the system forces all x=1? That's impossible because if all edges require 0 parity, then x can be all 0 or all 1. So both are solutions. So BFS root=0 yields all 0, not all 1. That's a solution. So not all 1.
Now, think about case where the system forces a specific pattern that is not all zeros. BFS root=0 yields that pattern.
Now, consider if the graph has multiple components, and we set root=0, we might get many ones. That's okay.
Thus the solution is correct.
Now, I'd like to test some random cases with brute force for small n to ensure no mistake.
I'll write a small brute-force solver for n up to 7, enumerate all subsets of vertices to toggle (2^n possibilities), simulate toggling, check if final all 1. Compare with our linear algebra solution. Should match.
I could do mental but perhaps trust.
But there is one subtlety: The operation toggles all roads incident to the city. If we apply multiple toggles, order doesn't matter. So subset model works.
Thus answer is correct.
Now, we must also consider that the graph might have multiple edges? The problem says "not more than one road", so simple.
Now, also consider possibility of multiple connected components with odd cycle constraints causing inconsistency? Already covered.
Now, the only possible pitfall: We treat the XOR operation: x[u] ^ r. But note that r = 1 - c. Since c is int, r = c ^ 1? Actually 1 - c works mod2, but careful: if c=0, 1-0=1; if c=1, 1-1=0. So fine.
Now, what about large n and m? Use vector and BFS.
Now, check memory: adjacency list storing pairs for each edge twice, so 2*m entries, each with int and int, okay.
Now, I'd like to confirm that we haven't missed the fact that we can choose up to n days, not exactly n days. So 0 days is allowed.
Now, what if solution exists but we have isolated vertices that we set to 0, which is fine.
Now, could there be a case where solution exists but all assignments require toggling at least one vertex from each component? Not a problem.
Now, implement.
But wait, there is another nuance: The operation is performed each day, and after each day, the crew toggles all edges incident. Our model of toggling a set S simultaneously is equivalent to doing them sequentially in any order because XOR is commutative and associative. So fine.
Now, check with sample Input1: Our output would be "2\n3 4\n" (or "2\n4 3\n" depending on order). That is a valid solution, but the sample output is different. So judges should accept any valid output.
Now, I'm thinking: The problem might be from some contest where they want to output any sequence length at most n, but maybe they require the sequence to be exactly the cities you send workers, and they may require that you don't repeat cities? Not stated; they can repeat. In our solution we don't repeat, but that's fine.
Thus final answer.
But before finalizing, I'll double-check the interpretation of r: Some might think r = c? Let's re-derive to be absolutely sure.
Define initial state s_e (0=not asphalted, 1=asphalted). Operation on vertex v toggles all edges incident to v. So after applying toggles at vertices in set S (each once), the state of edge e=(u,v) becomes s_e XOR [v in S?] Actually toggled if either endpoint in S. So toggled = (indicator of u in S) XOR (indicator of v in S) because if both, toggled twice = no change? Wait careful: If we toggle both endpoints, each toggling flips the edge. So first toggle flips, second toggle flips again, net no change. So the net effect is XOR of the two indicators: If exactly one of u,v is toggled, the edge flips; if both or none, it stays same. So net change = x_u XOR x_v. Thus final = s_e XOR (x_u XOR x_v). Set to 1 => s_e XOR (x_u XOR x_v) = 1 => x_u XOR x_v = 1 XOR s_e. So r = 1 XOR s_e. Good.
Thus r = 1 - s_e mod 2.
Now, what about edges that are initially asphalted (s_e=1)? We want final=1, so we need no net toggle (since 1 XOR 0 = 1) or toggle twice (both endpoints) to keep it 1? Actually to keep it 1, we need x_u XOR x_v = 0. So constraint: x_u = x_v. That matches.
Now, for s_e=0, need x_u XOR x_v = 1.
Thus equation.
So our BFS sets x_v = x_u XOR r.
Now, confirm with sample: s(1,2)=1, r=0 -> constraint x1=x2. Our BFS gave x1=0, x2=0, good.
Now, I'd like to test with a scenario where the graph is a tree with an odd number of edges needing parity 1? Actually for a tree, there is always a solution, because we can assign from root arbitrarily and propagate; no cycle to cause inconsistency. So any tree is solvable? Let's check: For a tree, we can always satisfy the equations? For each edge we set x_v = x_u XOR r. This assignment is consistent because no back edges. So always possible. So for any tree, there is always a solution. Indeed, because a tree is bipartite and no cycles, so any parity constraints can be satisfied. Let's test: A tree of two vertices: edge s=0 -> need x1 XOR x2=1, can choose x1=0,x2=1; works. Edge s=1 -> need x1=x2, can choose both 0; works. So yes, any tree works. That's interesting; but the problem might have cases where tree is impossible? No, it's always solvable. Let's test with three vertices in a path: 1-2 s=0 (r=1), 2-3 s=0 (r=1). Then from root 1=0, x2=1, x3=0. Check: x1 XOR x2 =1 ok, x2 XOR x3=1 ok. So works. So any forest is solvable because each component is a tree? Actually forest may contain isolated vertices; still solvable. So only cycles can cause inconsistency. So the only impossible cases are when there is a cycle with odd sum of r? Actually sum of r over cycle must be 0 mod2. If not, impossible.
Thus the problem essentially: check for each component if the XOR sum of r over any cycle is 0; equivalently, whether the parity constraints are consistent.
Now, is it possible that a graph with cycles still always solvable? Only if all cycles have even parity sum. That's the condition.
Now, we can also think of it as: we want to assign x such that for each edge, x_u + x_v ≡ r (mod 2). This is a system of linear equations over GF(2). The condition for solvability is that for any cycle, sum of r over edges in cycle is 0 mod2. That's what BFS will detect.
Thus algorithm stands.
Now, let's also consider potential performance: BFS with queue.
Now, I'll implement.
But one more nuance: The input may have m=0, n large. Our BFS will loop over all vertices, set x[i]=0 for each isolated vertex (since each isolated vertex is its own component). That's fine.
Now, regarding output: The answer list may be empty; we print only the first line. That's fine.
Now, should we include a newline after the first line? Yes.
Now, everything seems fine.
However, I recall that there is a known Codeforces problem "Roads in Berland" or something, but that one is about shortest paths. This problem seems to be from some contest.
Now, one more thought: Could it be that the problem expects you to output the sequence of operations, not just the set, and that sequence might need to be at most n days, but the set approach yields exactly the number of ones. But if that number is > n? Impossible. So fine.
Now, I'll produce final solution.
But before finalizing, let's test with some random small graphs using brute force to be 100% confident.
I'll simulate with n=3 all possible graphs and initial states.
But let's reason: For n=3, possible edges: 1-2, 2-3, 1-3. There are 2^3 possible initial state assignments. For each, we can compute if solution exists via BFS condition.
Let's enumerate:
Case: all edges present. We'll denote s12, s23, s13.
Summing all three: (x1⊕x2)⊕(x2⊕x3)⊕(x3⊕x1) = 0 = (1⊕s12)⊕(1⊕s23)⊕(1⊕s13) = (1⊕1⊕1) ⊕ (s12⊕s23⊕s13) = (1) ⊕ (s12⊕s23⊕s13) because 1⊕1⊕1 = 1 (since odd number of 1's). So condition: 1 ⊕ (s12⊕s23⊕s13) = 0 => s12⊕s23⊕s13 = 1. So a triangle is solvable iff the XOR of the three initial states is 1. That matches known: If all three are 0, XOR=0 -> impossible; if two 1's and one 0, XOR=0? Actually 1⊕1⊕0=0, so impossible? Wait 1⊕1⊕0=0 -> impossible; if one 1 and two 0, XOR=1 -> solvable; if three 1, XOR=1? 1⊕1⊕1=1 -> solvable. So indeed all three 1 works? Let's test manually: s12=1,s23=1,s13=1. Want final all 1. Initially all asphalted, so no toggles needed: x all 0 works. So solvable. Our condition gives XOR=1, so solvable. Good. For two 1's and one 0, e.g., s12=1,s23=1,s13=0. XOR=0, condition says impossible. Check manually: need toggles such that edges become 1. If we toggle some vertices, can we achieve? Let's try: initial: 1-2:1, 2-3:1, 1-3:0. We need to make all 1. Suppose we toggle set S. For edge (1,3) initially 0, need x1⊕x3=1. For (1,2) initially 1, need x1⊕x2=0. For (2,3) initially 1, need x2⊕x3=0. From x1⊕x2=0 => x2=x1. From x2⊕x3=0 => x3=x2=x1. Then x1⊕x3=0, but need 1 -> contradiction. So impossible. So condition correct.
Now, our BFS would detect inconsistency.
Now, test a graph with a cycle of length 4: earlier we had all s=0, so r all 1. Sum over cycle: 1+1+1+1=0 mod2 -> consistent. So solvable. BFS would give a solution.
Now, test a graph with a cycle of length 4 but with r sum 1? e.g., edges: 1-2 r=1, 2-3 r=1, 3-4 r=1, 4-1 r=0. Then sum=1+1+1+0=1 mod2 -> inconsistent. BFS would detect when encountering back edge.
Thus algorithm passes.
Now, we must also ensure we handle multiple components: The BFS loop iterates over all vertices, and for each unvisited, we start BFS. That ensures we set x for all vertices. For a component that is a tree, we will not encounter any visited neighbor that causes inconsistency (except maybe when we encounter an edge to an already visited vertex that is not the parent). In a tree, there are no such edges; but if the graph has cycles, there will be back edges. When we process such an edge, we check consistency. That works.
Now, one nuance: In BFS, when we go from u to v, we might have visited v earlier. The condition (x[u] ^ r) == x[v] ensures consistency. But what about the case when the edge is the one we just came from (i.e., parent)? That v is visited but it's the node we came from. The condition should hold because we set x[v] from that edge originally? Actually when we first discovered v from u, we set x[v] = x[u] ^ r. So later when processing v and examining edge back to u, we will check (x[v] ^ r) == x[u]. Since x[v] = x[u] ^ r, then x[v] ^ r = x[u] ^ r ^ r = x[u]. So condition holds. So no false positive.
Thus BFS works.
Now, final answer: implementation in C++.
But before finalize, I'll think if there is any alternate interpretation: Maybe the crew "asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it." That is exactly toggling. So correct.
Now, the problem says "determines whether you can in some way asphalt Berlandian roads in at most n days." Could it be that we are allowed to choose a city each day, but the crew toggles only the roads that are currently not asphalted? Wait, the phrasing: "asphalted all non-asphalted roads coming from the city, and vice versa, took the asphalt from the roads that had it." That means they toggle each incident road: if it's not asphalted, they asphalt it; if it is asphalted, they remove asphalt. So yes.
Now, is there any restriction that they can only asphalt roads that are currently not asphalted? No, they do both actions.
Thus fine.
Now, consider the possibility of the crew affecting roads that are already processed? No, it's just toggling.
Thus final.
Now, I'll produce final solution.
But I'm thinking: The problem might be from Codeforces Round 384 Div2? Possibly problem "Asphalting Roads". I'll search memory: I recall a problem "Asphalting Roads" where you have a grid? Not sure. But anyway.
Now, write final answer.
One more test: n=2, m=1, c=1. Our program: x1=0, x2=0, ans empty, output 0. That's correct: no need to do anything.
Now, n=100000, m=0: BFS loops over all vertices, set each to 0, ans empty, output 0. Works quickly.
Now, any potential integer overflow? No.
Thus solution ready.
But there is a nuance: The BFS algorithm uses a queue; for large n with many components, it's okay.
Now, I'll write final answer.
I'll also include reading optimizations: ios_base::sync_with_stdio(false); cin.tie(0).
Now, output.
I think this is the solution.
However, I'm slightly concerned because the problem seems too easy for a typical contest problem. But maybe it's from an easy division.
Alternatively, perhaps there is a twist: The king orders exactly one city per day, and the crew toggles all roads from that city. But if we toggle a city twice, it's like doing nothing. So the effective set is the set of cities toggled odd number of times. That's what we used. So indeed it's a linear algebra problem.
But maybe there is a catch: The roads are bidirectional, and toggling a city flips all incident edges. However, if we toggle two cities that are connected by an edge, that edge gets flipped twice, so it ends up unchanged. That's captured by XOR.
Thus it's correct.
Now, maybe they want to output a sequence of length exactly at most n, but we output exactly the number of toggles. That's fine.
Now, I'd like to run a quick mental test on a more complex graph: Suppose a graph with two components: component A is a tree (always solvable) and component B is an odd cycle with inconsistent parity. Then overall impossible. Our BFS will discover inconsistency in component B and output Impossible. Good.
Now, suppose both components solvable, our BFS will produce some assignment, maybe not optimal but valid.
Thus final.
I'll now produce final solution.
But before final, I'll re-read the problem statement from the user: It says "Berland has n cities, some of them are connected by bidirectional roads. For each road we know whether it is asphalted or not." Then the description. Input format: n, m — number of cities and roads. The image probably shows constraints, but we don't have them. Usually constraints: 1 ≤ n, m ≤ 10^5. But we can handle.
Thus code.
Now, final output: print "Impossible" if not possible.
One more nuance: In the sample output, they printed "4\n3 2 1 3\n". The numbers are separated by spaces, trailing space maybe not allowed but we avoid trailing space.
But the problem may have time limit tight; using BFS O(n+m) fine.
Now, final answer.
Wait, there might be another nuance: The problem says "at most n days". But if we output a solution with 0 days, it's at most n, ok. If we output a solution with exactly n days, also ok.
Now, what about a solution with more than n days? Not needed.
Thus final.
Now, I'll produce final solution.
But I'm thinking: Could there be a scenario where the linear system has a solution, but the only solution requires toggling all n vertices (which is allowed). That's fine.
Now, double-check memory: using vector of vector of pair. For m up to 200k, that's about 400k pairs, each pair two ints, maybe 16 bytes each, total ~6.4 MB, fine.
Now, use 0-index or 1-index? We'll use 1-index for vertices.
Now, code.
Let's implement:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> g(n+1);
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
int r = 1 - c;
g[a].emplace_back(b, r);
g[b].emplace_back(a, r);
}
vector<int> x(n+1, -1);
bool ok = true;
for (int i = 1; i <= n; ++i) {
if (x[i] == -1) {
x[i] = 0;
queue<int> q;
q.push(i);
while (!q.empty() && ok) {
int u = q.front();
q.pop();
for (auto [v, r] : g[u]) {
if (x[v] == -1) {
x[v] = x[u] ^ r;
q.push(v);
} else if ((x[u] ^ r) != x[v]) {
ok = false;
break;
}
}
}
}
}
if (!ok) {
cout << "Impossible\n";
} else {
vector<int> ans;
for (int i = 1; i <= n; ++i) {
if (x[i] == 1) ans.push_back(i);
}
cout << ans.size() << '\n';
if (!ans.empty()) {
for (size_t i = 0; i < ans.size(); ++i) {
if (i) cout << ' ';
cout << ans[i];
}
cout << '\n';
}
}
return 0;
}
Now, is there any chance that the BFS could be stuck in infinite loop? No, because we mark visited when we assign x[v].
Now, consider if the graph is huge and recursion? BFS fine.
Thus final.
Now, the answer to provide: We'll output the code and explanation.
But the user said "You are ChatGPT, ...". They want the solution. So I'll provide explanation and the code.
Now, I'll produce final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m;
cin >> n >> m;
vector<vector<pair<int, int>>> g(n + 1); // neighbour, required parity r
for (int i = 0; i < m; ++i) {
int a, b, c;
cin >> a >> b >> c;
int r = 1 - c; // we need x_u xor x_v = r
g[a].emplace_back(b, r);
g[b].emplace_back(a, r);
}
vector<int> x(n + 1, -1); // -1 = unvisited, 0/1 = chosen parity
bool possible = true;
for (int i = 1; i <= n && possible; ++i) {
if (x[i] == -1) {
// start a new connected component
x[i] = 0;
queue<int> q;
q.push(i);
while (!q.empty() && possible) {
int u = q.front();
q.pop();
for (auto [v, r] : g[u]) {
if (x[v] == -1) {
x[v] = x[u] ^ r;
q.push(v);
} else if ((x[u] ^ r) != x[v]) {
possible = false;
break;
}
}
}
}
}
if (!possible) {
cout << "Impossible\n";
} else {
vector<int> ans;
for (int i = 1; i <= n; ++i) {
if (x[i] == 1) ans.push_back(i);
}
cout << ans.size() << '\n';
if (!ans.empty()) {
for (size_t i = 0; i < ans.size(); ++i) {
if (i) cout << ' ';
cout << ans[i];
}
cout << '\n';
}
}
return 0;