We are asked: We have n beavers numbered 1..n. They are standing in a queue (some order). But the queue is messy. For each beaver i, we know a_i: the number of the beaver that should be directly in front of him in the queue. That is, if a_i != 0, then beaver i stands immediately after beaver a_i. So a_i is the predecessor of i. If a_i = 0, we don't know who is in front of i. It's given that the dependencies (a_i) are correct: no cycles, and each beaver has at most one predecessor (which is natural for a queue: each person has exactly one person before them except the head, but here a_i can be 0 meaning unknown, but also any beaver may not be referenced as predecessor? Actually in a queue, each person except first has exactly one person before them. But here we are given that a_i indicates the person directly in front of i. So for a valid queue, the a_i must define a linked list from head to tail: one node with a_i = 0 (head), and for each other node, a_i is the node before them, and each node can be the predecessor of at most one node (since only one after). The input is guaranteed to be correct: there is no cycles and each beaver is followed by at most one beaver (i.e., the out-degree from a node as predecessor is at most 1). However it doesn't guarantee that all nodes appear exactly once? Actually for a full queue of all n beavers, we must have that the a_i links form a single chain containing all nodes exactly once. But is it guaranteed that the given a_i defines a correct queue? The problem says: "It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue." That means the directed graph with edges (i -> a_i when a_i != 0) is a collection of chains (since each node has indegree at most 1? Actually a_i gives predecessor, so edges are from i to a_i, meaning that a_i points to i's predecessor. So each node can have at most one outgoing edge? Actually i has exactly one a_i, but a_i may be 0 meaning no outgoing? Actually each i has an a_i, but if a_i != 0, then that is an outgoing edge from i to a_i. So each node can have at most one outgoing edge (since a_i is single). Indegree: a node j could be a_i for many i? But it says "any beaver is followed by at most one beaver in the queue" meaning that at most one i has a_i = j. That is, the indegree of j (as predecessor) is at most 1. So we have a collection of node-disjoint chains (or paths) because each node has at most one outgoing (to predecessor) and at most one incoming (from successor). Actually outdegree <= 1 (since a_i is defined, but could be 0 meaning no outgoing), indegree <= 1 (since at most one i has a_i = j). So the structure is a set of vertex-disjoint chains (including possibly isolated nodes as chains of length 1). But there is also no cycles. So overall, the known links define some segments of the queue. Some segments are fully connected chains with known order, while some nodes have a_i=0 meaning they are the head of a chain (or unknown predecessor). However, it's also possible that a node has a_i != 0 but its predecessor might be unknown in the sense that it's given? Actually a_i !=0 gives a direct link; that link must be respected.
We are given that the queue actually exists as a permutation of 1..n respecting these known predecessor relations. That is, there is a total order of all beavers such that for each i, if a_i != 0, then a_i is immediately before i. Since the known links are correct (no cycles, each at most one predecessor/successor), such a total order exists? Not necessarily unique; there could be multiple possible queues consistent with the given constraints. The problem asks: given that the Smart Beaver is number x, and we have this ambiguous queue, we need to determine all possible positions (i.e., his index in the queue from front to back? Usually position 1 is the front, first to be served). Since the queue is a line, position numbers start from 1 at the head. We need to output all possible positions (as integers) that the Smart Beaver could be in, consistent with the constraints.
Input constraints: n <= 1000. a_i given. For subproblem B1 (30 points), number of zeros <= 20. For full (100 points), arbitrary zeros. But n is only 1000, so we can do exponential in zeros maybe? But zeros <= 20 gives exponential; full zeros arbitrary up to 1000, we need polynomial solution. But n is only 1000, so we can perhaps do DP.
We need to consider all ways to arrange the beavers into a single queue (a permutation) such that for every i, if a_i != 0, then i must appear immediately after a_i. Essentially we have fixed adjacencies: for each i with a_i != 0, the pair (a_i, i) must be consecutive in that order. That defines certain constraints: certain pairs are forced to be adjacent. This creates chains (segments) that must appear as contiguous blocks. The unknown parts are the connections between these chains and also isolated nodes (which are chains of length 1). The queue must be a concatenation of these blocks in some order, respecting the orientation (the blocks are directed: head to tail). Within each block, order is fully determined (since it's a chain: we know the predecessor relationships recursively). But note: the chains might not be maximal? Actually given the links, we can reconstruct maximal chains: start from any node with indegree 0? Wait, a_i gives predecessor, so node i has an outgoing edge to a_i. So for a chain from head to tail: head has a_i = 0 (unknown predecessor). The tail (last) is a node that is not a predecessor of anyone (no node j has a_j = tail). Because each node's predecessor is given; the node with no successor (i.e., not referenced as a_i by anyone) is the tail of its chain. So each node belongs to a unique chain where head is the node that has a_i = 0, and following successors: we need to traverse from head via reverse direction? Actually easier: Build graph: for each i with a_i != 0, we have an edge from a_i to i (meaning a_i is before i). So that is a directed edge from predecessor to successor. So we can treat it as a directed chain. For each node, we can find its predecessor (a_i) and its successor (if any j such that a_j = i). So we can compute for each node, whether it is a head (no predecessor) or tail (no successor). Chains are these maximal sequences where each consecutive pair is linked. Since indegree and outdegree <=1, and no cycles, each connected component is a chain. However, note that a head might have a_i = 0 (unknown predecessor). But it's possible that a node has a_i = 0, but it also has a successor? Yes, it can be head of a chain. Similarly, a node with a_i != 0 may be head? Actually if a_i != 0, then it has a predecessor, so it's not head. So heads are exactly nodes with a_i = 0. Tails are nodes with no successor (i.e., not any j with a_j = i). So we can partition all nodes into K chains. Within each chain, order is fixed: from head to tail.
Now, the queue is formed by concatenating these K chains in some order (any permutation of chains). However, there might be additional constraints? None. Because the only constraints are the immediate adjacencies inside each chain. There is no constraint about relative order between chains. So any concatenation is valid. But is there any additional condition from "queue is a permutation of all beavers"? Yes, we must include all beavers exactly once. So the concatenation of chains in any order yields a permutation that respects the fixed adjacencies. Are there any possibilities of merging chains by linking them together? For example, if we have two chains, could we insert a node between them? No, because if we put a chain A then chain B, the connection between the tail of A and head of B is not constrained; that's allowed. So indeed any ordering of chains yields a valid queue.
But wait: consider a node i with a_i=0 meaning unknown predecessor. That does not forbid that some other node j might be placed immediately before i. Since a_i=0 means we don't know who is before i, but it could be anyone (or none if i is at head). However, if we put someone before i, then that would set a predecessor for i, but a_i=0 indicates we have no information; it could be that actually there is a predecessor but we don't know. So the constraint is that if a_i != 0, then the predecessor must be exactly that beaver. If a_i = 0, there is no constraint, i.e., i can have any beaver before it or none (if placed at head). So the interpretation: For i with a_i=0, we are free to assign any predecessor (or none). But our model of concatenating chains assumed that heads have a_i=0, but also that we cannot insert any node between the head and the rest? Actually, if a_i=0, that node i is a head of its chain, but we could also potentially attach it as successor to some other node (by merging chains) because that would assign a predecessor to i, contradicting a_i=0? Wait: a_i=0 means the beaver i does not know who is in front of him. That is, the actual queue may have someone in front of i, but i does not know who. So it's not that a_i=0 means "no predecessor" as a constraint; it's a lack of information. So the actual queue must satisfy that for each i, if a_i != 0 then that a_i is directly in front. If a_i = 0, there is no constraint: the predecessor could be any beaver (including none if at front). So i with a_i=0 could be placed anywhere: as head (no predecessor) or after some other beaver. But if we place i after some j, then that would set a_i' to j, but since a_i is 0, it's okay: the given a_i is 0, meaning i reported that he doesn't know his predecessor; that doesn't contradict the actual predecessor being j. So i with a_i=0 can be placed anywhere, not necessarily as head. However, there is a nuance: The statement "It is guaranteed that values ai are correct. That is there is no cycles in the dependencies. And any beaver is followed by at most one beaver in the queue." This suggests that the given a_i represent actual relationships? Actually they represent what each beaver reported: i says the beaver in front of him is a_i; if he doesn't know, a_i=0. And it's guaranteed that these reports are correct? The phrase "values ai are correct" might mean that they are consistent with some actual queue. In other words, there exists at least one queue that satisfies all a_i (for non-zero) as actual predecessor relationships. And also it's guaranteed that no cycles, and no two beavers claim the same predecessor (since at most one can be followed by a beaver). So the a_i's are not necessarily describing the full queue; they are partial constraints. So for each i with a_i !=0, we must have that a_i is immediately before i. For i with a_i=0, there is no constraint; i's predecessor can be any beaver or none. So our chain model: we have forced edges (a_i -> i). Since each node has at most one predecessor constraint (indegree <=1) and each node can be predecessor to at most one (outdegree <=1) as per the condition, the forced edges form a set of disjoint chains (including length 1 nodes? Actually nodes with a_i=0 are not forced to have a predecessor; they could be isolated or they could be attached as successors to other nodes? Wait, if a node i has a_i != 0, it has a forced incoming edge. But a node with a_i = 0 has no forced incoming edge. However, it could have a forced outgoing edge? It could be a predecessor for some j (if some j has a_j = i). That would be a forced outgoing edge from i. So i could be part of a chain as a head if it has a_i=0 but maybe some j with a_j=i, then i is head of a forced chain: i -> ...? Actually the forced edges are directed from predecessor to successor: for each j with a_j != 0, we have an edge from a_j to j. So i could be a predecessor (source) of such edge if some j has a_j = i. So forced edges create chains where nodes may have indegree 1 (if they are successor in a forced edge) or outdegree 1 (if they are predecessor). Nodes with indegree 0 (i.e., no forced edge pointing to them) are not forced to have any particular predecessor; these are nodes i such that for all j, a_j != i. That includes heads of forced chains (if they have outdegree 1 but indegree 0) and also isolated nodes (no incoming or outgoing). Nodes with outdegree 0 (i.e., no j such that a_j = i) are tails of forced chains.
So the forced edges define several forced chains (maximal sequences where each consecutive pair is forced). But note that nodes with a_i=0 that also have no outgoing edge (i.e., not referenced as a predecessor) are isolated; they have no forced adjacency at all. They can be placed anywhere.
Now, the crucial part: While forced chains must appear as contiguous subsegments (with internal order fixed), they can be placed in any order relative to each other. However, can they be interleaved? Could we, for example, insert a node between two nodes of a forced chain? No, because that would break the forced adjacency. So forced chains must remain intact as blocks. But also, can we merge chains by linking them? For example, suppose we have two forced chains: chain A: ... -> a_tail; chain B: b_head -> ... . Could we place chain B immediately after chain A? That would mean a_tail is directly followed by b_head. Is that allowed? Yes, because there is no constraint preventing that. But note: if we do that, then b_head (which might have a_i=0, i.e., no forced predecessor) now gets a predecessor a_tail. That's okay because b_head's a_i is 0, meaning no constraint on its predecessor. However, if b_head has a_i != 0, then b_head is not a head; it's part of a forced chain already: it has a forced predecessor. So chain B's head must be a node with a_i=0 (no forced predecessor) or maybe a node that is not forced to have a predecessor (i.e., indegree 0). Actually any node that is the first element in a forced chain is a node with indegree 0. That includes nodes with a_i !=0? Wait, if a node i has a_i != 0, then it has indegree 1 (since a_i is a forced edge). So it cannot be head. So heads are exactly nodes with indegree 0. Tails are nodes with outdegree 0.
Thus forced chains are segments where internal order fixed; each chain has a head (indeg 0) and tail (outdeg 0). The heads may have a_i = 0 (since if indeg 0, it's possible that a_i = 0? Actually a_i is the node's own reported predecessor. For a head, indegree 0 means no one claims this node as successor. But the node itself may have a_i = something (non-zero) if it has a forced predecessor? Wait, indegree refers to being someone's predecessor? Let's be careful: The forced edges are from predecessor p to successor s, where s has a_s = p. So indegree of a node x is the number of s such that a_s = x. So indegree(x) = count of successors that point to x as predecessor. Outdegree of node x is 1 if a_x != 0 (since it points to a_x), else 0. Actually outdegree from x is whether it has a known predecessor: if a_x != 0, then x points to a_x, meaning x has an outgoing edge to its predecessor? Actually the edge direction is from x to a_x if we view it as "x knows its predecessor". But for the chain, it's more natural to think of the queue order: predecessor -> successor. So if a_x = y, then y is before x, so there is a directed edge from y to x. So we could define a directed edge from y to x when a_x = y. That edge indicates that y must be immediately before x. So from this perspective, each node x may have indegree 1 if there exists some i with a_i = x (i is its successor). And outdegree 1 if a_x != 0 (x has a predecessor). So heads are nodes with outdegree 0? Actually head of the chain is the node with no predecessor, i.e., a_x = 0, so outdegree 0. But indegree may be 1 or 0. Tails are nodes with indegree 0 (no successor). Wait, let's reconcile: In a chain, the first element (head) has no one before it: a_head = 0. So outdegree of head (the edge from head to its predecessor) is 0 (since a_head = 0). The last element (tail) has no one after it: there is no i such that a_i = tail. So indegree of tail is 0. So in a forced chain, head has outdeg 0, tail has indeg 0. So the chain direction: from head to tail, via edges: head's successor is some node i with a_i = head; that node's successor etc.
Thus forced chains are defined as maximal sequences such that for each consecutive pair (prev, next), a_next = prev. So start from a node with a_node = 0 (outdeg 0) and follow successors until a node that is not anyone's predecessor (indeg 0). So these forced chains are determined by the constraints.
Now, the queue must be a permutation that respects these forced adjacencies. So the forced chains must appear as contiguous blocks, and the blocks can be concatenated in any order. Additionally, can we have nodes that are not part of any forced chain? That is, nodes that have both a_i = 0 and are not anyone's predecessor? Those are isolated nodes: outdeg 0 and indeg 0. They can be placed anywhere as individual blocks of size 1. They are essentially chains of length 1. So all nodes belong to exactly one chain (forced or isolated). So total K chains.
Now, the queue is an ordering of these K chains. Within each chain, order is fixed (head first, tail last). So the full queue is determined by a permutation of chains.
Now, we are asked: given x, what positions (1-indexed from head) can x occupy in the queue, considering all possible orderings of chains?
But careful: Could there be additional flexibility? For a node with a_i = 0, it might be placed not as head of a chain if we decide to attach it after some other node? But that would effectively merge chains. However, if we attach a chain after another chain, that is exactly concatenating them: we take chain A and then chain B; that yields a block where the tail of A is before head of B. That's allowed because head of B has no forced predecessor, so we can put anyone before it. So it's just concatenation of chains. However, could we also insert a node between two nodes of a forced chain? No, that would break forced adjacency. Could we insert a node in the middle of a forced chain by reordering? No, because forced edges require immediate adjacency. So the chain must stay contiguous. Could we reverse the order of a chain? No, because the forced edges specify direction: head before tail. So chain order is fixed.
Thus the problem reduces to: We have K blocks (chains). Each block i has a size s_i (number of nodes in that block) and a known order within. For each block, we know the positions of nodes inside relative to block start. The beaver x is located in some block, at a certain offset from the start of that block (i.e., if block has nodes in order, we know x's index within that block: if x is at position p within its block (1-indexed from block head), then when the block is placed at some overall position in the queue, x's overall position = (sum of sizes of blocks placed before) + p.
Thus x's possible overall positions are determined by the possible sums of sizes of blocks that can appear before its block, over all permutations of blocks. Additionally, is there any constraint that might restrict ordering of blocks? Could there be constraints that some block must be before another due to indirect dependencies? For example, if we have a node i with a_i = 0 but we have some other node j that has a_j = i? That would make i part of a chain: i is head? Actually if a_j = i, then i is before j forced. That's already inside the chain. So no cross-block constraints beyond the forced edges: because forced edges are all inside a block; blocks are maximal forced chains. So no constraints between blocks. So all permutations of blocks are valid. However, is that always true? Consider scenario: There is a node i with a_i = 0 (head of its block) and there is another node j with a_j = 0, but we could also place i after j, or j after i, arbitrarily. Yes. But wait: There is also the condition "any beaver is followed by at most one beaver in the queue". That is automatically satisfied if we respect forced edges because each node can have at most one successor (since each node is predecessor for at most one i). However, if we concatenate blocks, we are creating new adjacency between tail of one block and head of the next. This sets the tail's successor to the head. But is that allowed? It would mean tail now has a successor (the head), even though maybe tail already has a forced successor? Actually tail by definition has indegree 0 (no forced successor). But tail could have a forced predecessor? Tail has outdegree? Tail is the end of a forced chain; it has no forced successor, meaning there is no j such that a_j = tail. So it's free to have any successor (or none) in the queue. So placing another block after it gives tail a successor, which is fine. Similarly, head has no forced predecessor, so it's fine to have a predecessor. So concatenating blocks creates new adjacencies not specified, which is allowed because they are not constrained (only the forced ones must hold). So all permutations are indeed valid.
But is there any scenario where two blocks cannot be adjacent because that would create a conflict with some a_i? For example, suppose we have a block A with tail t, and block B with head h. If we put A before B, then t is immediately before h. That's fine. However, could there be a situation where t has a_i = something? t's a_t may be non-zero (t has a predecessor) but that's within its block. No conflict. So yes, all permutations allowed.
Thus the problem seems straightforward: compute the blocks (chains), determine for each block its size, and within each block, the position of x if it belongs to that block. Then the set of possible overall positions is { p + sum_{blocks before} sizes } for any ordering where the block containing x can be placed at any position among the blocks. Since there are no restrictions, the set of possible overall positions is all integers of the form: offset = (sum of sizes of some subset of the other blocks placed before x's block) + p, where the subset can be any combination of the other blocks? But careful: In a permutation of K blocks, the blocks before x's block are exactly a subset of the other blocks, but they must appear in some order, and the total size is the sum of the sizes of those blocks. However, the order of blocks before doesn't matter, only the total sum of sizes matters for x's position. Since we can permute arbitrarily, can we achieve any subset of the other blocks before x? Let's think: In a permutation, the set of blocks that appear before a given block is exactly some subset of the other blocks. Conversely, any subset of the other blocks can be placed before x's block (by ordering them arbitrarily before, then x's block, then the rest). Since there is no restriction on order, yes we can arrange to have any desired set of other blocks before x. So the possible sums are p + S, where S ranges over all possible sums of sizes of any subset of the other blocks (i.e., the multiset of sizes of blocks except the one containing x). That includes 0 (empty subset) up to total sum of sizes of all other blocks. But is every integer sum achievable? The sizes are integers. Since we can choose any subset, the set of achievable sums is the set of all subset sums of the sizes of the other blocks. That's not necessarily all integers from 0 to total, because subset sum can have gaps. However, we need to output all possible positions, i.e., all achievable sums + p. So we need to compute the subset sum set of the sizes of other blocks. But n <= 1000, number of blocks K could be up to n (if all isolated). So we have up to 1000 numbers (sizes). Their total sum is n (since all nodes belong to exactly one block). Subset sum of up to 1000 numbers (each up to n) can be computed via DP (bitset or boolean array) in O(n * total) = O(n^2) = 1e6 which is fine. But we need to output all positions in increasing order, which are the sums + p. So we can compute all possible sums from other blocks, then add p.
But wait, is it always true that any subset of other blocks can appear before x's block? Yes, because we can order blocks arbitrarily. There's no additional constraint like the order within a block must be fixed, but we can put any set of blocks before x's block. However, note that blocks themselves are indivisible, but we can intermix? Actually we cannot interleave nodes of different blocks; blocks are contiguous. So permutation of blocks is exactly an ordering of the blocks. So for a given block containing x, we can place any selection of the other blocks before it, and the rest after. So the set of sums is exactly all subset sums of sizes of other blocks. So the answer would be: For each possible subset sum S, position = S + pos_in_block. But we must ensure that the total number of possible positions is not too many; total n possible positions, but output should be all distinct positions in increasing order. So we can compute a boolean array possibleSum[0..n] for sums from other blocks, then output all i such that possibleSum[i - pos] is true, where i ranges from 1..n.
But is this always correct? Let's test with examples.
Example 1:
n=6, x=1.
a = [2,0,4,0,6,0] (list a1..a6). Let's index from 1.
Beaver 1: a1=2 => 2 is before 1.
Beaver 2: a2=0 => head? Also check if any beaver has a_j=2: Beaver1 has a1=2, so 2 is predecessor of 1, so 2 has a successor 1. So chain: 2 ->1. For 2, a2=0, so 2 is head. So block1: [2,1] (size 2, order: 2 then 1).
Beaver3: a3=4 => 4 before 3.
Beaver4: a4=0 => head? Check if any j has a_j=4: Beaver3 has a3=4, so 4 has successor 3. So chain: [4,3] size 2.
Beaver5: a5=6 => 6 before 5.
Beaver6: a6=0 => head? Beaver5 has a5=6, so 6 successor 5. So chain: [6,5] size 2.
We have three blocks of size 2 each. x=1 is in block1, at position 2 within its block (since block order: 2 then 1). So pos_in_block = 2.
Other blocks sizes: [2,2] (two blocks of size 2). Subset sums: 0,2,4. Adding 2 yields positions: 2,4,6. Output: 2 4 6. Matches example.
Example 2:
n=6, x=2.
a = [2,3,0,5,6,0].
Let's compute:
Beaver1: a1=2 => 2 before 1.
Beaver2: a2=3 => 3 before 2.
Beaver3: a3=0.
Beaver4: a4=5 => 5 before 4.
Beaver5: a5=6 => 6 before 5.
Beaver6: a6=0.
Now also check incoming:
- Who has a_j =1? None? Beaver1 says a1=2, so 2 points to 1? Actually a1=2 means 2 is before 1, so 1 has predecessor 2, and 1 may be successor of 2. So 1 is successor of 2. Also any j with a_j =1? None.
- For 2: a2=3 => 3 before 2, so 2 is successor of 3. Also beaver1 has a1=2, so 2 is predecessor of 1. So 2 has both predecessor (3) and successor (1). So it's internal in a chain.
- For 3: a3=0 => head. Also beaver2 has a2=3, so 3 is predecessor of 2. So chain: 3->2->1? Check: 3 precedes 2, 2 precedes 1. So chain: [3,2,1] size 3.
- For 4: a4=5 => 5 before 4, so 4 is successor of 5.
- For 5: a5=6 => 6 before 5, so 5 is successor of 6. Also beaver4 has a4=5, so 5 predecessor of 4.
- For 6: a6=0 => head. So chain: [6,5,4] size 3.
Thus two blocks: block A size 3 with order: 3,2,1; block B size 3 with order: 6,5,4.
x=2 is in block A. Its position within block A: block A order: 3 (pos1), 2 (pos2), 1 (pos3). So pos_in_block = 2.
Other block size = 3.
Subset sums of other block: 0 and 3. So positions: 2 and 5. Output: 2 5. Matches example.
Example 3:
n=4, x=1.
a = [0,0,0,0].
All a_i=0, so no forced edges. Each beaver is isolated block of size 1. So K=4 blocks all size 1. x=1 is in a block of size 1, pos_in_block=1. Other blocks sizes: three 1's. Subset sums from other blocks: possible sums are 0,1,2,3 (since any number of 1's can be chosen). Adding 1 yields positions 1,2,3,4. Output: 1 2 3 4. Matches.
Example 4:
n=6, x=2.
a = [0,0,1,0,4,5].
Compute:
Beaver1: a1=0.
Beaver2: a2=0.
Beaver3: a3=1 => 1 before 3.
Beaver4: a4=0.
Beaver5: a5=4 => 4 before 5.
Beaver6: a6=5 => 5 before 6.
Now check incoming:
- For 1: a1=0; but beaver3 has a3=1, so 1 is predecessor of 3. So 1 has successor 3, no predecessor? a1=0 so no forced predecessor. So chain: maybe 1->3? But also, does 1 have any other? So block: [1,3] size 2? Wait, we need to follow successors: start from head (a=0). Node 1: a1=0, so head. It has successor? Yes, node 3 has a3=1, so successor is 3. Node 3: a3=1, its successor? Does any j have a_j=3? None. So block A: [1,3] size 2.
- For 2: a2=0. Does any j have a_j=2? None. So isolated block size 1: [2].
- For 4: a4=0; node 5 has a5=4, so 4 is predecessor of 5. Node 5: a5=4; node 6 has a6=5, so successor of 5 is 6? Actually a6=5 means 5 before 6, so 5's successor is 6. Node 6: a6=5; any j with a_j=6? None. So block B: [4,5,6] size 3.
Thus blocks: size2 (1,3), size1 (2), size3 (4,5,6). x=2 is in the size1 block, pos_in_block=1. Other blocks sizes: 2 and 3. Subset sums: possible sums from set {2,3} are 0,2,3,5. Adding 1 yields positions: 1,3,4,6. Output: 1,3,4,6. Matches example.
So our reasoning works for given examples.
Thus the problem reduces to: find all forced chains (blocks), compute size of each block and the position of x within its block. Then compute all possible subset sums of sizes of other blocks, and output (sum + pos_in_block) sorted.
But wait, are there any hidden constraints? Let's double-check the problem statement carefully: "the number of the beaver followed by the i-th beaver." Actually translation: "the number of the beaver followed by the i-th beaver." Wait: maybe it's "the number of the beaver that is in front of the i-th beaver"? The phrasing: "the number of the beaver followed by the i-th beaver." In Russian context, "followed by" could mean "the beaver that follows i"? Let's read original statement: "The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ n) — the number of the beaver followed by the i-th beaver." This is ambiguous: does "followed by" mean the beaver that comes after i? Or the beaver that i follows? Typically in queues, "followed by" suggests the beaver behind i. However, in examples, we interpreted as "the beaver that is immediately before i". Let's test with example 1: n=6, x=1; a: 2 0 4 0 6 0. If a_i is the beaver that follows i (i.e., the one behind i), then for beaver1, a1=2 means beaver2 is behind beaver1. Then dependencies: 1->2. For beaver2, a2=0 means no one behind him. For beaver3: a3=4 -> 4 behind 3. For beaver4: a4=0. For beaver5: a5=6 -> 6 behind 5. For beaver6: a6=0. Then we have chains: 1->2, 3->4, 5->6. Then the queue would be (head?) Actually, the direction: if a_i denotes successor, then each node can have at most one successor (since at most one can follow him). And each node can have at most one predecessor? Actually, there is also condition: "any beaver is followed by at most one beaver" i.e., at most one beaver can follow a given beaver. That matches the interpretation that a_i is the beaver that follows i. And also "if ai = 0, then the i-th beaver doesn't know who is should be in front of him." Wait, the phrase says "who is should be in front of him." That seems contradictory. Let's parse the original problem from Codeforces? Actually this is Codeforces problem 331B2? Let's recall: There is a known problem "Shave Beaver" maybe? Actually I think this is Codeforces Round? Might be problem "Queue" or "Beaver" something. Let's search memory: There is a problem "Queue" by Smart Beaver? Maybe it's "Little Beaver and the queue"? Actually I recall a problem "Little Elephant and Queue"? Not sure.
Better to examine the examples with both interpretations.
Interpretation A: a_i is the beaver that i follows (i.e., predecessor). Then as we did, it matches examples.
Interpretation B: a_i is the beaver that follows i (successor). Then let's test example 1 with interpretation B:
n=6, x=1
a = [2,0,4,0,6,0]
If a_i is successor, then:
- Beaver1 says his successor is 2, so 1 is before 2.
- Beaver2 says 0, so he doesn't know his successor (maybe tail).
- Beaver3 says successor 4 -> 3 before 4.
- Beaver4 says 0.
- Beaver5 says successor 6 -> 5 before 6.
- Beaver6 says 0.
Thus we have chains: 1->2, 3->4, 5->6. These are three chains of size 2 each. x=1 is in chain 1->2, at position 1 (head). The other chains sizes 2 each. Subset sums: 0,2,4 => positions: 1,3,5? Actually if we place chains in any order, the position of beaver 1 depends on how many nodes are before its chain. For chain of size 2, if placed first, position 1; if after one chain of size 2, then positions of chain start at 3? Actually if one chain of size 2 is placed before, then beaver1's position = 2 (from previous chain) + 1 = 3; if two chains before, position = 4+1=5. So possible positions: 1,3,5. But the output given is 2,4,6. So interpretation B gives 1,3,5, which does not match. So interpretation A (a_i is predecessor) is correct. Also note the phrase: "who is should be in front of him" suggests a_i indicates the beaver in front of i (i.e., predecessor). And "any beaver is followed by at most one beaver" means each beaver can have at most one beaver following him (i.e., at most one successor). In our earlier analysis, we used that each beaver can be followed by at most one (i.e., at most one j such that a_j = i). So indeed a_i indicates predecessor. The condition says "any beaver is followed by at most one beaver", which means for any beaver j, there is at most one i such that a_i = j (i.e., at most one beaver has j as predecessor). So correct.
Thus our modeling is correct.
Now, the problem mentions subproblem B1 with zeros <=20, and B2 with arbitrary zeros. However, our solution using subset sums works for arbitrary zeros, because number of blocks can be up to n (1000) and we can compute subset sums DP in O(n^2) which is fine (1e6). But note: The DP on subset sums of sizes of other blocks might have complexity O(K * n) = O(n^2) ~ 1e6, which is okay.
But there is a nuance: Are there any other possibilities where x could be placed in a position that is not simply determined by block ordering? Could the block containing x be split? No, because it's forced chain and must remain contiguous. Could we have multiple instances of the same block? No.
Thus answer is subset sums.
But wait, is it always that we can choose any subset of other blocks to be before? Yes, because we can order blocks arbitrarily. However, is there any situation where two blocks cannot be placed arbitrarily due to the fact that some block's head has a_i = something that might create a conflict if placed after a particular block? No, because no constraints cross blocks.
Thus the solution is straightforward: find blocks via graph traversal, compute sizes and x's offset within its block. Compute subset sums of sizes of other blocks using DP (bitset or boolean array). Output positions = offset + sum for each reachable sum.
Let's test edge cases:
-
x may be in a block where its position is not necessarily at some fixed offset? But within block, order is fixed, so offset is known.
-
What if x is in a block where the block is of size > 1, but could the block be reversed? The constraint is that a_i gives predecessor. So if a_i = j, then j must be immediately before i. That means in the order, j comes right before i. So the direction is fixed: j before i. So block order is fixed from head to tail. No reversal.
-
Could there be a scenario where some block is not maximal because we could combine blocks by linking them? For example, suppose we have two blocks: block A: head a (a_i=0) tail a_t; block B: head b (b_i=0) tail b_t. Could we also place block B immediately before block A? That would put b_t before a. That's allowed. But does that create a new adjacency that might violate something? No. However, could we merge them into a single block by making a_t have b as successor? That is exactly concatenation; they become one larger block but not forced adjacency. But in our model, blocks are defined by forced adjacencies. Concatenating blocks does not create a forced adjacency; it's just a free adjacency. So the blocks themselves remain as units; but after concatenation, they form a larger segment, but within that segment the forced blocks are still contiguous. So it's fine.
Thus answer stands.
But wait, there is one more nuance: The problem says: "The input limits for scoring 30 points are (subproblem B1): It is guaranteed that the number of zero elements ai doesn't exceed 20." In those cases, number of zeros is small, which means many constraints, so number of blocks is small? Actually zeros correspond to heads: each head has a_i=0. So number of blocks = number of zeros. Because each chain starts with a node with a_i=0. Indeed, each block's head has a_i=0. Also isolated nodes have a_i=0 and are heads as well. So K = number of zeros. So if zeros <=20, then K <=20. Subset sum DP would be trivial. For B2, zeros arbitrary, K could be up to n (like all zeros). But our DP works for n=1000.
Thus solution: O(n) to compute blocks, O(n^2) DP.
But we must be careful: The DP must consider sizes of all blocks except the one containing x. Let M = sum of sizes of other blocks = n - size_of_x_block. That's <= n. DP array of size n+1 boolean. DP[0]=true. For each other block with size s, we update DP in reverse for subset sums (standard knapsack). Complexity O(K * n) ~ 1e6.
Implementation steps:
- Read n, x.
- Read array a[1..n].
- Build adjacency for successors: For each i, if a[i] != 0, then add edge from a[i] to i. Actually we need to construct the chains. Since each node has at most one predecessor (incoming) and at most one successor (outgoing). We can compute:
- predecessor[i] = a[i] (0 if none)
- successor[i] = j such that a[j] == i, if exists (or 0)
But careful: Since multiple nodes could have a_i = same? Condition says at most one beaver is followed by any beaver, i.e., for each j, at most one i with a_i = j. So successor[i] is uniquely defined if exists.
We'll have arrays pred[i] = a[i] (0 if unknown), succ[i] = 0 initially, then for each i if a[i] != 0, set succ[a[i]] = i (if there is already a succ, but condition ensures at most one, so it's fine).
Now, we need to partition nodes into chains. We can start from each node i with pred[i]==0 (head) and follow succ links to build chain. This yields all chains. Keep a visited array to avoid double counting.
For each chain, compute:
- list of nodes in order from head to tail.
- size = length.
- for each node, record its position within chain (1-indexed) and also the chain id.
Find chain containing x, record its size (sz_x) and position of x within that chain (pos_x). Also record sizes of other chains.
But careful: Chains might have nodes with pred[i]==0? That's the definition. However, what about nodes that are part of a chain but not visited from a head? Since there are no cycles, all nodes will be in a chain starting from a head (pred==0) and ending at a node with succ==0). However, there might be nodes that are isolated: pred==0 and succ==0; they will be a chain of length 1.
One nuance: Could there be nodes that are not reachable from a head because they have pred != 0 but are not connected to a head? That would imply a cycle or infinite chain? But since no cycles and each node has at most one predecessor, if we start from any node and follow pred links backwards, we must eventually reach a node with pred==0. Because if we keep going pred, we cannot cycle, and n finite, so we must reach a node with pred==0. So all nodes are in some chain rooted at a head. So our method works.
We'll compute chains by iterating over all nodes i where pred[i]==0, and then traverse succ to build chain.
Now, we have list of sizes of other chains.
Now compute subset sums DP.
DP array size n+1 (maybe up to n). Initially dp[0]=true.
For each size s in other_sizes:
for sum from n-s down to 0:
if dp[sum]: dp[sum+s] = true.
After processing, we have all possible sums S that can be achieved by summing sizes of a subset of other chains. However, is it necessary that we can achieve any subset? Because the order of blocks is a permutation, the set of blocks before x's block is exactly some subset. There is no restriction that prevents us from selecting any subset. So all subset sums are achievable.
But wait: Could there be a scenario where two blocks are forced to be in a specific order relative to each other? For example, consider a situation where we have two heads, but also there is a condition that one beaver "doesn't know" his predecessor, but maybe there is indirect constraint? The constraints only specify immediate predecessor relations. There is no other constraints. So yes.
Thus answer set = { pos_x + S | S is achievable sum }.
We need to output each possible position in increasing order. Since n <= 1000, we can just iterate i from 1 to n, check if dp[i - pos_x] is true (and i-pos_x between 0 and n). But also ensure that the total sum of other sizes = n - sz_x, so i cannot exceed n. So iterate i = pos_x .. n? Actually i must be between 1 and n inclusive. For each i, check if (i - pos_x) >= 0 and (i - pos_x) <= n, and dp[i - pos_x] is true. But we also need to ensure that the subset sum of other sizes exactly i - pos_x is achievable. However, note that the maximum sum of other sizes is total_other = n - sz_x. So i - pos_x must be <= total_other. Also i - pos_x >=0. So iterate i from pos_x to pos_x + total_other, and check dp[i - pos_x]. However, we must also consider that the overall position must be valid, i.e., between 1 and n. So that's fine.
But caution: When we compute dp, we only considered sums up to total_other. So we can just iterate S from 0 to total_other, if dp[S], output pos_x + S.
Make sure to sort? dp already gives increasing order if we iterate S ascending.
Edge Cases:
- What if x is in a block with size sz_x, but pos_x could be any from 1 to sz_x. That's fixed.
- If there are multiple blocks, we just compute.
But wait: The problem might be more subtle: Are we sure that all subsets of other blocks are achievable? In a permutation, the set of blocks before a given block is exactly a subset. Yes.
But could there be blocks that must be placed before or after due to the fact that their internal order might conflict? No.
Thus solution done.
But let's double-check with some tricky cases.
Case: n=3, a = [2,3,0]. That is: 1 says 2 before 1, 2 says 3 before 2, 3 says 0. This yields chain: 3->2->1? Let's see: For 1: pred=2; 2: pred=3; 3: pred=0. So head is 3, succ[3]=2? Actually we need succ: from 3, who has a_i=3? 2 has a_2=3, so succ[3]=2. From 2, who has a_i=2? 1 has a_1=2, so succ[2]=1. So chain: 3,2,1. So size 3. Only one block. x could be any. For x=1, pos_x=3, other blocks empty. Subset sum only 0. So possible positions: 3. Is that valid? Yes, only queue order is 3,2,1. For x=2, pos_x=2 => position 2. For x=3, pos_x=1 => position 1. Good.
Case: n=3, a = [0,1,0]. Means: 1 pred=0, 2 pred=1, 3 pred=0. So chain1: 1->2 (head 1, succ[1]=2, tail 2). Chain2: 3 (head 3). Sizes: blockA size 2, blockB size1. For x=2, blockA pos=2. Other block size=1. Subset sums: 0,1 => positions 2,3. Check manually: possible orders: [1,2,3] gives position of 2 =2; [3,1,2] gives position of 2 =3. Also [1,2,3] only? Actually can we have [1,2,3] and [3,1,2]? What about [1,3,2]? That would place 3 between 1 and 2, breaking forced adjacency 1->2? Because 2 must be immediately after 1. In [1,3,2], 2 is not immediately after 1; there is 3 in between, so invalid. So only two orders: block A then B, or B then A. So positions 2 and 3. Good.
Case: n=3, a = [0,0,0]. All isolated. Blocks: three size1. For x=1, pos=1, other sizes [1,1]. Subset sums: 0,1,2 => positions 1,2,3. Valid orders: any permutation, so 1 can be at positions 1,2,3. Good.
Case: n=4, a = [0,1,2,3]. This gives chain? Let's see: 1 pred=0, 2 pred=1, 3 pred=2, 4 pred=3. So one chain 1-2-3-4, size4. x=3 pos=3. Other blocks none => only position 3. Is there any way to have other positions? No. So output 3. That seems correct.
Now consider a scenario where some block sizes are not all distinct; subset sums still works.
Thus solution seems sound.
But wait, there is one nuance: The problem says "the number of zero elements ai doesn't exceed 20" for B1. For B2 arbitrary zeros, we can still use DP. However, the number of blocks K = number of zeros could be up to n, but DP O(K * n) is fine (1e6). So it's acceptable.
But maybe there is a catch: The condition "any beaver is followed by at most one beaver" ensures that the indegree <=1. But what about outdegree? Each beaver has exactly one a_i (possibly 0). So outdegree is either 0 or 1? Actually a_i can be 0, so outdegree <=1. So the directed graph is a collection of vertex-disjoint paths and possibly isolated vertices. So indeed.
Thus the solution is straightforward.
But wait: Are we sure that any ordering of chains yields a valid queue? Consider a scenario where a block has size > 1, and we place another block between the nodes of that block? No, that would break forced adjacency. So we must keep blocks contiguous. So ordering blocks is the only degree of freedom.
Thus answer as described.
Now, we need to output all possible positions in increasing order, each on separate line. The examples show each number on separate line.
Implementation details:
-
Use 1-indexed arrays.
-
Compute pred[i] = a[i].
-
Compute succ[i] = 0 initially. For each i from 1 to n, if a[i] != 0, succ[a[i]] = i. Since at most one, fine.
-
visited array bool visited[n+1] = false.
-
vector sizes_other.
-
int x_block_size, x_pos.
-
Loop over i from 1 to n:
if pred[i]==0: (head)
// build chain starting from i
vector chain;
int cur = i;
while (cur != 0) {
visited[cur] = true;
chain.push_back(cur);
cur = succ[cur];
}
// chain is list from head to tail
int sz = chain.size();
// Check if x in this chain
auto it = find(chain.begin(), chain.end(), x);
if (it != chain.end()) {
x_block_size = sz;
x_pos = (it - chain.begin()) + 1; // 1-indexed position
} else {
sizes_other.push_back(sz);
}
-
After loop, also need to consider nodes that might not be visited? Since each node has pred (maybe non-zero) but eventually leads to head, all nodes should be visited. But to be safe, iterate over all nodes and if not visited, that means there is a cycle? But problem guarantees no cycles. However, if there is a node with pred != 0 but its head not visited? Actually if we start only from heads (pred==0), we will cover all nodes because following succ from heads covers all nodes that are reachable from a head. But could there be a node that is not reachable from any head? Suppose a node has pred != 0 and its chain goes backwards to a head; but if we follow succ from head, we go forward. So the node will be visited when we start from its head. So all nodes visited. So no need.
-
Then compute DP: dp[0] = true. For each s in sizes_other:
for (int sum = n - s; sum >= 0; --sum) if dp[sum] then dp[sum+s] = true.
-
Then iterate S from 0 to n - x_block_size (or total_