We need to solve: Given a directed graph with n nodes, each node i has a cost c_i, and a directed edge i -> a_i (so each node has outdegree 1). This is a functional graph (each node has exactly one outgoing edge). The mouse starts at some node at time 0, and moves deterministically along the edges each second. We can place traps in some nodes, and we want to guarantee that no matter the starting node, the mouse will eventually be caught (i.e., it will at some time step be on a node with a trap). We need to minimize total cost of traps placed.
Interpretation: The functional graph consists of cycles with trees feeding into them (directed toward the cycle). Since each node has outdegree 1, each component has exactly one cycle (or possibly self-loop). The mouse's trajectory from any start eventually reaches a cycle and then follows the cycle forever. So to guarantee capture, for each node, there must be some node on its forward path that has a trap. Equivalent: The set of trap nodes must be a "hitting set" for all forward paths; i.e., for every node u, the trap set intersects the set {u, a_u, a_{a_u}, ...}. Another way: The traps must form a set that intersects every reachable cycle? Actually, if a node is on a tree feeding into a cycle, if we trap a node on the cycle, then the mouse will eventually reach the cycle and be caught (if it passes the trap). But careful: The mouse moves each second to the next node. If we place a trap on a node on the cycle, when the mouse enters that node, it is caught. If we place trap on a node before the cycle, that also catches it if it starts there or passes through. So essentially, we need to select a set of nodes such that for every node u, there exists some k>=0 with a^k(u) (with a^0 = u) in the trap set. In graph terms, this means that the trap set is a "dominating set" for the functional graph in the sense of forward paths; more precisely, it's a set that is a "feedback vertex set"? Not exactly.
We can think of the graph as a set of components. In each component, the cycle is the sink (since all nodes eventually flow into the cycle). To guarantee capture from all starting nodes, it's sufficient and necessary to ensure that every directed cycle has at least one trap? Let's think: Suppose we have a cycle. If we have a trap on some node on the cycle, then any node that eventually reaches that cycle will at some point hit that node when it cycles (if it goes around the cycle, eventually it will land on that trap node). However, if we have a trap only on a node that is not on the cycle but in a tree feeding into the cycle, then nodes that start on the cycle may never hit that trap because they never leave the cycle and they might never pass through that tree node (since edges are directed toward the cycle, not away). So from a node on the cycle, the path is only within the cycle; it never goes into the tree. So to catch a mouse starting on a cycle node, we must place a trap on at least one node of that cycle. Conversely, if we place a trap on at least one node of each cycle, then for any node u, its forward path eventually reaches a cycle, and once on the cycle, after some steps it will eventually hit the trap (since the trap is on the cycle and the mouse traverses the cycle infinitely). But careful: What if the cycle length >1 and the trap is on a specific node; the mouse may enter the cycle at some node and then go around; but will it eventually hit the trap? Since it's deterministic and moves step by step along the cycle, starting from any node on the cycle, after a finite number of steps (at most cycle length) it will visit the trap node because it cycles through all nodes. So yes. However, there is nuance: If the mouse starts at a node that is in the tree, it will eventually reach the cycle and then be caught as above. But what if the trap is on a node in the tree that is not on the cycle? Could that also catch mice starting on the cycle? No, because the cycle never goes into the tree. So we definitely need at least one trap on each cycle. Is that also sufficient? Let's check: Suppose we have a component with a cycle. If we place a trap on at least one node of that cycle, then any node in the component eventually reaches the cycle and then eventually hits that trap. But we must also consider that there could be multiple cycles in separate components. So overall, we need to cover all cycles. However, is there any possibility that a trap placed on a node that is not on any cycle could also cover multiple cycles? That seems impossible because from a node not on a cycle, its forward path goes to a unique cycle (the one it eventually reaches). So a trap on a non-cycle node can only catch nodes whose forward paths go through that node. That includes nodes that are upstream of that node (i.e., nodes whose path passes through that node) and the node itself. But nodes on other cycles won't ever reach that node. So covering all cycles is necessary.
But is it sufficient to just pick one node per cycle? Possibly we could pick a node that is on a cycle and also its cost might be high, but maybe there is a cheaper solution: Instead of placing a trap on a cycle node, we could place multiple traps on the tree such that every node on the cycle is "covered" by some trap on the tree? Let's examine: For a node on the cycle, its forward path is the cycle itself; it never leaves the cycle. So the only way to catch it is to have a trap on some node that it visits, i.e., on the cycle. No node outside the cycle is visited. Thus, each cycle must contain at least one trap. So indeed, the minimal trap set must include at least one node from each cycle. Moreover, if we include at least one node from each cycle, then from any node not on a cycle, its forward path leads to a cycle, and eventually it will hit the trap on that cycle (since it will traverse the cycle and eventually land on the trap). But careful: Consider a component with a cycle, and we have a trap on one node of that cycle. For a node in the tree, it eventually reaches the cycle at some entry point (the node on the cycle that is the root of the tree). Then it proceeds around the cycle. Will it necessarily hit the trap? Yes, because from the entry point, as it continues around the cycle, after some steps it will reach the trap node. However, there is a subtlety: The mouse is caught when it enters a node that has a trap. If the trap is on a cycle node, and the mouse enters that node at some time, it is caught. But what if the mouse enters the cycle and then before reaching the trap, it passes through nodes that are not trapped; that's fine. So it will eventually be caught. So indeed, covering each cycle with at least one trap is both necessary and sufficient.
But wait: There is another scenario: what if the graph has self-loops (cycle of length 1)? Then the node points to itself. Trap on that node catches it. So same.
Thus the problem reduces to: In a functional graph, we need to select at least one node from each directed cycle, with minimum total cost. We can choose any node from each cycle. The trees are irrelevant for selection because they don't need traps if cycles are covered? Actually, there is a nuance: What about components that are purely acyclic? In a functional graph, each component has exactly one cycle. However, it is possible that the component is just a cycle (no trees). So all nodes are on cycles. So indeed every component has exactly one cycle. So we need to pick at least one node from each cycle.
But is there any possibility that we could place a trap on a node that is not on a cycle but that would effectively cover multiple cycles? That would require that node to be on multiple cycles, impossible in functional graph. So minimal solution is: sum over each cycle of the minimum cost among nodes in that cycle.
But wait, sample 1: n=5, edges: 1->1 (self-loop), 2->3, 3->4, 4->3, 5->3. Costs: 1,2,3,2,10. The cycles: Node 1 is a self-loop (cycle of length 1). Nodes 3 and 4 form a cycle (3->4, 4->3). So cycles: {1} and {3,4}. Minimum cost in {1} is 1. Minimum cost in {3,4} is min(3,2)=2. Sum = 3. Sample output is 3. So matches.
Sample 2: n=4, edges: 1->2, 2->4, 3->2, 4->2. Costs: 1,10,2,10. The graph: All nodes eventually go to node 2? Let's examine: Node2->4->2 forms a cycle? Actually 2->4, 4->2, so cycle {2,4}. Node1->2, Node3->2. So cycles: {2,4}. Minimum cost in {2,4} is min(10,10)=10. Sum=10. Sample output 10. matches.
Sample 3: n=7, edges: 1->2, 2->2, 3->2, 4->3, 5->6, 6->7, 7->6. Costs: all 1. So cycles: {2} (self-loop? Actually 2->2, so cycle of length 1). And {6,7} cycle length 2. Minimum cost for {2}=1, for {6,7}=1, sum=2. Output 2. So matches.
Thus the solution is: identify all cycles in the functional graph, for each cycle compute min cost among its nodes, sum them up.
But wait: Are we absolutely certain that we don't need any traps on nodes not in cycles? Consider a component where the cycle length is L and we put a trap on some node on the cycle. Then a node that is in the tree might have a path that goes through the cycle and then later goes into the tree again? Not possible because edges are directed and outdegree 1, so once you enter the cycle, you stay in cycle forever. So it's fine.
But there is a nuance: What about nodes that are part of a cycle but also have incoming edges from the tree? The trap on the cycle catches them when they are on the cycle. But if the trap is placed on a specific cycle node, and the mouse starts on a tree node, it will eventually reach the cycle at some node (the entry point). If the entry point is not the trap node, then it will travel around the cycle. But if the trap is placed on a node that is upstream from the entry point? Not possible, since from the cycle, the direction is only forward along the cycle; there is no way to go back to the tree. So it will eventually hit the trap after some steps. So yes.
Thus the problem reduces to finding all cycles in functional graph and summing minimal costs.
We need to handle up to n=2e5.
The standard algorithm for functional graph: Use DFS with state (0=unvisited, 1=visiting, 2=processed) to detect cycles, or use topological sort (removing nodes with indegree 0 repeatedly) to strip away the trees, leaving only nodes that are part of cycles. Then each remaining node belongs to exactly one cycle; we can group them by finding cycles. Then for each cycle compute min cost and sum.
Simpler: Use visited array and dfs to find cycles. But careful: In functional graph, each node has outdegree 1. We can do a "peeling" approach: compute indegree for each node, then push nodes with indegree 0 into a queue, and remove them (like topological sort). After processing all, nodes with indegree >0 are part of cycles. But cycles are strongly connected components where each node has indegree at least 1 within the cycle; after removing all nodes that are not in cycles, we are left with nodes that are in cycles. However, cycles may consist of nodes that all have indegree >=1 but after removal of trees, indegree might be only from within cycle. Actually after removing all nodes with indegree 0 iteratively, the remaining nodes each have indegree at least 1 and form directed cycles. Moreover, each component is a set of cycles? Actually in a functional graph after removing trees, each remaining component is a cycle (maybe with some chords? No, because each node has exactly one outgoing edge, so the remaining subgraph consists of disjoint cycles (each node's outgoing edge remains, and each node has indegree from within the cycle maybe also from trees but those have been removed). So indeed the remaining nodes are exactly the nodes on cycles. Then we can traverse each cycle to compute min cost. But careful: There could be cycles with nodes that have indegree from trees, but after removal of trees, these edges are removed (the nodes themselves are still there). But in the process, we are not physically removing edges; we just decrement indegree. The typical algorithm: compute indegree of each node (counting incoming edges). Then repeatedly remove nodes with indegree 0: for each such node, we consider its outgoing edge to v, decrement indegree of v, and if indegree becomes 0, push v. After this, nodes with indegree >0 are those on cycles. But this works because each node on a cycle will always have at least one incoming edge from within the cycle, so indegree won't become 0. However, there is nuance: A node on a cycle may have indegree from trees as well; after removing trees, its indegree may be reduced, but still at least 1 from the cycle (since each cycle node has at least one incoming edge from its predecessor in the cycle). So after processing, nodes with indegree >0 are exactly cycle nodes. Then we can iterate over all nodes, if indegree >0 (meaning it's in a cycle), then we can start exploring the cycle to compute min cost, but we need to avoid double-counting cycles. Standard: For each node not visited (or still marked as cycle), we walk along its outgoing edges until we complete the cycle, collecting nodes and marking them visited. Since the graph after removal of trees is just disjoint cycles, we can simply do: for each node that is still in the "cycle set" (i.e., indegree >0), if not visited, traverse the cycle: start at node, while not visited, mark visited, add cost to current cycle's min, move to a[node]. But we need to stop when we come back to a visited node? But we may encounter nodes from other cycles? No, because each node has exactly one outgoing edge, and cycles are disjoint. So we can do: for i from 1 to n: if indegree[i] > 0 and not visited[i]: then follow i's outgoing edge until we return to a node already visited in this traversal; we can collect all nodes in that cycle. Since the structure is a cycle, we can do: start = i; curr = i; do { visited[curr]=true; minc = min(minc, c[curr]); curr = a[curr]; } while (curr != start); Actually careful: The cycle may not start at i if i is not part of a cycle? But we only start at nodes with indegree>0, which are cycle nodes, so they are on a cycle. But the cycle may include nodes that we have not visited yet. However, starting at i, following edges, we will eventually loop back to i because it's a cycle. So the do-while works. But we need to ensure that we don't loop infinitely if there is a cycle but indegree>0 condition is satisfied but i might not be part of the cycle? Actually if indegree>0, then it's part of some cycle because after removing trees, the remaining nodes form cycles; but there is a nuance: A node could have indegree from a tree and also from a cycle? Actually suppose we have a node that is part of a cycle and also receives edges from trees. After removal of trees, its indegree from trees gets decremented to 0? Wait, the process: initially indegree counts all incoming edges, including those from trees. When we remove a tree node (with indegree 0), we decrement indegree of its successor. This could reduce indegree of a cycle node. But if that cycle node's only remaining indegree is from the cycle predecessor, then after removal of all tree nodes, its indegree becomes exactly 1 (from the predecessor). So it will still be indegree >0. So yes, nodes on cycles have indegree>0 after the removal of all tree nodes. But could there be a node that is not on a cycle but after removal still has indegree>0? Consider a node that is part of a "pseudo-cycle"? In functional graph, the only strongly connected components are cycles. If a node is not on a cycle, its eventual path leads to a cycle, and it can have indegree from other non-cycle nodes; after we remove all non-cycle nodes via topological sort, that node would be removed because it would eventually have indegree 0? Let's simulate: Suppose we have a node X that is not on a cycle but has indegree from other non-cycle nodes. Initially indegree(X) could be >0. However, since X is not on a cycle, there is a path from X to a cycle, and it has no way to return to itself. In the topological sort approach for functional graph, we compute indegree and then repeatedly remove nodes with indegree 0. Nodes not on cycles will eventually become indegree 0 because they have no incoming edges from cycles (only from trees). Actually, is it guaranteed? Consider a node that is part of a tree feeding into a cycle. It may have indegree from multiple child nodes, but these child nodes are also not on cycles. As we remove leaves (nodes with indegree 0) we eventually will remove all nodes that are not part of cycles. Even if a node has high indegree, it will only be removed when all its incoming nodes are removed, reducing its indegree to 0. So indeed all non-cycle nodes will eventually have indegree 0 and be removed. So after the process, nodes with indegree >0 are exactly those on cycles. So we can safely use indegree>0 as cycle membership.
Then we need to sum min cost for each cycle. But careful: In the indegree removal approach, we don't physically delete nodes; we just mark them as removed or not. We can compute indegree array, then queue nodes with indegree 0. While queue not empty: pop u, mark removed (or simply decrement indegree of its successor). Then after that, nodes with indegree >0 are cycle nodes. Then we need to traverse each distinct cycle. We can do that by iterating through nodes, if indegree>0 and not visited, traverse the cycle using a simple while loop. Complexity O(n).
Alternatively, we can use DFS with colors to detect cycles directly and compute min cost in each cycle. That is also O(n). Simpler to implement: For each node, have state: 0=unvisited, 1=visiting (in current recursion stack), 2=processed. Then do DFS from each unvisited node, following the single outgoing edge. When we encounter a node with state 1, we have found a cycle; we can then go around the cycle to compute min cost, sum it. But careful: In functional graph, a DFS may go into a visited node that is part of a cycle already processed; we need to avoid double counting. Using the three-state method: For each node, if state 0, set state 1, then recurse to its neighbor. After recursion, set state 2. If during recursion we encounter a node with state 1, that means we are on a cycle. We can then traverse from that node following edges until we return, collecting nodes in the cycle. But we need to ensure we don't sum the same cycle multiple times. Since each node in cycle will have state 1 when we first detect the cycle, we can compute the min cost for the cycle at that moment and add to answer, and then mark all nodes in the cycle as processed (state 2) perhaps by continuing traversal? But we must be careful not to count a cycle more than once.
Simpler: Use the indegree removal method; it's straightforward and less error-prone.
Algorithm steps:
- Read n.
- Read array c[1..n] (costs).
- Read array a[1..n] (edges).
- Compute indegree for each node: indeg[i] = number of incoming edges. Since each node has exactly one outgoing edge, we can increment indeg[a[i]] for each i.
- Initialize queue with all nodes i where indeg[i] == 0.
- While queue not empty:
u = queue.pop()
v = a[u]
indeg[v]--.
if indeg[v] == 0: queue.push(v)
- After this, nodes with indeg[i] > 0 are in cycles.
- Initialize visited boolean array (or we can use indeg>0 as cycle marker, but we need to mark nodes we have processed to avoid multiple cycles). We'll have an array visited[1..n] = false.
- For i from 1 to n:
if indeg[i] > 0 and not visited[i]:
// traverse the cycle starting from i
curr = i
min_cost = INF
while not visited[curr]:
visited[curr] = true
min_cost = min(min_cost, c[curr])
curr = a[curr]
// after loop, we have visited all nodes in cycle.
ans += min_cost
- Print ans.
Check correctness: Suppose there is a cycle where some nodes have indeg>0 but we start at a node that is visited? We only start if not visited. Then we traverse along outgoing edges until we come back to a visited node. Since all nodes in the cycle are unvisited at start, we will visit them all. The loop condition while not visited[curr] ensures we stop when we encounter a node that was already visited in this cycle (i.e., we return to the start). But careful: The cycle might not start at i; if i is not the "first" node of the cycle but we start anyway, traversing will eventually loop around and come back to i because it's a cycle. Since all nodes are unvisited at the start, the while loop will continue until we come back to i? Actually, suppose we have cycle: 2->3->4->2. If we start at node 3, visited[3] false, mark true, go to 4 (false), mark true, go to 2 (false), mark true, go to 3 (now visited true). Then the while condition "while not visited[curr]" would check before marking? In our pseudocode: while not visited[curr]: mark visited, update min, move to next. At the point we are at node 3 again, visited[3] is already true from earlier, so loop exits. We have visited all nodes in cycle. So it's fine. However, we need to be careful that we don't exit prematurely if we start at a node that is visited? But we only start if not visited. So ok.
Edge case: a cycle of length 1 (self-loop). Starting at i: visited[i] false, we mark it, go to a[i] which is i, now curr = i, but visited[i] is true, so loop exits after one iteration. min_cost = c[i]. Works.
Thus answer computed.
But is there any situation where we could do better than taking one node per cycle? Could we possibly place a trap on a node that is not on the cycle but still catch mice from that cycle? As argued earlier, no, because mice starting on the cycle never leave it. So each cycle must have at least one trap. So minimal cost is indeed sum of min cost per cycle.
Thus solution is straightforward.
Double-check constraints: n up to 2e5, costs up to 1e4, answer fits in int? n*1e4 = 2e9, need 64-bit. So use long long.
Complexity O(n) time and O(n) space.
But wait, is it always safe to use indegree removal to identify cycles? Let's test on a graph where there is a cycle but some node on the cycle also has indegree from trees, which after removal might still have indegree>0. Yes.
Edge Cases: Could there be a component that is not a cycle but all nodes have indegree >0? In a functional graph, each node has outdegree exactly 1. Consider a component that is a "rho" shape: a cycle with trees feeding into it. The cycle nodes have indegree at least 1 from the cycle and possibly from trees. Non-cycle nodes have indegree from their children. However, after removal of leaves (nodes with indegree 0) we eventually remove all non-cycle nodes because they will become indegree 0 after their children are removed. So yes, only cycle nodes remain with indegree >0.
One more nuance: If there is a node that has self-loop (cycle length 1), its indegree might be from itself? Actually indegree counts incoming edges from all nodes. For self-loop i -> i, the indegree includes at least that self-edge? The edge from i to i contributes 1 to indeg[i] (since i points to i). So indeg[i] >=1, and after removal of trees, indeg[i] might still be >0. Also, if there are incoming edges from trees, indeg may be larger, but still >0 after removal (since the self-loop ensures indegree >=1). So it's fine.
Implementation details:
- Use vector indeg(n+1, 0).
- For i=1..n: indeg[a[i]]++.
- queue q; for i=1..n if indeg[i]==0 q.push(i).
- While !q.empty(): u = q.front(); q.pop(); v = a[u]; indeg[v]--; if(indeg[v]==0) q.push(v);
- Then vector visited(n+1, false); long long ans=0;
- For i=1..n: if(indeg[i] > 0 && !visited[i]) { // node in cycle not visited yet
int cur = i;
int minc = INT_MAX; // or 1e9+5
while(!visited[cur]) {
visited[cur]=true;
minc = min(minc, c[cur]);
cur = a[cur];
}
ans += minc;
}
- Print ans.
We must ensure that we don't accidentally include nodes that are not in cycles but have indeg>0 due to some leftover? As argued, all such nodes are cycles. But to be safe, we could also directly detect cycles using DFS. However, this method is standard.
Now let's test on sample inputs.
Sample1:
n=5, c=[1,2,3,2,10], a=[1,3,4,3,3]
Compute indeg:
i=1->1: indeg[1]++
i=2->3: indeg[3]++
i=3->4: indeg[4]++
i=4->3: indeg[3]++ -> indeg[3]=2
i=5->3: indeg[3]++ -> indeg[3]=3
indeg: [1:1, 2:0, 3:3, 4:1, 5:0]
Queue: nodes with indeg 0: 2,5.
Process 2: v=a[2]=3; indeg[3]-- -> 2; if 0? no.
Process 5: v=3; indeg[3]-- -> 1; not 0.
Queue empty.
Remaining indeg>0: 1 (1), 3 (1), 4 (1). So cycle nodes: 1,3,4. But actually cycle nodes are 1 (self-loop) and 3-4 cycle. So indeed these three nodes are in cycles. Now traverse:
i=1: indeg>0 and !visited, traverse: cur=1, minc=1, visited[1]=true, cur=a[1]=1, visited[1] already true, loop ends. ans+=1.
i=2: indeg[2]=0 skip.
i=3: indeg>0 and not visited: cur=3, visited[3]=true, minc=3, cur=4; not visited: visited[4]=true, minc=min(3,2)=2, cur=a[4]=3; visited[3] true, loop ends. ans+=2 => total 3.
i=4 visited already skip.
i=5 indeg 0 skip.
Answer 3. Works.
Sample2:
n=4, c=[1,10,2,10], a=[2,4,2,2]
indeg:
1->2: indeg[2]++
2->4: indeg[4]++
3->2: indeg[2]++
4->2: indeg[2]++ => indeg[2]=3, indeg[4]=1, indeg[1]=0, indeg[3]=0.
Queue: 1,3.
Process 1: v=2, indeg[2]-- =>2; not 0.
Process 3: v=2, indeg[2]-- =>1; not 0.
Remaining indeg>0: 2 (1), 4 (1). So cycle nodes: 2 and 4.
Traverse:
i=2 not visited: cur=2, visited[2]=true, minc=10, cur=a[2]=4; not visited: visited[4]=true, minc=min(10,10)=10, cur=a[4]=2; visited[2] true, loop ends. ans=10.
i=4 visited, skip. Answer 10.
Sample3:
n=7, c all 1, a: [2,2,2,3,6,7,6]
indeg:
1->2: indeg[2]++
2->2: indeg[2]++ => indeg[2] becomes 2?
3->2: indeg[2]++ => 3
4->3: indeg[3]++ =>1
5->6: indeg[6]++ =>1
6->7: indeg[7]++ =>1
7->6: indeg[6]++ =>2
So indeg: 1:0,2:3,3:1,4:0,5:0,6:2,7:1.
Queue: nodes with indeg 0: 1,4,5.
Process 1: v=2, indeg[2]-- =>2; not 0.
Process 4: v=3, indeg[3]-- =>0; push 3.
Process 5: v=6, indeg[6]-- =>1; not 0.
Now process 3 (from queue): v=a[3]=2, indeg[2]-- =>1; not 0.
Queue empty.
Remaining indeg>0: 2 (1),6 (1),7 (1). So cycle nodes: 2,6,7.
Traverse:
i=2 not visited: cur=2, visited[2]=true, minc=1, cur=a[2]=2; visited true, exit => ans+=1.
i=6 not visited: cur=6, visited[6]=true, minc=1, cur=7; not visited: visited[7]=true, minc=1, cur=a[7]=6; visited true, exit => ans+=1.
Total 2.
Matches.
Thus solution is correct.
Now consider if there is a node with indeg>0 but not part of a cycle? Could there be a situation where after removal of nodes with indeg 0, we are left with a set of nodes that all have indeg>0 but are not forming a simple cycle? In functional graph, each node has outdegree 1, so the subgraph induced by nodes with indeg>0 after removal of nodes that become indeg 0 must be a collection of disjoint cycles. Because consider a node u with indeg>0; its outgoing edge goes to v. Since we removed all nodes that could have indeg 0, v also has indeg>0 (otherwise u's edge to v would have contributed indeg to v, but v's indeg could become 0 if all its incoming edges were from removed nodes; but then v would have been removed earlier). Actually it's possible to have a node v that originally had indeg>0 but after removal of its incoming edges from trees, its indeg becomes 0 and then it would be removed. So after removal process, any remaining node v must have indeg>0 meaning at least one incoming edge from a remaining node. So each remaining node has at least one incoming edge from remaining nodes. Since each node has exactly one outgoing edge, the subgraph is a collection of disjoint cycles (each node's outedge points to another remaining node, and indegree at least 1 from remaining nodes; by counting edges, it must be that each node has indegree exactly 1 within the remaining set? Not necessarily exactly 1, but because each node has exactly one outgoing edge, the number of edges in the remaining set equals number of nodes. For a directed graph where each node has outdegree 1, if the subgraph is such that each node also has indegree at least 1, then the indegree must be exactly 1 for each node (by counting: sum indeg = number of edges = number of nodes, so average indeg = 1; if all indeg >= 1, then each indeg = 1 exactly). So yes, each remaining node has indegree exactly 1 from within the remaining set. That implies that the remaining graph is a disjoint union of directed cycles (each node's incoming from exactly one node in the set, and outgoing to exactly one node). So they are cycles.
Thus method is solid.
Potential pitfalls: Large n, need to use efficient data structures, but simple arrays are fine. Use 0-indexing or 1-indexing. I'll use 0-index for convenience but careful with queue operations. Might be simpler to use 0-indexing. But then arrays of size n. We'll adjust.
Implementation details:
-
Input n.
-
vector c(n), a(n).
-
for i in 0..n-1: read c[i].
-
for i in 0..n-1: read a[i], but note that given a_i is 1-indexed. We'll convert to 0-index by subtracting 1.
-
vector indeg(n, 0);
-
for i in 0..n-1: indeg[a[i]]++.
-
queue q;
-
for i in 0..n-1: if indeg[i]==0: q.push(i);
-
while(!q.empty()) {
int u = q.front(); q.pop();
int v = a[u];
indeg[v]--;
if(indeg[v]==0) q.push(v);
}
-
vector visited(n, false);
-
long long ans = 0;
-
for i in 0..n-1: if(indeg[i] > 0 && !visited[i]) {
int cur = i;
int minc = c[cur]; // or INT_MAX
while(!visited[cur]) {
visited[cur] = true;
minc = min(minc, c[cur]);
cur = a[cur];
}
ans += minc;
}
-
print ans.
But careful: The while loop condition while(!visited[cur]) will stop when we encounter a node already visited. However, if we start at a node that is part of a cycle, we will traverse the cycle and eventually come back to the start; the start is visited in the loop's first iteration. At that point cur will be a neighbor of the last node; after marking last node and moving cur = a[cur], cur becomes the start (already visited). Then loop exits. So minc will be computed for all nodes in the cycle. But what about the case when there is a cycle but we start at a node that is not the "first" in the cycle? It works as described.
One nuance: In the loop, we set minc = min(minc, c[cur]) after checking visited? Actually we check while(!visited[cur]) then inside we mark visited and update minc, then move cur. But if we set minc initially to something like INF and then update inside loop, that's fine. If we set minc = c[cur] before loop and then loop only updates after moving? Better to initialize minc to a large value and update inside loop. Or we can set minc = INF and then in loop update.
Simpler:
int cur = i;
int minc = INT_MAX;
while(!visited[cur]) {
visited[cur] = true;
minc = min(minc, c[cur]);
cur = a[cur];
}
ans += minc;
But if the cycle length is 0? Not possible.
Now consider if there is a node with indeg>0 but we start at it, and its cycle includes nodes that have been visited already from a previous cycle? That cannot happen because cycles are disjoint. However, the while loop condition will prevent infinite loop.
Time complexity: O(n). Memory: O(n).
Edge case: n=1. Graph: a_1 could be 1 (self-loop). indeg[0] = 1. q empty. visited false. i=0 indeg>0, traverse: cur=0, visited[0]=true, minc=c[0], cur=a[0]=0, visited[0] true, exit loop. ans = c[0]. That's correct: we need to trap in room 1.
If a_1 points to something else? But since only one node, a_1 must be 1, because 1 <= a_i <= n. So it's self-loop.
Another edge case: All nodes form a single big cycle. Then after indeg removal, all nodes indeg>0. Then we will find one cycle and compute min cost across all nodes, sum = min cost. That's correct: we need at least one trap in that cycle, pick cheapest node.
If there are multiple cycles, we sum min for each.
Thus solution is correct.
But is there any scenario where placing a trap on a node that is not on a cycle could be cheaper than placing on a cycle node, while still covering that cycle? As argued, no, because the cycle nodes themselves need to be covered directly. However, there is a nuance: Suppose we place a trap on a node that is in the tree, but that node is visited by all nodes in the cycle? That's impossible because from cycle nodes, the path never goes into the tree; they only move along the cycle. So the trap on a tree node will not be visited by any node that starts on the cycle. Thus not sufficient.
What if we place multiple traps on tree nodes such that every node on the cycle is eventually caught? But to catch a node on the cycle, the mouse must at some time be on a node with a trap. Since the mouse moves deterministically along the cycle, the only nodes it ever visits are those on the cycle. So the trap must be on a cycle node. So indeed each cycle must have at least one trap on a node that belongs to that cycle.
Therefore minimal cost is sum over cycles of min(c_i).
Thus the problem reduces to cycle detection.
Now we need to write code accordingly.
Potential pitfalls: The input size is up to 2e5, reading with cin and sync_with_stdio(false) is fine.
Now we can implement.
But wait: The problem statement says "mouse can be in any room from 1 to n at second 0." It also says "If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap." So we only need to catch it eventually, not immediately. And we can set traps in multiple rooms. So our reasoning stands.
Double-check with some custom cases:
Case: n=3, edges: 1->2, 2->3, 3->2. Costs: 100, 1, 2. Graph: node2 and 3 form a cycle (2->3, 3->2). Node1 feeds into 2. Cycles: {2,3}. Minimum cost in cycle = min(1,2)=1. Sum=1. Our algorithm: indeg: 1->2 indeg[2]++; 2->3 indeg[3]++; 3->2 indeg[2]++; so indeg[1]=0, indeg[2]=2, indeg[3]=1. Queue:1; remove 1: v=2 indeg[2]-- =>1. After that, indeg[2]=1, indeg[3]=1. Then traverse cycles: start at 2, minc=1, visit2, cur=3, minc=min(1,2)=1, visit3, cur=2 visited exit => ans=1. Good.
Case: n=3, edges: 1->2, 2->1, 3->2. Costs: 100, 1, 50. Cycles: {1,2}. min=1. Node3 feeds into 2. Sum=1. Works.
Case: n=3, edges: 1->2, 2->3, 3->3. Self-loop at 3. Cycles: {3}. min cost = cost of 3? Suppose cost[3]=5. Node1->2->3, node2->3. So sum=5. Our algorithm: indeg: 1->2 indeg[2]++, 2->3 indeg[3]++, 3->3 indeg[3]++. So indeg: [1:0,2:1,3:2]. Queue: 1 (indeg=0). Process 1: v=2 indeg[2]-- =>0 => push 2. Process 2: v=3 indeg[3]-- =>1 (still >0). Queue empty. Remaining indeg>0: 3 (1). Cycle node: 3. ans+=cost[3]=5. Good.
Now think about a more complex case: multiple cycles in separate components.
All good.
Thus answer is sum of min cost per cycle.
Now we can implement.
But wait, there's a nuance: The graph might have nodes that are part of a cycle but also have incoming edges from trees. In our indegree removal, after removing trees, those nodes still have indegree>0. But their indegree could be >1 due to multiple incoming edges from trees? Initially indegree counts all incoming edges. After removal of trees, we decrement indegree for each removed tree edge. If a cycle node has multiple tree incoming edges, its indegree will be reduced by the number of those trees. But its indegree from the cycle remains (at least 1). So after removal, its indegree might be >1 if it has multiple incoming edges from within the cycle? But in a cycle, each node has exactly one incoming edge from within the cycle (from its predecessor). However, could a cycle node have another incoming edge from another cycle? Not possible because functional graph components are disjoint: each node has exactly one outgoing edge, so cycles in different components are separate; a node cannot have an incoming edge from another component because that would merge components. So within a component, cycle nodes only have one incoming edge from within the cycle (the predecessor) plus possibly from trees. After tree removal, only the cycle edge remains. So indegree becomes exactly 1. So after processing, indegree for cycle nodes should be exactly 1. So we could also check indegree == 1. But we use indeg>0 to be safe.
Now implement.
Potential issues: The queue removal process might be O(n) but we must be careful to not overflow the queue.
Now let's consider if there is any scenario where we can do better than taking one per cycle? Could we avoid placing a trap on a cycle if we place traps on multiple nodes on the tree such that they cover all nodes in the cycle? For a node on the cycle, its forward path is only the cycle. So to catch it, we need a trap on some node that it visits, i.e., on the cycle. So each cycle must have at least one trap on a node in that cycle. So it's necessary. So sum of min per cycle is lower bound, and achievable by picking min-cost node in each cycle. Thus optimal.
Thus the solution is correct.
Now I'll write code in C++.
Pseudo:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
vector c(n);
for (int i = 0; i < n; ++i) cin >> c[i];
vector a(n);
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
a[i] = x - 1; // convert to 0-index
}
vector indeg(n, 0);
for (int i = 0; i < n; ++i) {
indeg[a[i]]++;
}
queue q;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) q.push(i);
}
while (!q.empty()) {
int u = q.front(); q.pop();
int v = a[u];
indeg[v]--;
if (indeg[v] == 0) q.push(v);
}
vector visited(n, false);
long long ans = 0;
for (int i = 0; i < n; ++i) {
if (indeg[i] > 0 && !visited[i]) {
int cur = i;
int minc = INT_MAX;
while (!visited[cur]) {
visited[cur] = true;
minc = min(minc, c[cur]);
cur = a[cur];
}
ans += minc;
}
}
cout << ans << '\n';
return 0;
}
Check: For nodes not in cycles (indeg == 0 after processing), we ignore. For nodes in cycles (indeg>0), we traverse and sum min.
One potential nuance: In the removal process, we decrement indegree of v even if u is removed. That's correct. However, what about nodes that are part of a cycle but also have indegree 0 initially? That can't happen because a cycle node always has at least indegree >=1 (at least from its predecessor). So fine.
Now verify on sample inputs.
Edge Cases: Large n, maybe recursion not used, so no stack overflow.
Complexity: O(n).
Now I'll produce final answer.
But wait, could there be a scenario where the graph has a cycle and we have to consider that placing a trap on a node that is part of the cycle but also has a tree might be cheaper than placing on other cycle nodes, but we already take min. So correct.
Now I think it's done.
However, I recall a known Codeforces problem "Mouse Trap" or similar? This problem is CF round #... Actually it's problem 1020B? No, that's about finding cycles. This one is "Mouse in a Trap"? I think it's CF 319B? Actually it's "Bear and Bowling" no. The problem is "B. Mouse Hunt" from Codeforces Round #... Yes, I've seen a problem "Mouse Hunt" with similar description. Indeed the solution is as we described.
Thus final answer: sum of min cost per cycle.
Now let's provide explanation in solution.
Implementation details: Use 0-index.
Now check for integer overflow: ans can be up to 2e5 * 1e4 = 2e9, fits in 64-bit, but use long long.
Now final code.
But note: In the removal process, we used a queue. That's standard.
Alternate approach: Use DFS with three colors to detect cycles and compute min cost. But indegree removal is fine.
Now produce final answer.
We'll also include comments to clarify.
Now final solution. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> cost(n);
for (int i = 0; i < n; ++i) cin >> cost[i];
vector<int> to(n);
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
to[i] = a - 1; // 0‑based
}
// indegree of each vertex
vector<int> indeg(n, 0);
for (int i = 0; i < n; ++i)
indeg[to[i]]++;
// remove all vertices that are not in a cycle (topological sort)
queue<int> q;
for (int i = 0; i < n; ++i)
if (indeg[i] == 0)
q.push(i);
while (!q.empty()) {
int u = q.front(); q.pop();
int v = to[u];
if (--indeg[v] == 0)
q.push(v);
}
// now vertices with indeg > 0 belong exactly to directed cycles
vector<bool> visited(n, false);
long long answer = 0;
for (int i = 0; i < n; ++i) {
if (indeg[i] > 0 && !visited[i]) {
// traverse one whole cycle
int cur = i;
int minc = INT_MAX;
while (!visited[cur]) {
visited[cur] = true;
minc = min(minc, cost[cur]);
cur = to[cur];
}
answer += minc;
}
}
cout << answer << '\n';
return 0;
}