We need to solve problem: Given a directed graph with n vertices, each vertex has exactly two outgoing edges, one labeled 0 and one labeled 1 (so deterministic complete transition). Each vertex also has a type: 0 (round) or 1 (hexagon). We define equivalence: two vertices a and b are equivalent if (1) same type, and (2) for every nonempty finite sequence (length >= 1) of bits, the vertex type reached after following that sequence from a and from b is the same. Actually condition says: "For any sequence of lengths 1 or more consisting of 0s and 1s, the types of vertices that are finally reached when the transition is started from each of a and b are the same." It says "the types of vertices that are finally reached". So we need that the type (round/hexagon) of the final vertex after applying the sequence from a and from b are equal. It does not require the actual vertex numbers to be equal, only types. And the sequences are of length >=1. Also note: "any sequence of lengths 1 or more" meaning all finite nonempty sequences.
Now we need for each query vertex q, output the number of vertices that are equivalent to q (including itself? yes, "the number of vertices equivalent to this vertex" includes itself, as examples: first example n=2, both vertices type 0, and output 2, so include itself.)
We need to compute equivalence classes under this relation. Then for each query, output size of its class.
n up to 3000, m up to n. So we can afford O(n^2) possibly but careful with constants; maybe O(n^2) might be okay for n=3000 (9e6) but maybe we need something smarter. However we need to consider the equivalence definition that depends on types after arbitrary sequences. This resembles DFA minimization with acceptance states defined by vertex types. Indeed, we have a deterministic finite automaton (DFA) where each state is a vertex, alphabet = {0,1}, transition function given (each state has exactly one transition for each symbol), and "accepting" states are those of a certain type? But note condition: equivalence requires that for any input string (nonempty), the types of the states reached are equal. That's like: Two states are equivalent if for every nonempty string w, the type of δ(a,w) equals the type of δ(b,w). However, we don't have a concept of accepting; it's just that the output (type) after reading the entire string must be equal. That is like a Mealy machine where output is the type of the state after transitions? Actually, it's like a DFA where we only care about the output (0/1) of the final state, not about acceptance. But we could define each state's output as its type. Then two states are equivalent if for every input string (including empty?), they produce the same output sequence? Wait: They compare only the final vertex's type after the whole string. Not the output sequence along the way. Condition only cares about the type at the end, not intermediate types. So it's like they produce output only at the end. However, if we consider the output function on states, then for any string w, the output after reading w from state a is type(δ(a,w)). So this is like a Moore machine where output is associated with states, and we consider output after the entire input string. In automata theory, two states are equivalent if for every input string, the outputs produced from that state (including the output before any input? In Moore machine, output is produced on entry to state, so the output sequence for input w = output(start state) followed by output after each transition? Typically, equivalence for Moore/Mealy machines requires that for any input string, the output sequences are identical. But here they only care about the final state's output, not the outputs along the path. That is a different notion.
Let's formalize: Define type: T(v) ∈ {0,1}. For a state a and a nonempty string w ∈ {0,1}^+, define f(a,w) = T(δ(a,w)). Condition: a and b equivalent if T(a)=T(b)? Wait condition 1 says a and b are same kind of vertices. So they must have same type initially. And condition 2: For any nonempty w, f(a,w) = f(b,w). So they must have same output on every nonempty input string. Note that if we allowed empty string (length 0), then f(a,ε) = T(a). Since condition 1 already ensures T(a)=T(b), so it's consistent. So we could also include empty string; but they explicitly say lengths 1 or more, but condition 1 covers the initial type.
Thus equivalence is: a ~ b iff T(a)=T(b) and for all w ∈ Σ^+, T(δ(a,w)) = T(δ(b,w)).
This is reminiscent of bisimulation but with types as observation. It's essentially the Myhill-Nerode type equivalence for the function from strings to outputs (type). That is, define language L_a: set of strings w such that T(δ(a,w)) = 1? But they want equality of T(δ(a,w)) for all w, not just a subset. So it's like two states define the same function f: Σ^+ → {0,1} (or Σ^* → {0,1} including empty). So it's like they are equivalent as states of a deterministic transducer that outputs a bit at the end. This is exactly the notion of "indistinguishable states" in a DFA if we consider the final/accepting states set? But here "accepting" is not binary? Actually, if we treat each vertex type as a binary output, we can think of two separate sets: set of vertices of type 0 and type 1. Then condition says that for all strings w, δ(a,w) is in type X iff δ(b,w) is in type X? That is, for all w, the membership in type 1 set from a and b is same. So define set F = { vertices of type 1 } (or type 0). Then condition 2: for every nonempty w, δ(a,w) ∈ F ⇔ δ(b,w) ∈ F. So it's exactly the Myhill-Nerode equivalence for the regular language of strings that lead to F from the state? But careful: In DFA minimization, two states are equivalent if for every string w (including empty), the state reached by w from each is either both accepting or both rejecting. That's the standard definition of equivalence used for DFA minimization. Indeed, for a DFA with set of accepting states F, two states p and q are equivalent (indistinguishable) if for all strings w, δ(p,w) ∈ F iff δ(q,w) ∈ F. Typically, the empty string is included, meaning p and q themselves must both be accepting or both rejecting. That matches our condition if we treat F as the set of vertices of type 1 (or type 0)? But condition 1 already requires same type initially, which matches the empty string condition. So condition 2 for nonempty strings is equivalent to for all w∈Σ^*, δ(p,w)∈F ⇔ δ(q,w)∈F, because the empty string condition is covered by condition 1. So indeed a ~ b iff they are indistinguishable in the DFA sense with respect to the partition of states into two sets: type 0 and type 1.
But wait: In DFA minimization, the equivalence relation is defined over all states (not requiring initial types to be same; the empty string condition forces that if they are of different types, they are distinguishable). So indeed two states of different types are distinguishable by empty string. So our equivalence classes are exactly the classical DFA state equivalence classes under the partition of states by their type (output). So we can compute the equivalence classes by DFA minimization algorithm (Hopcroft's algorithm, or simpler O(n^2) for n=3000). However, note the graph is deterministic complete (each state has two outgoing transitions). So we can apply the partition refinement algorithm.
But careful: In DFA minimization, we typically consider the automaton with a set of final states; equivalence is defined as: two states are equivalent if for every string, both either lead to final or non-final. This exactly matches our condition (with type being the "final" flag). So yes.
Thus we need to compute the number of states in each equivalence class under DFA minimization.
Given n <= 3000, we can implement a standard partition refinement algorithm (e.g., Hopcroft) which runs in O(n log n) or O(n * alphabet size) but given constraints, even O(n^2) using table-filling (state pair distinguishability) might be acceptable: n=3000, number of pairs ~4.5 million, which is manageable. But we need to compute for each vertex the size of its equivalence class, and answer m queries. So we could use the table-filling algorithm for DFA minimization: initially mark all pairs (i,j) where types differ as distinguishable. Then iteratively propagate: if there exists an unmarked pair (i,j) such that for some symbol c, (δ(i,c), δ(j,c)) is marked distinguishable, then mark (i,j) as distinguishable. Repeat until no changes. This is O(n^2 * alphabet) which for n=3000, alphabet=2, that's about 9 million pairs * iterations? Actually classic algorithm runs in O(n^2 * |Σ|) with a worklist approach (like Hopcroft-Karp for DFA minimization). But we can implement BFS of pairs: initialize a queue with all distinguishable pairs (type different). Then for each pair (p,q) in queue, we look at all incoming transitions: for each symbol c and each state r such that δ(r,c)=p, and each state s such that δ(s,c)=q, if (r,s) is not yet marked, mark it and enqueue. This is typical algorithm. That would be efficient: O(|Σ| * n^2) worst-case but with good constants. Since each state has exactly two outgoing, but many incoming? Could be O(n^2) if we store reverse edges: for each symbol c, we can have a list of predecessors (states that have transition on c to a given state). Then for each pair (p,q) we can consider all (r,s) where r in pred_c(p) and s in pred_c(q). That could be O(n^2) per pair in worst case if pred lists are large, but overall total operations can be O(|Σ| * n^2) because each combination of r and s may be considered multiple times? Actually the standard algorithm: for each pair (p,q) that becomes distinguishable, we look at all incoming edges: for each symbol a, for each state x with δ(x,a)=p, for each state y with δ(y,a)=q, if (x,y) is not yet distinguishable, mark it and add to queue. This can be O(|Σ| * n^2) in total if we iterate over all (x,y) pairs for each (p,q). But since number of pairs is O(n^2), and each pair may be processed once (when marked), total considered combinations across all pairs may be O(|Σ| * n^3) if we naively loop over all x,y combinations? Because for each distinguishable pair (p,q), we need to consider all pairs of states that go to p and q via same symbol. If many states have transitions to p and q, the number of such pairs is |pred_a(p)| * |pred_a(q)|. In worst-case, each state could have many incoming edges? Since each state has exactly two outgoing, the total number of incoming edges per state can be up to n (if all transitions point to the same state). So |pred_a(p)| can be O(n). Then for a pair (p,q), considering all pairs of predecessors could be O(n^2). And there can be O(n^2) pairs marked. That would be O(n^4) too high.
But we can do better: Use the standard table-filling algorithm with dynamic programming that iterates over all pairs and check if any symbol leads to a distinguishable pair, and repeat until fixpoint. That can be O(n^2 * |Σ| * iterations) which might be O(n^3) in worst-case if we use naive loops. However n=3000, maybe we can afford O(n^2) with proper optimization? Actually O(n^2) is ~9e6; O(n^3) is 27e9, too high.
Thus we need an algorithm that runs in O(|Σ| * n^2) or better. Hopcroft's algorithm for DFA minimization runs in O(|Σ| * n log n) typically. That is safe for n=3000. But implementing Hopcroft's algorithm correctly may be a bit more involved but doable. Alternatively, we can use the partition refinement approach starting from initial partition based on type (two groups). Then repeatedly split groups based on transitions. That is similar to Hopcroft but simpler: maintain partition of states into blocks (equivalence classes). While there exists a block B and a symbol a such that the set of states that go to some block (or subset) under a causes a split, we refine. This is essentially the algorithm for computing the coarsest stable refinement of initial partition with respect to the transition function. This is known as the Moore algorithm for DFA minimization, which runs in O(|Σ| * n^2) but can be optimized to O(|Σ| * n log n) with appropriate data structures. However for n=3000, even O(n^2) = 9e6 might be acceptable if constant factor low. But Moore algorithm may require iterating over blocks and splitting repeatedly; its worst-case can be O(n^2) per iteration? Actually the classical Moore algorithm's complexity is O(|Σ| * n^2) because each refinement step can split at most one block, and there can be O(n) splits, and each step we may need to recompute signatures for all states, which costs O(|Σ| * n). So total O(|Σ| * n^2). For n=3000, |Σ|=2, that's 2*9e6 = 18e6 operations, which is definitely fine. Wait: O(|Σ| * n^2) = 2 * 9e6 = 18e6, that's trivial. But we must confirm that the Moore algorithm indeed achieves O(|Σ| * n^2). Let's think: In Moore algorithm, we start with partition P = {F, Q\F} (two blocks). Then we refine: for each block B in P, we compute for each state q its signature: the tuple of blocks that q goes to on each symbol. Then we split each block into subblocks based on identical signatures. This is done repeatedly until no changes. In worst case, each iteration can split many blocks, but the number of iterations can be up to n (since each split increases number of blocks by at least 1, and maximum blocks is n). In each iteration we process all n states and for each compute the signature (look at two transitions, look up block ids). That is O(|Σ| * n) per iteration. So total O(|Σ| * n * iterations). Since iterations <= n, worst-case O(|Σ| * n^2). With n=3000, that's 18e6, which is fine.
But is it safe that number of iterations can be up to n? In worst-case yes, but often less. 3000*3000 = 9 million; times 2 = 18 million. That's trivial.
Thus we can implement Moore's algorithm (also known as DFA minimization by partition refinement). It's straightforward: we maintain an array block_id for each state (0..n-1). Initially, assign block_id = type (0 or 1). But careful: There are two types; we can just set block_id = type (since type is 0/1). But maybe there could be more than 2 blocks later. We'll maintain mapping from block_id to block (list of states). We'll also maintain the current partition as a list of blocks (each block is a set/list of states). In each iteration:
For each block B, we need to compute for each state q in B its signature: (block_id[ δ(q,0) ], block_id[ δ(q,1) ]). Then within B, group states by signature. If B splits into multiple groups, we replace B with those groups (assign new block_ids to the new blocks). We continue until no splits occur.
At the end, the partition corresponds to the equivalence classes under Myhill-Nerode equivalence. Indeed, this yields the minimal DFA (state equivalence) but note: in DFA minimization, we usually merge indistinguishable states; the Moore algorithm refines until the partition is stable: for any two states in same block, for each symbol they go to states in same block. This condition is exactly the Myhill-Nerode equivalence? Actually, the stable partition condition is: if two states are in the same block, then for each symbol, their successors are in the same block. This is a necessary condition for equivalence but not sufficient; equivalence also requires that the outputs (accepting/non-accepting) are same, which is ensured by initial partition by type. However, is stability sufficient to guarantee that two states are equivalent? In DFA minimization, the standard algorithm uses refinement until stable; the resulting partition is the coarsest stable refinement of the initial partition. Indeed, two states are equivalent if they are in the same block of the coarsest stable partition. So this algorithm computes exactly the equivalence classes we need.
Thus we can implement:
-
Input n, m.
-
For i in 0..n-1: read v_i, s_i (transition on 0), t_i (transition on 1). We'll store type[i] = v_i; trans[i][0] = s_i; trans[i][1] = t_i.
-
Initialize block_id[i] = type[i] (0 or 1). But note: there may be only two blocks initially. However, if all vertices have same type, then initial partition is one block? Actually if all types are same (0 or 1), then initial partition would have just one block (since all are same type). But we treat partition as blocks based on type: we need to separate type 0 and type 1. So we should have two blocks initially. If all vertices are type 0, then block 0 contains all; if all type 1, then block 1 contains all. That's fine.
-
We'll maintain a list of blocks. Each block we can store as a list of state indices. Also we need quick mapping from block_id to block index? Since block_ids may be reassigned, we can just maintain an array of block objects with ids as indices in the block list. We'll keep block_id as the index of block in current block list.
Let's design:
- blocks = list of lists (current partition).
- For each state i, assign block_id[i] = type[i] (0 or 1). But if we want to support case where type[i] can be 0 or 1, we can map type to block index: Let's create initial blocks: for each type value (0 or 1) we create a block containing all states of that type. However, if one type has no states, we may have only one block. So we should first collect states by type: type0 list, type1 list. Then assign block_ids: for states in type0, block_id = 0; for type1, block_id = 1 (if both exist). But if only one type exists, we only have one block with id 0. So we need to handle that.
Simplify: We'll start with an array block_id initial: we assign each state a block number based on type. But we need to compress block numbers to 0..num_blocks-1. So we can do:
- Use a dict: type_to_block = {}.
- For each state i, if type[i] not in type_to_block, assign new block index and create an empty list. Then append i to that block's list, and set block_id[i] = that index.
After reading all, we have blocks (list of lists) and block_id.
Now iterate:
changed = True
while changed:
changed = False
new_blocks = [] # will hold new partition
new_block_id = [ -1 ] * n
# We'll iterate over current blocks
for block in blocks:
# For each state in block, compute signature: pair (block_id[trans[i][0]], block_id[trans[i][1]])
# Use dictionary to map signature to list of states within this block.
sig_map = {}
for i in block:
sig = (block_id[trans[i][0]], block_id[trans[i][1]])
if sig not in sig_map:
sig_map[sig] = []
sig_map[sig].append(i)
# If more than one group, we split
if len(sig_map) > 1:
changed = True
# For each group, assign new block id (starting from current length of new_blocks)
for group in sig_map.values():
new_id = len(new_blocks)
new_blocks.append(group)
for i in group:
new_block_id[i] = new_id
else: # same group, keep block as is
new_id = len(new_blocks)
new_blocks.append(block)
for i in block:
new_block_id[i] = new_id
blocks = new_blocks
block_id = new_block_id
After loop, blocks contain equivalence classes.
Now, we need to answer queries: For each query qj, output the size of the block containing qj (i.e., len(blocks[block_id[qj]])).
Check with examples:
Example 1:
n=2, m=1
Vertices: 0: type0, trans0:0->0? Actually input:
2 1
0 0 1
0 1 0
0
First vertex: v=0, s=0, t=1 -> from vertex 0 on 0 goes to 0, on 1 goes to 1.
Second vertex: v=0, s=1, t=0 -> from 1 on 0 goes to 1, on 1 goes to 0.
Both type 0.
Initial partition: all type0 -> one block: [0,1].
Iteration 1:
For state0: sig = (block_id[0], block_id[1]) = (0,0) because both in block0.
State1: trans: on 0->1 (block0), on1->0 (block0) => sig=(0,0). So same signature, no split. So algorithm ends, block size 2. Output for q=0 is 2. matches.
Example 2:
6 6
0 1 5
1 1 1
0 1 5
0 2 1
0 5 1
1 5 5
Queries: 0 1 2 3 4 5
Let's compute manually using algorithm.
Data:
0: type0, trans0:0->1, 1->5
1: type1, trans1:0->1, 1->1 (both to 1)
2: type0, trans2:0->1, 1->5? Actually "0 1 5": type0, s=1? Wait lines:
vertex0: 0 1 5
vertex1: 1 1 1
vertex2: 0 1 5
vertex3: 0 2 1
vertex4: 0 5 1
vertex5: 1 5 5
So:
0: type0, trans0:0->1, 1->5
1: type1, trans1:0->1, 1->1
2: type0, trans2:0->1, 1->5
3: type0, trans3:0->2, 1->1
4: type0, trans4:0->5, 1->1
5: type1, trans5:0->5, 1->5
Initial partition: type0: vertices {0,2,3,4} -> block0; type1: vertices {1,5} -> block1.
Let block_id: 0->0, 1->1, 2->0, 3->0, 4->0, 5->1.
Iteration1:
Process block0 ({0,2,3,4}):
Compute signatures:
- state0: trans0->1 (block1), trans1->5 (block1) => sig=(1,1)
- state2: same as state0 => (1,1)
- state3: trans0->2 (block0), trans1->1 (block1) => (0,1)
- state4: trans0->5 (block1), trans1->1 (block1) => (1,1)?? Wait: trans4:0->5 (block1), 1->1 (block1) => (1,1)
But check: state4 trans0->5 (type1 block1), trans1->1 (type1 block1) => (1,1). So states 0,2,4 have sig (1,1); state3 has sig (0,1). So block0 splits into two: groupA {0,2,4} and groupB {3}.
Process block1 ({1,5}):
state1: trans0->1 (block1), trans1->1 (block1) => (1,1)
state5: trans0->5 (block1), trans1->5 (block1) => (1,1) because block_id[5]=1, block_id[5]=1 => (1,1). So they have same signature => no split.
Now new blocks: after iteration1, we have three blocks:
Block0: {0,2,4} (type0)
Block1: {3} (type0)
Block2: {1,5} (type1)
Block ids: 0:0,1:2?, Actually careful: We'll assign new ids sequentially.
In our algorithm, we process blocks in order. Suppose initial blocks: block0 = type0 list, block1 = type1 list. For first block (type0), we split into two groups: groupA {0,2,4} and groupB {3}. We'll add them to new_blocks in order: first groupA -> new_id0; then groupB -> new_id1. For block1 (type1), we keep as is, add as new_id2. So final block_id:
0->0, 2->0, 4->0
3->1
1->2, 5->2
Now check if partition is stable: We need to verify that for each block, all states have same signatures using the new block_ids.
Iteration2:
Compute block0: {0,2,4}
- state0: trans0->1 (block_id[1]=2), trans1->5 (block_id[5]=2) => (2,2)
- state2: same (2,2)
- state4: trans0->5 (2), trans1->1 (2) => (2,2) => all same, no split.
Block1: {3}
Only one state, no split.
Block2: {1,5}
- state1: trans0->1 (block_id[1]=2), trans1->1 (2) => (2,2)
- state5: trans0->5 (2), trans1->5 (2) => (2,2) => same, no split.
Thus stable. So equivalence classes: {0,2,4} size3, {3} size1, {1,5} size2.
Now queries:
0 -> size3
1 -> size2
2 -> size3
3 -> size1
4 -> size3
5 -> size2
Matches sample output:
3
2
3
1
3
2
Good.
Thus algorithm works.
Now we need to implement for n up to 3000. The number of iterations could be at most the depth of splitting. In worst-case, the partition can refine to n blocks, requiring up to n iterations. Each iteration we process each block and each state. So total O(n^2) ~ 9e6, which is fine.
Potential pitfalls: The initial partition might have two blocks, but if all vertices same type, there is one block. That's okay.
We need to answer m queries; we can compute an array class_size[block_id] after final partition, then for each query print class_size[block_id[q]].
Now check constraints: The graph is connected when considered undirected? They said: "Assuming that the edges of a given graph can move in both directions, there is a set of edges that connects any two points, that is, the given graph is concatenated." So the underlying undirected graph is connected. However, this property may not be needed for algorithm.
We should confirm that equivalence defined as we computed matches the problem definition exactly. Let's double-check with potential nuance: Condition says "For any sequence of lengths 1 or more consisting of 0s and 1s, the types of vertices that are finally reached when the transition is started from each of a and b are the same." This does not consider sequences of length 0, but condition 1 ensures same type. So it's exactly as DFA equivalence.
One nuance: The transition function is deterministic and total. Yes.
Thus algorithm stands.
Now, note that the problem states "When two vertices a and b satisfy the following two conditions, a and b are equivalent." It does not require that the reached vertex types be same for all sequences including those that may lead to non-terminating? But it's finite deterministic, so always terminates.
Thus answer is correct.
Now we need to implement with reading input, processing, output.
Edge Cases:
-
n=1: Only one vertex. It will be in a block of size 1. Queries ask that vertex, output 1. Works.
-
All vertices same type: maybe equivalence classes based solely on transition behavior. Example: a two-state DFA where both are type0, but they may be distinguishable based on future transitions? Since condition 2 requires for all sequences, final vertex types must be same. If all vertices are type0, then for any sequence the final vertex type is always 0. So condition 2 is automatically satisfied regardless of transitions? Wait careful: If all vertices are type0, then for any start state and any sequence, the final vertex's type is always 0, because all vertices type0. So condition 2 is automatically true for any pair of vertices? But condition 1 requires they are same type, which they are (all type0). So would all vertices be equivalent? According to definition: for any sequence, the types of vertices finally reached from a and b are the same. Since every vertex is type0, the type reached from a is always 0, and from b always 0, so they are the same. So yes, all vertices would be equivalent. But is that consistent with DFA minimization? In DFA minimization, if all states are non-accepting, then they are all equivalent? In standard DFA minimization, if there are no accepting states (or all non-accepting), then indeed all states are equivalent because the language recognized from each state is empty? Wait: In DFA, if all states are non-accepting, then for any state, the set of strings that lead to acceptance is empty? Actually from any state, if there is no accepting state, the language accepted is empty. So all states accept the empty language, so they are equivalent. But also there could be other distinguishing behavior if the automaton may have accepting states reachable? But if all are non-accepting, then regardless of transitions, the output after any string is always false, so indistinguishable. So yes, all states are equivalent. So our algorithm: initial partition: all states same type (say 0), so only one block. Then we refine: signatures may differ, but the condition for stability is that within a block, states have same successor blocks. Since we only have one block initially, if we refine based on signature, we might split the block. But does that correspond to equivalence? In DFA minimization with only non-accepting states, the standard algorithm would merge all states into one block because there is no distinction; but Moore algorithm starts with partition based on accepting/non-accepting. Since all are non-accepting, initial partition is a single block. Then we refine: we look at signatures: if two states have different successor blocks, but since all are in same block, the signature is just (block, block) for both? Wait, if there is only one block, then all states have signature (0,0) regardless of where they go, because the block ids of successors are all 0. So no split occurs. So indeed they remain in one block. That's correct. Good.
Now consider all vertices same type but there are both 0 and 1? Actually type is 0 or 1; if all are same type, it's either all 0 or all 1. So same as above.
Now consider mixed types. The algorithm works.
Thus implementation straightforward.
Complexity: O(n^2 * |Σ|) worst-case. For n=3000, it's fine.
But we need to be careful about recursion depth? Not needed.
Memory: store transitions (2*n ints), type (n), block_id (n), and lists.
Implementation details:
-
We'll read integers using sys.stdin.read().split() for speed.
-
Use list for transitions: trans0 = [0]*n, trans1 = [0]*n or trans = [[0,0] for _ in range(n)].
-
type array: typ = [0]*n.
-
Initialize block_id as list of length n, initially assign based on type.
Simpler: we can compute initial partition by grouping:
from collections import defaultdict
blocks = []
block_of_state = [0]*n
type_groups = defaultdict(list)
for i in range(n):
type_groups[typ[i]].append(i)
for idx, group in enumerate(type_groups.values()):
blocks.append(group)
for i in group:
block_of_state[i] = idx
Then iterate:
while True:
new_blocks = []
new_block_of_state = [0]*n
changed = False
for block in blocks:
# if len(block) == 1: we can just keep as one group, but we still need to check signature? Actually even if size 1, signature is trivially same, so we can just keep it. But we might still process to assign new id.
# We'll compute signature map.
sig_map = {}
for i in block:
sig = (block_of_state[trans[i][0]], block_of_state[trans[i][1]])
# Use tuple as key
if sig in sig_map:
sig_map[sig].append(i)
else:
sig_map[sig] = [i]
if len(sig_map) > 1:
changed = True
for group in sig_map.values():
new_id = len(new_blocks)
new_blocks.append(group)
for i in group:
new_block_of_state[i] = new_id
else:
# keep block as is
new_id = len(new_blocks)
new_blocks.append(block)
for i in block:
new_block_of_state[i] = new_id
if not changed:
break
blocks = new_blocks
block_of_state = new_block_of_state
After loop, we have final block_of_state.
Now compute size per block: block_sizes = [len(block) for block in blocks]
Then for each query q, output block_sizes[block_of_state[q]].
Now test with given examples.
But also consider potential complexity: In each iteration, for each block, we iterate over its states. That's total O(n) per iteration. But we also do dictionary operations per state. That's fine.
Potential memory: block list of lists can hold up to n lists, each list containing states. That's fine.
Edge Cases: It's possible that the graph has self-loops, etc.
Now, we must confirm that equivalence defined in problem is exactly the DFA minimization equivalence. Let's double-check with an example where two states are considered equivalent in DFA but might differ because they have to have same type? Already included. Also note condition: "the types of vertices that are finally reached" - they care about the final vertex type, not about the entire path. That's exactly what we used.
Thus solution is sound.
Now we should confirm that Moore algorithm yields the coarsest stable refinement of the initial partition, which corresponds to the equivalence relation where two states are indistinguishable by any string. That's proven.
Thus we can implement.
But wait: There is nuance: In DFA minimization, we typically consider the set of final states as accepting; the equivalence is defined as: for all strings w, δ(p,w) is accepting iff δ(q,w) is accepting. That is exactly the condition 2 plus condition 1 (empty string). So it's consistent.
Thus answer.
Now I think about performance: n=3000, each iteration O(n) but we might have up to n iterations => 9e6 operations; plus dictionary overhead, still fine.
However, we need to be careful that the number of iterations could be as high as n only if each iteration splits exactly one block into two, and the number of blocks increases by 1 each time, reaching n. That is possible? For example, if the automaton is a chain that yields a different behavior for each state, initial partition may be one block if all same type? But if types are all same, then as argued, they may all be equivalent? Not necessarily. Wait, if all states are same type, then condition 2 is automatically satisfied because final type always same. So all states are equivalent. So partition remains one block, no splits. So iterations = 0. If types are mixed, then initial partition has at least two blocks. The refinement can split blocks. But maximum number of blocks is n. So starting from 2 blocks, we need at most n-2 splits; each iteration could split multiple blocks, but worst-case we could have each iteration split only one block into two, requiring up to n-2 iterations. So iterations could be O(n). So O(n^2) overall.
But 3000^2 = 9 million, so fine.
Now, there is a possible nuance: The algorithm described (Moore) might require O(n^2) time but also may be O(|Σ| * n^2). That's fine.
But we need to be careful about Python's performance: 9 million operations plus dictionary lookups per state each iteration. If iterations = 3000, that would be 3000 * n = 9 million per iteration? Wait: O(n^2) total means total across all iterations is about n^2. But if iterations = n, then each iteration processes all n states, total operations = n * n = n^2. So that's 9 million. That's very light. However, each iteration we also do dictionary insertion per state. That's fine.
But is it possible that number of iterations could be larger than n? No, because each iteration increases number of blocks by at least 1 (if changed) and max blocks is n, so at most n iterations from initial number of blocks (which is at least 1). Actually initial blocks could be 1 or 2. So at most n-1 iterations. So n iterations worst-case.
Thus total state visits = O(n^2) = ~9e6. That's trivial in Python.
Thus implementation straightforward.
Now, check memory: storing transitions as two lists of ints: 2*3000 = 6000 ints; type array: 3000; block_of_state: 3000; and blocks lists: each state appears in exactly one block, so total list elements = n.
All good.
Now produce final answer.
But before finalizing, let's verify with some edge cases.
Consider a case where two states have same type, and from them, for every nonempty sequence, the type of the reached state is always the same? Could there be a case where the DFA minimization equivalence differs from the problem's equivalence due to the fact that sequences are of length >=1 but condition 1 already ensures type equality? In DFA equivalence we require for all strings (including empty) they agree on acceptance. Condition 1 + condition 2 (nonempty) implies agreement on empty string because condition 1 says they have same type. So it's equivalent.
Now, what about infinite sequences? Not considered.
So fine.
Thus answer.
Now, we can write code.
But wait, the problem statement says: "For any sequence of lengths 1 or more consisting of 0s and 1s, the types of vertices that are finally reached when the transition is started from each of a and b are the same." It says "finally reached", meaning after the entire sequence. That's exactly what we used.
Now, possible misinterpretation: Could the phrase "the types of vertices that are finally reached" be interpreted as "the types of vertices that are reached at the end of the process (i.e., the last vertex visited) are the same type"? Yes.
So all good.
Now, algorithm is simple.
We'll implement.
But we also need to be careful: The graph is directed, but they said underlying undirected is connected, but we don't need that.
Now, we can write final solution.
But I'll test with some additional scenarios.
Test 1: n=3, all type 0.
transitions:
0: 0->1,1->2
1: 0->0,1->1
2: 0->2,1->2
All type0.
Our algorithm: initial block = [0,1,2]
Iteration1: compute signatures:
state0: succ0=1 (block0), succ1=2 (block0) => (0,0)
state1: succ0=0 (0), succ1=1 (0) => (0,0)
state2: succ0=2 (0), succ1=2 (0) => (0,0) => all same, no split. So final class size =3. All equivalent. Indeed, for any sequence, final vertex type =0. So correct.
Test 2: n=3, types: 0:0, 1:0, 2:1.
transitions:
0: 0->0,1->1
1: 0->1,1->2
2: 0->2,1->2 (or something)
We can compute: Are 0 and 1 equivalent? They both type0. For any string w, the final type from 0 and 1 must be same. Since 2 is type1, and maybe some strings lead to 2. Let's test w='1': from 0 goes to 1 (type0), from1 goes to 2 (type1) -> types differ. So not equivalent. DFA minimization will separate them.
Our algorithm: initial partition: type0: {0,1}, type1: {2}. block ids: 0,0,1.
Iteration1: block0 {0,1}:
state0: trans: (0->0 (block0), 1->1 (block0)) => (0,0)
state1: trans: (0->1 (block0), 1->2 (block1)) => (0,1) different -> split into {0} and {1}.
So blocks: {0}, {1}, {2}. Next iteration stable. So sizes: 1,1,1. So correct.
Now, test with more complex equivalence merging.
All good.
Now, regarding input format: first line n m. Then n lines each: vi si ti. Then m lines each: qj. So we need to read accordingly.
Now, I'll implement.
But before finalizing, think about alternative approach: Since n <= 3000, we could also compute equivalences using BFS on pairs (distinguishable) as described earlier. But that may be more complex to implement correctly. So Moore's algorithm is simpler.
Implementation steps in code:
- import sys
- data = list(map(int, sys.stdin.read().split()))
- Use pointer to read.
Pseudo:
def main():
import sys
it = iter(map(int, sys.stdin.read().split()))
n = next(it)
m = next(it)
typ = [0]*n
trans0 = [0]*n
trans1 = [0]*n
for i in range(n):
typ[i] = next(it)
trans0[i] = next(it)
trans1[i] = next(it)
queries = [next(it) for _ in range(m)]
# initial partition by type
from collections import defaultdict
type_groups = defaultdict(list)
for i in range(n):
type_groups[typ[i]].append(i)
blocks = [] # list of lists
block_of_state = [0]*n
for idx, group in enumerate(type_groups.values()):
blocks.append(group)
for v in group:
block_of_state[v] = idx
# refine
while True:
new_blocks = []
new_block_of_state = [0]*n
changed = False
for block in blocks:
# if len(block) == 1: can shortcut? But we'll still compute signature for consistency; but we can skip dict if single, but overhead small.
sig_map = {}
for v in block:
sig = (block_of_state[trans0[v]], block_of_state[trans1[v]])
# use dict to group
if sig in sig_map:
sig_map[sig].append(v)
else:
sig_map[sig] = [v]
if len(sig_map) > 1:
changed = True
for group in sig_map.values():
new_id = len(new_blocks)
new_blocks.append(group)
for v in group:
new_block_of_state[v] = new_id
else:
# keep whole block
new_id = len(new_blocks)
new_blocks.append(block)
for v in block:
new_block_of_state[v] = new_id
if not changed:
break
blocks = new_blocks
block_of_state = new_block_of_state
# compute sizes
block_sizes = [len(block) for block in blocks]
out = []
for q in queries:
out.append(str(block_sizes[block_of_state[q]]))
sys.stdout.write("\n".join(out))
if name == "main":
main()
Now, test with sample.
Should work.
But we need to be careful: The initial partition based on type: if there are only two types (0/1), it's fine. But suppose there were more types? No, only binary.
Now, about integer reading: using iter and next is fine.
Now, check if there is any tricky case: The graph may have unreachable parts from some vertices? But equivalence considers all strings, regardless of reachability. So algorithm still works.
Now, ensure that the refinement algorithm indeed converges to the coarsest stable partition. This is standard.
Now, confirm that condition 2 requires sequences of length 1 or more, but we included empty in condition1. In DFA minimization, equivalence includes empty string. So it's fine.
Now, final note: The equivalence classes computed might be larger than actual if there are states that are not reachable from each other? But equivalence is defined globally, not based on reachable sets. So it's fine.
Now, let's think about a potential subtlety: In DFA minimization, it's typical to consider all strings over alphabet, but here the strings are of length at least 1. However, if two states have same type, they satisfy empty string condition. So it's the same.
Thus solution is correct.
Now, also consider if the graph could have states that are not reachable from each other? That doesn't affect equivalence.
Now, consider the possibility of multiple edges? Not allowed; each vertex has exactly one 0-edge and one 1-edge.
Now, maybe we need to consider that the graph is "concatenated" (connected) but not needed.
Now, let's run through some random small cases to test with brute force: For n small, we could compute equivalence by checking all strings up to some length? But our algorithm should match.
Now, another nuance: The problem says "For any sequence of lengths 1 or more consisting of 0s and 1s". It doesn't restrict the length. So it's infinite. The equivalence relation is based on infinite set of strings. Our algorithm handles that.
Now, we should verify that the refinement algorithm indeed yields the coarsest stable partition. It's a standard algorithm known as Moore's algorithm for DFA minimization. Starting from initial partition (based on output), repeatedly refine based on transitions. It converges to the coarsest partition that is refinement of the initial one and is transition-consistent. This corresponds to Myhill-Nerode equivalence.
So good.
Now, we can implement.
But there is a potential issue: In the refinement algorithm, we must ensure that we use the updated block ids for signature calculation within the same iteration. Our code does that: We compute signature using current block_of_state (from previous iteration) and then create new partition. This is correct.
Now, we should also consider the possibility that the number of blocks can grow up to n, and the dictionary sig_map may have many keys, but that's fine.
Now, we need to ensure that we handle large n within time; as argued, O(n^2) ~9e6, but Python's overhead for dictionary per state per iteration may be a bit higher. However, worst-case n=3000 and iterations=3000, but is that possible? Let's analyze worst-case number of iterations for Moore's algorithm. It can be O(n) but perhaps not always n=3000. In worst-case, the number of iterations may be log(n) for Hopcroft but could be O(n) for Moore. However, is it possible to have n iterations for n=3000? For that to happen, each iteration must split only one block into two, increasing block count by 1. Starting from 2 blocks, we would need n-2 splits. But can each iteration split only one block? Possibly if the automaton's structure forces that. But is it possible given that we have only two symbols? Perhaps yes. Consider a linear chain where each state i (i from 0..n-1) has transitions that lead to state i+1 mod something? But need to ensure that each state becomes distinguishable from others gradually. Let's attempt to construct a DFA where states are pairwise distinguishable and the Moore algorithm takes n-1 iterations. For DFA with binary alphabet, there exists a family called "slowly distinguishable" automata. For example, consider the DFA that accepts strings of length >= k ending with a specific pattern? Actually, there is known that Moore's algorithm can require O(n) rounds for some DFAs. So it's possible. For n=3000, that would be 3000 iterations. Each iteration does O(n) work = 9e6 total, which is fine. But note each iteration also does dictionary operations for each state, which may add overhead. 9e6 dictionary operations is fine (each insertion and lookup). Python can handle millions easily. So overall runtime should be under 1 second? Possibly a couple of seconds, but given typical contest time limits (maybe 2 sec), Python should be okay. But we can further optimize by early termination if no splits, but that's already in loop.
But we can also implement a more efficient version: Instead of recomputing signatures for all states each iteration, we could maintain those that need update, but not necessary.
Nevertheless, 3000 * 3000 = 9 million, which is fine. Even 9 million dictionary operations: each dict lookup/insert is maybe ~100 ns? Actually Python dict operations are slower, maybe ~50-100 ns? Let's estimate: 9e6 dict ops might take ~0.5-1 second. Plus other overhead, still okay.
But we should be careful that each iteration we also create new lists for blocks, copying states. That adds overhead. However, number of blocks can increase, but total size of all blocks is n. In each iteration we create new_blocks lists, which involves copying references to states. That's O(n) per iteration, so total O(n^2) references. That's okay.
Thus this implementation is acceptable.
Now, we should test with worst-case scenario. Let's try to think of a DFA that might cause many splits. For n=3000, we can test locally with random data? Not necessary.
Now, check memory: After each iteration, we reassign blocks and block_of_state. The old lists become eligible for GC. Could cause memory churn, but n small.
Now, we can also reduce overhead by using list of ints for block_of_state and avoid dict for signatures when block size is small? But fine.
Now, let's produce final answer.
But wait: The problem states: "For any sequence of lengths 1 or more consisting of 0s and 1s, the types of vertices that are finally reached when the transition is started from each of a and b are the same." Could it be that they also require that the types reached after each step? No, only final.
Now, double-check with sample: They considered vertex 0 and vertex 4: both round. They said: "Also, the number of vertices reached as a result of transitioning from these vertices by 0 or 1 is 1 or 5. Vertices 1 and 5 continue to stay at the vertices regardless of the sequence of numbers." Actually they say: "Also, the number of vertices reached as a result of transitioning from these vertices by 0 or 1 is 1 or 5." That is a bit ambiguous; but they refer to reachable vertices? Anyway.
Now, our algorithm produced the sample correctly.
Thus final solution.
Now, I'll implement as described.
But before finalizing, think about possible pitfalls: The Moore algorithm may not converge to the true Myhill-Nerode equivalence if the automaton is not complete? But it's complete. Also, it's deterministic.
Alternatively, we could use BFS on pair distinguishability. That might also be O(n^2) but with less iterations. However, I'll stick with Moore.
Now, confirm that condition 1 is same type. That is part of initial partition.
Now, about output: For each query, output one line with the number.
Now, final code.
But wait: The input specification: "v0 s0 t0" etc. So each line i: vi si ti. So we read that.
Now, we must be careful about indices: they are 0-based.
Now, final.
I'll produce solution.
But also consider potential improvement: Use list of tuples for signature to avoid dictionary overhead? Actually dictionary is fine.
Now, I'll write final answer.
Now, double-check that we treat both symbols correctly: trans[i][0] corresponds to weight 0? In input, si is "the vertex number of the transition destination by 0", and ti by 1. So yes.
Thus trans0 = si, trans1 = ti.
Now, code.
One more edge case: When initial partition has two blocks but one block is empty (if no vertex of a certain type). That's okay.
Now, final answer.
We'll present explanation of algorithm in final output: describe as DFA minimization.
Now, produce final ChatGPT answer. ```python
import sys
from collections import defaultdict
def solve() -> None:
data = list(map(int, sys.stdin.read().split()))
it = iter(data)
n = next(it)
m = next(it)
typ = [0] * n
trans0 = [0] * n
trans1 = [0] * n
for i in range(n):
typ[i] = next(it)
trans0[i] = next(it)
trans1[i] = next(it)
queries = [next(it) for _ in range(m)]
# ---- initial partition: two blocks by vertex type ----
type_groups = defaultdict(list)
for i in range(n):
type_groups[typ[i]].append(i)
blocks = [] # list of lists (current partition)
block_of = [0] * n # block index for each state
for idx, group in enumerate(type_groups.values()):
blocks.append(group)
for v in group:
block_of[v] = idx
# ---- refine using Moore's algorithm ----
while True:
new_blocks = []
new_block_of = [0] * n
changed = False
for block in blocks:
# group states inside this block by their signature
sig_map = {}
for v in block:
sig = (block_of[trans0[v]], block_of[trans1[v]])
if sig in sig_map:
sig_map[sig].append(v)
else:
sig_map[sig] = [v]
if len(sig_map) > 1: # split the block
changed = True
for group in sig_map.values():
new_id = len(new_blocks)
new_blocks.append(group)
for v in group:
new_block_of[v] = new_id
else: # keep the whole block
new_id = len(new_blocks)
new_blocks.append(block)
for v in block:
new_block_of[v] = new_id
if not changed:
break
blocks = new_blocks
block_of = new_block_of
# ---- answer queries ----
block_sizes = [len(block) for block in blocks]
out_lines = [str(block_sizes[block_of[q]]) for q in queries]
sys.stdout.write("\n".join(out_lines))
if name == "main":
solve()