We need to solve the problem: given N propositions (variables) and M implications a_i -> b_i. Determine for each proposition i, the set of propositions j (including i) such that i and j are logically equivalent under the given implications (i.e., i <-> j holds). The equivalence is defined as: i and j have the same value (i.e., are logically equivalent) if both i -> j and j -> i hold given the implications.
But careful: The problem says: "Given in the form 'a_i b_i' which means that a_i is b_i." Actually reading the statement: "The i-th information is 'a_i b_i', which means that a_i is b_i. ("If" is a logical conditional and the transition law holds.) For each proposition i, output all propositions that have the same value as i in ascending order. However, proposition i and proposition i are always the same value. Proposition X and proposition Y have the same value as 'if X then Y' and 'X if Y'." So it's the logical equivalence: X <-> Y holds, i.e., X implies Y and Y implies X.
But we are only given one-direction implications. However, we can infer new implications through transitivity? The problem mentions "transition law holds" meaning that if we have a->b and b->c then we can deduce a->c. So closure under transitive closure. Also, we need equivalence if both directions are deducible.
Thus we have a directed graph on N nodes (propositions) with M directed edges. We need to compute the strongly connected components (SCCs) in the transitive closure sense? Actually, we need to consider the implication closure: i implies j if there exists a directed path from i to j in the graph. Since the graph is not necessarily transitive initially, but we are allowed to use transitivity. So the deducible implication relation is the reachability relation.
Then two propositions are equivalent if i can reach j and j can reach i. That is exactly mutual reachability, i.e., they are in the same strongly connected component (SCC) in the usual graph sense (SCC is maximal set where every node is reachable from every other node). However careful: In directed graphs, SCC is defined as a maximal subset where for every u, v, there is a path from u to v and from v to u. That matches.
Thus we need to compute SCCs, but we also need to consider that not all nodes may have both ways reachable. So equivalence classes are the SCCs.
Then for each node i, output all nodes in its SCC (including i) sorted ascending.
Given N up to? Not specified. Usually N up to maybe 10^5? M up to? We should consider efficient algorithm. Since we need to output up to N lines each listing possibly many nodes. The total output size could be O(N^2) worst-case (if all nodes in one SCC), but if N is large, output can be huge. Usually constraints would ensure total output fits within limits. Let's assume constraints moderate: maybe N ≤ 2000? Or N up to 10^5? The problem is from AtCoder? Possibly "Logical Inference" (but I'm not sure). Actually the format: Input first line: N M, then M lines a_i b_i. Output as described. Could be from AtCoder ABC? Not sure.
Let's search memory: There is AtCoder problem "Logical Operations" maybe? Alternatively, this might be from JOI? Or just a generic problem.
We need to write solution in Python.
We can compute SCCs using Kosaraju or Tarjan. Then for each component, store its members sorted. Then for each node output its component's members in ascending order separated by spaces.
The only nuance: The implications are "a_i is b_i"? Actually "a_i is b_i" might mean "a_i equals b_i"? But the description says "if" is logical conditional, so "a_i is b_i" might be misinterpretation. It says: "the i-th information is 'a_i b_i', which means that a_i is b_i. ("If" is a logical conditional and the transition law holds.)" It might be that they mean "a_i implies b_i". So indeed it's implication.
Thus SCC approach works.
Edge Cases: Nodes with no edges are SCCs of size 1.
Now about complexity: O(N+M) to compute SCCs using Kosaraju (2 DFS) or Tarjan. In Python, need to handle recursion depth if N large; can use iterative DFS or set recursion limit.
Better to use iterative Kosaraju with stack to avoid recursion.
But we can also use networkx? No, we implement.
Plan:
- Read N, M.
- Build adjacency list for graph (forward edges) and reverse adjacency list for reversed graph.
- Perform DFS on original graph to compute finishing order (postorder) using iterative approach to avoid recursion overflow.
- Then process nodes in reverse order of finishing times (largest finish first) to assign components on reverse graph.
- While assigning, each component we collect nodes.
- After we have component id for each node, we group nodes by component id.
- For each component, sort its nodes.
- Then for node i from 1 to N, output its component's sorted list as space-separated.
Note: Node indices are 1-indexed given in input.
Potential pitfalls: The graph might have self-loops? Possibly, but they don't affect.
Now about output: Each line should have all propositions that have same value as i, separated by blanks, in ascending order. So if there are multiple nodes, output them separated by spaces. If a component is size 1, output just that number.
Thus we need to output N lines, each possibly with multiple numbers.
Let's check sample:
Input:
5 2
1 2
2 1
Thus edges: 1->2, 2->1. SCC: {1,2}. Others: {3},{4},{5}. Output:
1 2
1 2
3
4
5
Matches.
Thus correct.
Now about constraints: Possibly N up to 2000? But to be safe we handle up to 200000.
But total output can be O(N^2) if one SCC contains all nodes. For N=200000, that would be 40 billion numbers, impossible. So constraints likely limit N to maybe 2000 or 5000. But we don't know. Let's think: The problem might be from AtCoder Beginner Contest (ABC) but I'm not aware of this exact problem. Or from JOI? Possibly JOI 2010/2011? Not sure.
Could be from AtCoder "Logical Inference" (maybe AtCoder Regular Contest). I recall a problem "Logical Operations" where you need to output equivalence classes. Actually there is AtCoder problem "Logical Expression" but not this.
We can check online: but as an AI, I can't browse.
Given typical problems, N might be up to 10^5 and M up to 2*10^5, but outputting each component's list for each node would be too large if SCC large. However, the output asks to output for each node the list of all nodes in its SCC. That's redundant; they could compress but they want to output N lines each containing the list. So if SCC size is K, the list of K numbers appears K times. So total output size is sum over components of (size^2). That could be huge for large N. Usually contest problems avoid such output requirements because they would be huge. They might limit N to 1000 or so. But we should check: maybe N <= 2000. Alternatively, they might ask to output each line only the numbers that are equivalent, but they don't require the list sorted? But they do.
We can deduce constraints from typical JOI/AtCoder: There is a problem "Logic" from JOI 2013/2014? Or "Proposition" from AtCoder? Hmm.
I think it's safe to implement and if N is large, output may be too large but then the problem wouldn't have such constraints.
Given the instruction: "Output all propositions that have the same value as i in ascending order." That suggests we need to output list for each i. That's typical for problems with small N.
Thus implement as described.
But careful: The graph might be large but M could be up to 10^5; we can compute SCC quickly, but outputting could be optimized by printing same list for nodes in same component multiple times. But printing each list individually even if same is necessary. We can store component's sorted list as a string and print for each node.
So algorithm:
-
Read input.
-
Build adjacency lists: graph = [[] for _ in range(N)], graph_rev = [[] for _ in range(N)].
-
For each edge, read a,b; convert to 0-index: a-1, b-1; append b to graph[a]; append a to graph_rev[b].
-
Compute order using iterative DFS:
visited = [False]*N
order = []
def dfs1(s):
stack = [(s, 0)] # (node, next index?) Or use explicit stack for postorder.
# We'll simulate recursion with stack storing (node, iterator index)
Actually easier: implement recursive DFS with sys.setrecursionlimit. But if N up to 10^5, recursion depth may cause recursion limit error if graph is deep. Use iterative.
Approach for Kosaraju iterative:
For each node not visited:
stack = [(node, 0)] # second element: state 0=enter, 1=exit
while stack:
v, state = stack.pop()
if state == 0:
if visited[v]:
continue
visited[v] = True
stack.append((v, 1)) # push exit marker
for w in graph[v]:
if not visited[w]:
stack.append((w, 0))
else:
order.append(v)
This yields order in postorder (exit order). Then we need to process nodes in reverse order for second DFS on reverse graph.
-
Second pass: visited2 = [False]*N
comp = [-1]*N
comp_nodes = [] # list to hold list of nodes per component
For node in reversed(order):
if not visited2[node]:
# start DFS on reverse graph to collect nodes
stack = [node]
visited2[node] = True
component = []
while stack:
v = stack.pop()
comp[v] = len(comp_nodes) # assign component id
component.append(v)
for w in graph_rev[v]:
if not visited2[w]:
visited2[w] = True
stack.append(w)
comp_nodes.append(component)
-
Now we have comp_nodes lists (unsorted). For each component, we need to sort the node indices (1-indexed) for output. But careful: we have 0-indexed internal, convert to 1-indexed when outputting.
-
For i from 0 to N-1 (i.e., node i), get comp_id = comp[i]; then sorted_nodes = sorted([x+1 for x in comp_nodes[comp_id]]). Then print " ".join(map(str, sorted_nodes)).
But if N is large and SCC size large, we will sort each component once, but for each node we recompute the string? That is O(N * size_of_component?) Actually we need to output N lines. We can precompute for each component the output string (the space-separated list). Then for each node, print that string. That's efficient.
So:
comp_output = []
for nodes in comp_nodes:
sorted_nodes = sorted([x+1 for x in nodes])
comp_output.append(" ".join(map(str, sorted_nodes)))
Then for i in range(N):
print(comp_output[comp[i]])
That prints same line for nodes in same component.
Now check sample: comp_nodes: for component 0: nodes [0,1] sorted [1,2] string "1 2". For component 1: node [2] => "3". etc. Prints as desired.
Now complexity: Building adjacency O(N+M). DFS O(N+M). Sorting components: sum over components O(size_i log size_i) total O(N log N) worst-case. Output O(N + total output size). The total output size is sum over components (size_i * size_i) (since each component's string printed size_i times). But that's inherent to output requirements. We can't reduce.
Thus solution.
Edge Cases: M=0: each node alone.
Now about reading input: We'll use sys.stdin.read() to read quickly.
Implementation details.
Now think about potential pitfalls: Graph may be disconnected, but Kosaraju handles.
Now memory: storing graph: adjacency list for N up to maybe 200000, M up to 200000, that's okay.
Now, is there any nuance about "transition law holds"? It means transitivity is allowed. But do we also need to consider that from a->b we can deduce not something else? No.
But what about contrapositive? The problem didn't mention "if and only if" but only "if" as conditional. It says "transition law holds", which might refer to the law of hypothetical syllogism: from a->b and b->c we can infer a->c. They didn't mention contrapositive: from a->b and not b -> not a? But that is not given. So we only have implication and transitivity. So the closure is just reachability.
Thus SCC is correct.
Thus final answer: Python code.
Let's produce final solution with explanation.
But the user asked only for code? The instruction: "solve the problem and output final answer code in the appropriate language." So we output Python code.
We'll also include comments.
Now produce final answer.
Note: The problem statement uses " ... " latex formatting, but we understand.
Now finalize.
Potential improvements: Use iterative DFS to avoid recursion limit.
We'll write code:
import sys
def main():
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
N = int(next(it))
M = int(next(it))
graph = [[] for _ in range(N)]
graph_rev = [[] for _ in range(N)]
for _ in range(M):
a = int(next(it)) - 1
b = int(next(it)) - 1
graph[a].append(b)
graph_rev[b].append(a)
# Kosaraju
visited = [False]*N
order = []
for i in range(N):
if not visited[i]:
# iterative DFS for postorder
stack = [(i, 0)]
while stack:
v, state = stack.pop()
if state == 0:
if visited[v]:
continue
visited[v] = True
stack.append((v, 1))
for w in graph[v]:
if not visited[w]:
stack.append((w, 0))
else:
order.append(v)
visited2 = [False]*N
comp = [-1]*N
comp_nodes = []
for v in reversed(order):
if not visited2[v]:
stack = [v]
visited2[v] = True
component = []
while stack:
node = stack.pop()
comp[node] = len(comp_nodes)
component.append(node)
for w in graph_rev[node]:
if not visited2[w]:
visited2[w] = True
stack.append(w)
comp_nodes.append(component)
# Prepare output strings for each component
comp_output = []
for nodes in comp_nodes:
# convert to 1-index, sort
sorted_nodes = sorted(x+1 for x in nodes)
comp_output.append(" ".join(map(str, sorted_nodes)))
out_lines = []
for i in range(N):
out_lines.append(comp_output[comp[i]])
sys.stdout.write("\n".join(out_lines))
if __name__ == "__main__":
main()
Now final answer. ```python
import sys
def main() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
N = int(next(it))
M = int(next(it))
# 0‑based indexing
graph = [[] for _ in range(N)]
graph_rev = [[] for _ in range(N)]
for _ in range(M):
a = int(next(it)) - 1
b = int(next(it)) - 1
graph[a].append(b)
graph_rev[b].append(a)
# ---------- Kosaraju : first pass ----------
visited = [False] * N
order = []
for start in range(N):
if visited[start]:
continue
stack = [(start, 0)] # (vertex, state) state 0 = entry, 1 = exit
while stack:
v, state = stack.pop()
if state == 0:
if visited[v]:
continue
visited[v] = True
stack.append((v, 1)) # push exit marker
for w in graph[v]:
if not visited[w]:
stack.append((w, 0))
else:
order.append(v) # postorder
# ---------- second pass on reversed graph ----------
visited2 = [False] * N
comp_id = [-1] * N
components = [] # list of lists, each holds vertices of one SCC
for v in reversed(order):
if visited2[v]:
continue
stack = [v]
visited2[v] = True
cur_comp = []
while stack:
node = stack.pop()
comp_id[node] = len(components)
cur_comp.append(node)
for w in graph_rev[node]:
if not visited2[w]:
visited2[w] = True
stack.append(w)
components.append(cur_comp)
# ---------- prepare output strings ----------
comp_output = []
for comp in components:
# convert to 1‑based, sort, join with spaces
line = " ".join(str(x + 1) for x in sorted(comp))
comp_output.append(line)
out_lines = [comp_output[comp_id[i]] for i in range(N)]
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()