, where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence.
si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge.
Output
Print the sum of the weights the Minimum-Cost Arborescence.
We are asked: "Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E)." Input format: first line: |V| |E| r. Then |E| lines: s t w.
We need to compute the minimum cost arborescence (also known as minimum spanning arborescence or directed MST) rooted at r.
Constraints: |V| up to 100, |E| up to 1000, weights up to 10000. Graph is guaranteed to have at least one arborescence rooted at r.
We need to output total weight.
We can implement Edmonds' algorithm (Chu–Liu/Edmonds) for minimum arborescence. Since |V| small, we can do a straightforward O(VE) or O(E log V) but we can implement the standard algorithm.
We'll implement the following:
function min_cost_arborescence(V, E, root):
Let N = V, edges = list of (u, v, w)
Initialize result = 0
For each v != root:
// find minimum incoming edge weight to v
min_in[v] = INF
for each edge (u,v,w): if w < min_in[v]: min_in[v]=w, min_edge[v] = (u,v,w)
if min_in[v] is INF: no arborescence (but guarantee exists), so maybe skip? But we assume it exists.
result += min_in[v] // This adds weight of min incoming edge, but we'll adjust for cycles later
code
// Now subtract min_in[v] from each incoming edge to v, to create reduced costs
For each edge (u,v,w):
if v != root: edge.w -= min_in[v]
// Now detect cycles in the subgraph formed by selecting the min_in edge for each v != root (the chosen edges after reduction)
// Build adjacency list: each v != root has chosen incoming edge (min_edge[v]) with reduced cost 0 (since we subtracted min_in[v]).
// Then find cycles in this 0-weight subgraph.
// We'll find cycles via DFS or using Union-Find? The algorithm typically contracts cycles.
// We'll do iterative contraction:
While true:
// Initialize arrays: parent, visited, cycle_id, etc.
Let parent = array size N, set to -1; visited = array to track order;
// For each vertex v != root, if not visited, traverse via the chosen zero-reduced-cost incoming edges until we hit root or a visited node.
// Actually we need to find cycles among the selected edges (each node except root picks one incoming edge). This forms a set of edges that each node (except root) has exactly one incoming edge; the root has none. This directed graph can have cycles (excluding root). Those cycles are disjoint (each node has out-degree? Actually each node can have multiple outgoing edges, but each node (except root) has exactly one incoming edge selected. So the selected edges form a set of directed trees that all point towards the root? Not exactly: Each node has exactly one incoming edge, so the structure is a functional graph; if we start from any non-root node and follow incoming edges (i.e., go from v to the source of its selected edge), we will eventually either reach root or enter a cycle. Since root has no incoming edge, any path will terminate at root if no cycle. If there is a cycle, it must be a directed cycle where each node's selected edge points to the previous node. So indeed we can detect cycles.
// We'll assign an order number to nodes as we traverse.
// We'll use an array 'status' for each vertex: 0 = unvisited, 1 = in current stack, 2 = processed (no cycle). We'll also maintain 'cycle' membership via a 'contracted' mapping.
// For v from 0 to N-1:
// if v != root and not assigned to a cycle and not visited, then trace following parent edges (min_edge) until we reach root, a visited node, or a node already in a cycle.
// While tracing, record the path. If we encounter a node already in current stack, we found a cycle.
// The standard implementation: for each node, while not visited and node != root, set visited[node] = current run id? Or use stack.
// However, we can contract cycles if found.
// But we need to keep track of reduced edges and map nodes to supernodes.
// Simplify: Implement the classic algorithm:
// 1. For each vertex v != root, select the incoming edge with minimum weight (after previous reductions). Add its weight to answer.
// 2. Subtract min_in[v] from each incoming edge of v.
// 3. Form graph of selected zero-weight edges (each v != root has exactly one incoming zero-weight edge). Determine if there is any directed cycle among these selected edges (excluding root). If no cycles, then the selected edges (after expansion) plus the root form an arborescence, and we are done. Otherwise, contract each cycle into a supernode, adjust the graph, and repeat.
// We'll implement with while loop.
// Data structures:
// - edges list: each edge has (u, v, w)
// - we maintain an array 'incoming' for each vertex: the index of the chosen edge (or -1)
// - After contraction, we need to map original vertices to contracted ones.
// However, because V is up to 100, we can implement recursively with a function that given n, root, edges, returns weight.
// I'll write a function edmonds(n, root, edges) where edges is list of (u,v,w) with u,v in [0,n-1].
// Pseudocode from Wikipedia:
// For each v != root:
// incoming[v] = edge with minimum weight among edges ending at v.
// For each v != root:
// total += incoming[v].weight
// For each edge e ending at v:
// e.weight -= incoming[v].weight
// // find cycles
// Initialize visited array of size n, set to -1. cycle_id[v] = -1.
// For each v != root:
// if visited[v] != 0:
// continue
// Start tracing from v: set cur = v, while visited[cur]==0 and cur!=root:
// visited[cur] = v (or mark step) Actually we can use a stack.
// Instead use typical method:
// let u = v
// while visited[u] == -1 and u != root:
// visited[u] = v (or index)
// u = incoming[u].from
// if u == root or cycle_id[u] != -1:
// then no cycle for this path; continue.
// else if visited[u] == v: then a cycle found. Nodes from u back to u form a cycle.
// This works if we assign a unique mark for each start.
// After detecting cycles, if no cycles, break. Else, contract each cycle into a new vertex. For each edge, if it goes from outside to inside cycle, adjust its weight? Actually after contraction, we need to create new graph with supernodes.
// Steps for contraction:
// Assign new index for each cycle (starting from n). For each vertex, if it belongs to a cycle, map to new supernode. Otherwise, map to itself (but later we will renumber so that total nodes = n - |cycle_vertices| + number_of_cycles). Usually we compress the graph to have n' = n - (size of cycle) + 1 for each cycle.
// For each edge (u,v,w):
// u' = cycle_id[u] if cycle_id[u] != -1 else u (but we will renumber)
// v' = cycle_id[v] if cycle_id[v] != -1 else v
// If u' != v': then this edge connects different supernodes.
// If u' == v': then both ends inside same cycle; ignore because within cycle it's not needed (since we already selected an edge inside cycle? Actually we need to consider that after contraction, edges within the same cycle become self-loops and are discarded).
// If v' is the contracted node (representing the cycle) and u' is not, then this edge is an incoming edge to the cycle. In the algorithm, we need to adjust the weight: we already subtracted min_in for vertices in the cycle, but for edges entering the cycle, we need to incorporate the fact that we might replace the selected edge in the cycle. The algorithm's recurrence: when we contract a cycle C to a supernode c, for each edge e = (u,v) with v in C, we set its weight to w(e) - min_in[v] (which we already did). Then we treat the contracted graph. That's exactly what we've done after subtracting min_in. So we can simply keep the reduced weight for edges. When we later expand the cycle, we will select all edges except one from the cycle's selected incoming edges (the one that was originally chosen as min_in) and then add the chosen incoming edge from outside. The reduction step already accounted for the sum of min_in of all vertices in the cycle, and the edges coming into the cycle have reduced weights that represent the additional cost if we replace the min_in edge of that particular vertex. So after contraction, we just continue.
// But careful: When we contract, we need to treat root specially: if root is inside a cycle? Should not happen because root has no incoming edge, so cannot be part of a cycle in selected edges. So safe.
// After constructing new edges list, we recursively call the algorithm on n' nodes with new root mapping: if root was not in any cycle, its supernode remains root; if root got contracted (shouldn't), handle.
// The recursive call returns the total weight of the arborescence in the contracted graph. But we have already added min_in values for all vertices (including those in cycles) before contraction. So the final result is sum(min_in for all v != root) + result_from_contracted_graph.
// However, in some implementations, they do the following:
// total = 0
// For each v != root: total += min_in[v]
// For each edge: if v != root: edge.weight -= min_in[v]
// Detect cycles. If none: return total
// Else: contract cycles to supernodes, get new total' = edmonds(contracted_graph) // total' is the additional cost beyond the sum of min_in? Actually after contraction, we call the same algorithm on the contracted graph, which will again add min_in' for each contracted vertex? Wait, careful: The algorithm's typical recursive definition:
// - For each vertex except root, choose min incoming edge weight, add to answer.
// - Subtract that min from all incoming edges.
// - Contract cycles of zero-weight edges.
// - Recursively solve the contracted graph.
// - The answer from recursive call is added to the initial sum.
// But note that when we contract, the contracted node is treated as a vertex, and we will again compute min_in for each vertex (including the supernode). However, the edges entering the supernode already have reduced weights that reflect the adjustment. Then the recursive call will add its own min_in values, which correspond to the extra cost to choose an incoming edge to the cycle (replacing one of the cycle's edges). So total sum = sum(min_in over all original vertices) + recursive_result. This is correct.
// So we implement recursively.
// Implementation details:
// Function: edmonds(n, root, edges) returns min cost.
// Steps:
// if n == 1: return 0 (only root)
// Let INF large.
// // min_in[v] for v in [0..n-1], exclude root.
// vector<double> min_in(n, INF); // Use long long maybe.
// vector<int> inc_edge(n, -1); // index of the edge with minimal incoming weight to v.
// for each i, edge (u,v,w):
// if v != root and w < min_in[v]:
// min_in[v] = w;
// inc_edge[v] = i; // store edge index
// // check for any v != root with min_in[v] == INF -> no arborescence, but input guarantee.
// long long total = 0;
// for v = 0..n-1:
// if v != root and min_in[v] != INF:
// total += min_in[v];
// // reduce edges:
// for each edge i:
// if edge.v != root:
// edge.w -= min_in[edge.v]; // becomes reduced cost
// // now build selected edges from inc_edge: for each v != root, selected edge inc_edge[v] (with reduced cost 0) points to v from u.
// // Detect cycles using these selected edges.
// vector<int> used(n, 0); // 0 = unvisited, 1 = visiting, 2 = processed.
// vector<int> cycle_id(n, -1); // which cycle node belongs to. Initially -1.
// int cycles = 0; // number of cycles found.
// for v = 0..n-1:
// if v == root || used[v] != 0) continue;
// // trace path following selected incoming edges (go from current node to its predecessor via inc_edge)
// int cur = v;
// while (true) {
// if (cur == root || used[cur] == 2) {
// // no cycle: mark all visited as processed? Actually we need to mark nodes along path as processed? We'll implement a stack method.
// // Instead, do a proper DFS.
// }
// }
// Alternate approach: iterate over nodes and follow predecessor until root or a node already visited in current walk. We'll assign a "vis" array that stores the order number from the start of the current trace.
// Use array "vis" initialized to -1. For each v not visited, start a stack.
// int cnt = 0; // timestamp for nodes visited in current traversal?
// But careful: We need to detect cycles that may not be reachable from v if we start from v and follow predecessor; since each node has exactly one predecessor (except root), the graph of predecessors is a set of trees pointing to root plus cycles. So any node either leads to root (no cycle) or leads to a cycle. Starting from an unvisited node, we can walk following inc_edge[u].from (the predecessor) until we encounter a node already visited in this walk (cycle) or root or a node already assigned to a cycle or marked as processed. We can then assign cycle membership to nodes in the cycle.
// Implementation:
// vector<int> pre(n, -1); // predecessor for each node based on inc_edge.
// for v != root: if inc_edge[v] != -1: pre[v] = edges[inc_edge[v]].u else pre[v] = -1? But inc_edge should exist because min_in finite; if not, then no arborescence; but guarantee exists.
// Actually we can compute pre array:
// for v != root: pre[v] = edges[inc_edge[v]].u.
// Then we do a cycle detection on functional graph defined by pre.
// We'll use an array "comp" = -1; "state" 0=unvisited,1=in_stack,2=done.
// For each v (v != root and comp[v]==-1), do DFS:
// stack = []
// while (state[v]==0) {
// state[v]=1; stack.push(v);
// if (v == root) break; // root has no predecessor
// v = pre[v];
// }
// if (state[v]==1) then we found a cycle: from the occurrence of v in stack to end.
// assign new cycle id to those nodes.
// // set state of all nodes in stack to 2 and if not in cycle comp = -1? Actually we need to mark all nodes visited as done, and for those not in a cycle, comp remains -1.
// But we also need to treat root separately: root may be visited if we start from some node? But root has no pre, so we stop.
// Simpler: Use classic algorithm from cp-algorithms: "find_cycles" function:
// int cnt_cycles = 0;
// vector<int> used(n, 0);
// vector<int> parent(n, -1);
// for (int i = 0; i < n; ++i) parent[i] = (inc_edge[i] != -1) ? edges[inc_edge[i]].u : -1;
// for (int i = 0; i < n; ++i) {
// if (used[i] != 0 || i == root) continue;
// int v = i;
// while (used[v] == 0 && v != root) {
// used[v] = i+1; // mark with start index (so we know which traversal)
// v = parent[v];
// }
// if (used[v] == i+1) { // cycle found
// // v is in the cycle
// // assign cycle id to all nodes in the cycle
// int u = v;
// do {
// cycle_id[u] = cnt_cycles;
// u = parent[u];
// } while (u != v);
// cnt_cycles++;
// }
// }
// This works because used[v] stores the index of the start node (i+1) if visited during this traversal, or some other value if visited earlier. If we encounter a node v that has used[v] == i+1, that means we came back to a node visited in the same traversal -> cycle.
// After the loop, we have cycle_id for nodes in cycles. Others remain -1.
// If cnt_cycles == 0: break; return total.
// Else: contract.
// Create a new node numbering: total new nodes = n - sum_of_cycle_sizes + cnt_cycles.
// But we can assign new indices incrementally: new_id starts from 0. For each old vertex i: if cycle_id[i] == -1: map i -> new_id++; else, we need to map all nodes in same cycle to the same new_id. So we can create an array "new_idx" of size n, initially -1. For each old vertex, if cycle_id[i] != -1, then we assign a mapping for the whole cycle only once. We can do: for each cycle id, assign a new index. Then for each vertex, if cycle_id[i] != -1, new_idx[i] = cycle_id_new_index[cycle_id[i]]; else, new_idx[i] = new_id++ after processing cycles? Actually we need consistent mapping.
// Steps:
// vector<int> new_id(n, -1);
// int new_n = 0;
// // assign ids for cycles first, so they get a single id
// for i in 0..n-1:
// if (cycle_id[i] != -1 && new_id[cycle_id[i]] == -1) // but cycle_id is per vertex; we need mapping from cycle_id (an identifier) to new index. We can create array map_cycle(counter_cycles, -1).
// Let's do:
// vector<int> cycle_new_idx(cnt_cycles, -1);
// for (int i=0; i<n; ++i) {
// if (cycle_id[i] != -1) {
// int cid = cycle_id[i];
// if (cycle_new_idx[cid] == -1) {
// cycle_new_idx[cid] = new_n++;
// }
// new_id[i] = cycle_new_idx[cid];
// }
// }
// // then assign ids to non-cycle vertices
// for (int i=0; i<n; ++i) {
// if (cycle_id[i] == -1) {
// new_id[i] = new_n++;
// }
// }
// So new_n is total number of nodes after contraction.
// Determine new root: if root is in a cycle? It shouldn't, but just in case: if cycle_id[root] != -1, then the new root should be the contracted node representing that cycle. So new_root = new_id[root].
// Create new edges list:
// vector<Edge> new_edges;
// for each original edge e (u,v,w):
// int u2 = new_id[u];
// int v2 = new_id[v];
// if (u2 != v2) { // ignore self-loops
// // But note: The edge weight is already reduced (we subtracted min_in). Keep as is.
// new_edges.push_back(Edge(u2, v2, w));
// }
// Then recursively call edmonds(new_n, new_root, new_edges) and add its result to total. Then return total.
// This recursive call will again compute min_in for new graph, etc.
// Edge case: If after contraction, the number of nodes is 1 (only root), then recursion ends and returns 0.
// Complexity: Each recursion reduces number of nodes by at least 1 (since each contraction collapses at least 2 nodes into 1). So depth at most V. Each step we scan all edges O(E). So total O(VE) which is fine for V=100, E=1000.
// Implementation details: Use long long for weights (sum could be up to 10,000 * (100-1) = 990k, but recursion might add multiple steps, still safe in int but use long long to avoid overflow).
// Also, we need to be careful about infinite loops if no cycles? We break.
// Let's implement.
// One more nuance: In the first step, we compute min_in[v] for all v != root. But if there is a vertex v with no incoming edge, then min_in[v] = INF, which would break. However, problem states that graph has arborescence(s) with root r, so there must be at least one incoming edge for every vertex except root (or at least reachable). So min_in should be finite. However, we might still have vertices with no incoming edge? Actually an arborescence requires each vertex (except root) to have exactly one incoming edge in the final tree, but the original graph may not have a direct incoming edge? Wait, arborescence: a directed spanning tree rooted at r, so for each vertex v != r, there must be a directed path from r to v. That does not require a direct edge incoming to v; it can be via intermediate nodes. But for the minimum arborescence, the algorithm still works if some vertices have no direct incoming edge? Actually the algorithm requires that for every vertex v != r, there is at least one incoming edge (from some other vertex) in the graph. Because the first step picks minimum incoming edge for each v. If a vertex has no incoming edge, then the graph cannot have an arborescence rooted at r because you can't reach v from r? Actually if there's no incoming edge to v at all, then v has indegree 0, but then the only way to reach v from r is if v = r? No, if indegree 0, no directed path from r can end at v because any path ending at v must have an incoming edge. So indeed, an arborescence existence implies every vertex (except r) must have at least one incoming edge. So min_in[v] is finite.
// So we can safely assume.
// Let's test with examples.
// Example 1:
// 4 6 0
// 0 1 3
// 0 2 2
// 2 0 1
// 2 3 1
// 3 0 1
// 3 1 5
// Compute manually: should output 6.
// Let's simulate algorithm quickly.
// n=4, root=0.
// Compute min_in:
// v=1: incoming edges: (0,1,3), (3,1,5) => min=3, inc_edge: (0,1,3)
// v=2: incoming: (0,2,2), (2,0? that's from 2 to 0, not incoming to 2), (?? Actually edges ending at 2? none? Wait: edges: 0->1, 0->2, 2->0, 2->3, 3->0, 3->1. So incoming to 2: none? There is no edge that ends at 2. That's a problem: vertex 2 has no incoming edge? But the graph has an arborescence? Let's check: We can have arborescence from root 0 to all vertices? To reach vertex 2, we need a directed path from 0 to 2. There is edge 0->2 directly, so that's an incoming edge to 2? Wait, 0->2 is an edge from 0 to 2, so it is incoming to 2 (target is 2). Yes, 0->2 is incoming to 2. I missed: 0 2 2 means source 0, target 2, so target is 2. So yes, incoming to 2: (0,2,2). So min_in[2]=2.
// v=3: incoming: (2,3,1) only? Also maybe (?? 3->? no). So min_in[3]=1.
// root=0: ignore.
// total = 3+2+1=6.
// Reduce edges: subtract min_in from each incoming edge.
// For v=1: subtract 3 from edges to 1: (0,1,3) becomes 0; (3,1,5) becomes 2.
// v=2: subtract 2: (0,2,2) becomes 0.
// v=3: subtract 1: (2,3,1) becomes 0.
// Other edges unchanged? (2,0,1) target is root? root doesn't subtract. (3,0,1) target root, no subtraction.
// Now selected edges (inc_edge) are the ones with reduced cost 0: for v=1: (0,1,0), v=2: (0,2,0), v=3: (2,3,0). Build predecessor: pre[1]=0, pre[2]=0, pre[3]=2.
// Now detect cycles: Starting from each v:
// v=1: visited[1]=? start trace: cur=1, pre[1]=0, root -> stop, no cycle.
// v=2: pre[2]=0 -> root stop.
// v=3: pre[3]=2, visited[3] unvisited, mark then go to 2. 2 not visited? But 2 hasn't been visited? Actually we visited 2 in the loop? We are iterating v from 0..n-1. We'll check v=3: state 3 unvisited, start trace: set used[3]=4 (i+1?). Using method: for i=0..n-1, if i not visited and i!=root. Suppose i=3, used[3]==0. while used[3]==0 and 3!=root: used[3]=4 (i+1=4) maybe. then go to parent[3]=2. used[2]==0? Actually earlier we might not have visited 2 because we haven't started from 2 yet. So we set used[2]=4, then go to parent[2]=0. 0 is root, break. After loop, we check if used[v]==i+1? The v we are checking at the end of while is the last node (root), not necessarily the node that caused break. In typical implementation, they set v = node where loop terminated, then if used[v] == i+1 and v != root? Actually careful: In cp-algorithms, they use:
// for (int i = 0; i < n; ++i) {
// if (used[i] != 0 || i == root) continue;
// int v = i;
// while (used[v] == 0 && v != root) {
// used[v] = i + 1;
// v = parent[v];
// }
// if (used[v] == i + 1) {
// // cycle found, starting at v
// ...
// }
// }
// So they break when used[v]!=0 or v==root. Then after while, if used[v] == i+1, that means v was visited in this same traversal (i.e., we encountered a node that already had used[v] set to i+1). This can happen only if v != root and used[v] was set earlier in this traversal -> cycle. So it works.
// In our case for i=3: we start v=3, used[3]==0, v!=root, set used[3]=4, v=parent[3]=2. used[2]==0, v!=root, set used[2]=4, v=parent[2]=0. v==root, break loop. After loop, v=0, used[0] is not set (0 maybe root not visited), but used[0] is 0? Actually root is not set because we don't set used for root. So used[0] is 0, not equal to i+1=4. So condition fails, no cycle.
// Thus no cycles, algorithm ends, total = 6. Output 6 matches.
// Example 2:
// 6 10 0
// 0 2 7
// 0 1 1
// 0 3 5
// 1 4 9
// 2 1 6
// 1 3 2
// 3 4 3
// 4 2 2
// 2 5 8
// 3 5 3
// Output should be 11.
// Let's test algorithm mentally:
// n=6, root=0.
// Compute min_in for v !=0:
// v=1: incoming edges: (0,1,1) from 0; (2,1,6); (?? maybe others) -> min=1 (edge 0->1).
// v=2: incoming: (0,2,7); (4,2,2) -> min=2 (edge 4->2).
// v=3: incoming: (0,3,5); (1,3,2) -> min=2 (1->3).
// v=4: incoming: (1,4,9); (3,4,3) -> min=3 (3->4).
// v=5: incoming: (2,5,8); (3,5,3) -> min=3 (3->5).
// total = 1+2+2+3+3 = 11.
// Reduce edges:
// v=1 subtract 1: (0,1,1)->0; (2,1,6)->5.
// v=2 subtract 2: (0,2,7)->5; (4,2,2)->0.
// v=3 subtract 2: (0,3,5)->3; (1,3,2)->0.
// v=4 subtract 3: (1,4,9)->6; (3,4,3)->0.
// v=5 subtract 3: (2,5,8)->5; (3,5,3)->0.
// root edges unchanged? Edges with target root? none.
// Selected edges (inc_edge with reduced cost 0):
// v=1: (0,1,0)
// v=2: (4,2,0)
// v=3: (1,3,0)
// v=4: (3,4,0)
// v=5: (3,5,0) (since (3,5) weight 0 after reduction; there is also (2,5) weight 5; min was (3,5) originally weight 3, now 0)
// Build predecessors:
// pre[1]=0
// pre[2]=4
// pre[3]=1
// pre[4]=3
// pre[5]=3
// Now detect cycles:
// Process i=1 (v=1): used[1]==0, not root.
// while used[1]==0 and 1!=root: used[1]=2 (i+1=2), v=parent[1]=0 -> root, break. after loop v=0, used[0]==0, not equal to 2 -> no cycle.
// i=2 (v=2): used[2]==0, while: used[2]=3, v=parent[2]=4; used[4]==0, v!=root: used[4]=3, v=parent[4]=3; used[3]==0: used[3]=3, v=parent[3]=1; used[1]!=0? used[1] is 2 (from previous), not 0, so while condition fails (used[1]!=0) and v!=root, break. After loop, v=1, used[1]==2, not equal to 3 -> no cycle? But wait, we might have a cycle? Let's examine the selected edges: pre[1]=0, pre[2]=4, pre[3]=1, pre[4]=3, pre[5]=3. This forms a chain: 2<-4<-3<-1<-0. That's no cycle. Actually we might have a cycle if there was e.g., 4->2 and 2->? something to 4? But selected edges: pre[4]=3, pre[3]=1, pre[1]=0, so no back edge. So no cycle. But is that correct? However, the classic algorithm expects sometimes cycles? In this case, the min_in selection gave a DAG (directed acyclic) because each node points towards root eventually. That means the selected edges already form an arborescence? Let's see: edges: 0->1, 1->3, 3->4, 4->2, and 3->5. That's a tree rooted at 0? It includes all vertices? 0,1,2,3,4,5. Check: root 0 has outgoing to 1. 1 has outgoing to 3. 3 has outgoing to 4 and 5. 4 has outgoing to 2. This is a directed tree from root to all others. Indeed it's an arborescence. Total weight = 1+2+2+3+3 = 11. So algorithm stops at first iteration and returns 11, matches output.
// So algorithm works.
// Another test: Suppose there is a cycle. Let's test a known case. Example from somewhere: Graph: root 0, vertices 1,2. edges: 0->1 (1), 0->2 (2), 1->2 (1), 2->1 (1). Minimum arborescence cost? Could be 1+1=2? Actually root 0->1 (1) and 1->2 (1) =2; also 0->2 (2) and 2->1 (1)=3; or 0->1 (1) and 2->1 (1) but 2 not connected; need spanning all. So min is 2. Let's run algorithm:
// n=3, root=0.
// min_in[1]: edges: 0->1 (1), 2->1 (1) -> min=1, inc_edge could be 0->1.
// min_in[2]: edges: 0->2 (2), 1->2 (1) -> min=1, inc_edge could be 1->2.
// total=1+1=2.
// reduce: subtract min_in[1]=1: (0,1,1)->0, (2,1,1)->0; subtract min_in[2]=1: (0,2,2)->1, (1,2,1)->0.
// selected edges: for v=1: (0,1,0) or could choose (2,1,0) but we chose inc_edge[1] which was the first min edge? Typically we break ties arbitrarily; but we must choose exactly one min edge for each v. In this algorithm, we need to pick one specific incoming edge for each v (the one with smallest weight; if tie, any). The algorithm's correctness holds regardless of which min edge we pick, because after subtracting min, all min edges become zero, and we can arbitrarily choose one as the "selected" edge for cycle detection. However, careful: The choice of which zero-weight edge we use as the incoming edge for each vertex can affect the cycles we detect. But it's okay because any zero-weight incoming edge could be used; the algorithm will contract cycles and recursively solve. It should yield the same total cost. However, in some implementations, they define the "minimum incoming edge" arbitrarily (like the first encountered) and then use it to define the predecessor. It works.
// So suppose we pick for v=1: inc_edge = (0,1) (weight 0 after reduction). For v=2: inc_edge = (1,2) (weight 0 after reduction). Then predecessor: pre[1]=0, pre[2]=1. No cycle. So algorithm ends, total=2. That's correct.
// But if we had chosen inc_edge[1] = (2,1) (weight 0) and inc_edge[2] = (1,2) (weight 0), then pre[1]=2, pre[2]=1 => cycle 1<->2. Then we would contract cycle and continue. Let's see: total initially 2. After reduction, we have edges: (0,1,0), (2,1,0), (0,2,1), (1,2,0). Choose inc_edge[1]=(2,1), inc_edge[2]=(1,2). Then predecessor: pre[1]=2, pre[2]=1. Detect cycle {1,2}. Contract cycle into a supernode, say c. New mapping: vertices: 0 remains 0, cycle becomes c. Need new edges: For each original edge (u,v,w) where u and v map to different nodes:
// (0,1,0): u=0, v in cycle => edge (0, c, 0) since v maps to c.
// (2,1,0): u=2 (in cycle), v in cycle => self-loop ignore.
// (0,2,1): u=0, v in cycle => edge (0, c, 1).
// (1,2,0): u in cycle, v in cycle => ignore.
// Also edges from cycle to outside? There is no outgoing from cycle to 0? Actually there is maybe (1,? ) none; (2,?) none. So new edges: (0,c,0) and (0,c,1). New root is 0 (root not in cycle). n_new=2 (0 and c). Now call recursively:
// In recursive call: n=2, root=0. Compute min_in for c (only non-root): min_in[c] = min among incoming edges to c: (0,c,0) weight 0, (0,c,1) weight 1 => min=0, inc_edge = (0,c,0). total += 0 = 0. Reduce: subtract 0, edges unchanged (0,c,0) stays 0, (0,c,1) stays 1. Selected edge for c: (0,c,0). Pre[c]=0 -> no cycle. Return 0. So final total = 2+0 = 2. Same result.
// So algorithm works regardless of tie-breaking.
// However, we need to be careful: In the first step, we compute min_in and store inc_edge as the edge with minimum weight (and if multiple, we can choose any, e.g., the first encountered). It's fine.
// Implementation steps more concretely:
// Define a struct Edge { int u, v; long long w; };
// Function long long edmonds(int n, int root, vector<Edge> edges) {
// const long long INF = 1e18;
// long long res = 0;
// while (true) {
// // Step 1: find minimum incoming edge for each vertex
// vector<long long> min_in(n, INF);
// vector<int> inc_edge_idx(n, -1);
// for (int i = 0; i < edges.size(); ++i) {
// int v = edges[i].v;
// if (v == root) continue;
// if (edges[i].w < min_in[v]) {
// min_in[v] = edges[i].w;
// inc_edge_idx[v] = i;
// }
// }
// // check if any vertex (except root) has min_in INF -> error, but problem says exists.
// for (int v = 0; v < n; ++v) {
// if (v != root && min_in[v] == INF) {
// // no arborescence, but we'll return something like -1.
// }
// }
// // add to result
// for (int v = 0; v < n; ++v) {
// if (v != root && min_in[v] != INF) {
// res += min_in[v];
// }
// }
// // Step 2: reduce edges and build parent array
// vector<int> parent(n, -1);
// for (int v = 0; v < n; ++v) {
// if (v != root && inc_edge_idx[v] != -1) {
// Edge e = edges[inc_edge_idx[v]];
// parent[v] = e.u; // predecessor
// }
// }
// // subtract min_in
// for (Edge &e : edges) {
// if (e.v != root) {
// e.w -= min_in[e.v];
// }
// }
// // Step 3: find cycles using parent
// vector<int> used(n, 0); // 0=unvisited, 1=visiting? Actually we'll use the method with start index.
// vector<int> cycle_id(n, -1);
// int cycles = 0;
// for (int i = 0; i < n; ++i) {
// if (i == root || used[i] != 0) continue;
// int v = i;
// // trace until we hit visited or root
// while (used[v] == 0 && v != root) {
// used[v] = i+1; // mark with start index (i+1 to avoid 0)
// v = parent[v];
// }
// // If we ended on a node that was visited in this same traversal, we found a cycle
// if (used[v] == i+1) {
// // v is in the cycle
// int u = v;
// do {
// cycle_id[u] = cycles;
// u = parent[u];
// } while (u != v);
// cycles++;
// }
// }
// if (cycles == 0) {
// break; // no cycles, we have answer
// }
// // Step 4: contract cycles
// // assign new ids
// vector<int> new_id(n, -1);
// int new_n = 0;
// // first assign ids to cycles (each cycle gets a new id)
// for (int i = 0; i < n; ++i) {
// if (cycle_id[i] != -1) {
// int cid = cycle_id[i];
// if (new_id[cid] == -1) { // but new_id is per original vertex? Actually we need mapping from cycle id to new index. We'll use separate array.
// }
// }
// }
// // Actually we need:
// vector<int> cycle_new_idx(cycles, -1);
// for (int i = 0; i < n; ++i) {
// if (cycle_id[i] != -1) {
// int cid = cycle_id[i];
// if (cycle_new_idx[cid] == -1) {
// cycle_new_idx[cid] = new_n++;
// }
// new_id[i] = cycle_new_idx[cid];
// }
// }
// // assign ids to non-cycle vertices
// for (int i = 0; i < n; ++i) {
// if (cycle_id[i] == -1) {
// new_id[i] = new_n++;
// }
// }
// // new root id
// int new_root = new_id[root];
// // create new edges
// vector<Edge> new_edges;
// for (Edge e : edges) {
// int u2 = new_id[e.u];
// int v2 = new_id[e.v];
// if (u2 != v2) {
// new_edges.push_back(Edge(u2, v2, e.w));
// }
// }
// // recursive call
// res += edmonds(new_n, new_root, new_edges);
// return res; // after recursion, we can break the loop and return
// }
// return res;
// }
// However, note that after we contract and recursively call, we should return the result immediately (since the recursion will handle further cycles). So the while loop is essentially just one iteration unless we break early. Many implementations use recursion or iteration with while and contraction. I'll implement a recursive function as described.
// But caution: In the while loop above, we might need to break after recursion? Actually the algorithm is usually implemented as a function that does the steps and if cycles found, it contracts and calls itself on the contracted graph, then returns sum. So we can structure as:
// long long dmst(int n, int root, vector<Edge> edges) {
// if (n <= 1) return 0;
// // Step 1-2 as above, compute min_in etc.
// // Step 3 detect cycles.
// if (no cycles) return total;
// // else contract and return total + dmst(new_n, new_root, new_edges);
// }
// That's simpler.
// I'll implement that.
// Edge cases: If there are multiple edges, fine.
// Test with example.
// Additional nuance: The root may be part of a cycle? In selected edges, root has no incoming edge, so it cannot be in a cycle. So safe.
// However, it's possible that after contraction, the root gets mapped to a supernode (if root was in a cycle). But that cannot happen because root has no incoming edge, and cycles arise from following selected incoming edges. Since root has no incoming selected edge, it cannot be part of a cycle. So root remains outside cycles.
// Implementation details:
// - Use long long for weights.
// - In step 1, for vertices with no incoming edge, min_in remains INF. But we can early exit if that happens, but problem says arborescence exists, so we can assume INF won't happen. However, to be safe, we could check and return INF (error). But we can also ignore because it's guaranteed.
// - For parent array: some vertices may have inc_edge_idx == -1 if min_in is INF. But if min_in is INF, we have error. So we can skip those or handle.
// - In cycle detection, we should only consider vertices with parent != -1? Actually if min_in[v] is INF, parent[v] would be -1. But those vertices would not have been part of any cycle anyway, but also they might cause issues in traversal. Since we guarantee existence, min_in is finite, so parent is defined for all non-root vertices.
// - But what if after reduction, we have a vertex v with min_in finite but inc_edge_idx[v] = some index, then parent[v] is defined. So fine.
// - In the while loop for detecting cycles: while (used[v] == 0 && v != root) we also need to ensure parent[v] != -1? Actually if v != root and min_in finite, parent is defined; but if we accidentally have a vertex with parent -1 (should not happen for non-root), then the while loop might break because v != root but parent[v] = -1. In that case, when we set v = parent[v] we would get -1; that would cause out-of-bounds. So we should ensure that for all non-root vertices, parent is set to something valid. Since min_in finite, inc_edge_idx exists, so parent set. So safe.
// - However, in the detection code, we need to access parent[v] inside while. To be safe, we could add condition: if (parent[v] == -1) break; but not needed.
// - Used array: we use int for marking the start index (i+1). Since i max is n-1, i+1 <= 100, fits.
// - After cycle detection, we may have some vertices that are not in cycles. Good.
// - For contraction mapping: new_id for cycle vertices uses cycle_new_idx per cycle id.
// - Then we assign new_id for non-cycle vertices sequentially.
// - Important: new_n should be the number of distinct supernodes after contraction. Since we assign new ids in order, new_n will be exactly cycles + (# non-cycle vertices). But we must count non-cycle vertices exactly once each. However, we assign new_id for each original vertex; for non-cycle vertices, we assign a new unique id (new_n++). So new_n ends up as total number of supernodes.
// - The root's new_id will be assigned either as a non-cycle vertex (since root not in cycle) or if root in cycle (shouldn't), it would get cycle_new_idx. But we ignore.
// - Then new_edges: for each original edge, map endpoints and add if u2 != v2.
// - Then recursively call dmst(new_n, new_root, new_edges). new_root = new_id[root].
// - The recursion will add its own total.
// - Finally return total + recursive result.
// Let's test a scenario with cycle.
// I'll test a simple case: n=3, root=0, edges: 0->1 (5), 1->2 (6), 2->1 (3). (Actually 2->1 weight 3). Also maybe 0->2 (10). And need to cover all vertices. Minimum arborescence? Possibly pick 0->1 (5) and 1->2 (6) = 11, or 0->2 (10) and 2->1 (3) =13, or 0->1 (5) and 2->1 (3) but 2 not connected; So min is 11. However, does algorithm handle cycle? Let's compute.
// Step 1: min_in[1]: edges: (0,1,5), (2,1,3) -> min=3 (edge 2->1). min_in[2]: edges: (1,2,6) (0,2,10) -> min=6 (edge 1->2). total=3+6=9.
// Reduce: subtract min_in[1]=3: (0,1,5)->2, (2,1,3)->0. subtract min_in[2]=6: (1,2,6)->0, (0,2,10)->4.
// Selected edges: inc_edge[1] = (2,1) weight 0; inc_edge[2] = (1,2) weight 0. parent[1]=2, parent[2]=1. So cycle between 1 and 2.
// Cycle detection: detect cycle with vertices 1,2. cycles=1, cycle_id[1]=0, cycle_id[2]=0.
// Contraction: assign new id for cycle: cycle_new_idx[0] = 0 (new_n=1). Then assign new ids for non-cycle vertices: root 0 gets new_id[0] = new_n++ = 1? Actually we assign for each non-cycle vertex: loop over i=0..n-1, if cycle_id[i]==-1: new_id[i] = new_n++. So for i=0 (root): new_id[0] = 1 (since new_n was 1, after assignment becomes 2). So new_n = 2. So supernodes: cycle -> 0, root -> 1. new_root = new_id[root] = 1.
// Build new edges: original edges after reduction: (0,1,2), (2,1,0), (1,2,0), (0,2,4). Map:
// (0,1,2): u=0 -> new_id[0]=1, v=1 -> new_id[1]=0 => edge (1,0,2)
// (2,1,0): u=2->new_id[2]=0, v=1->0 => self-loop ignore.
// (1,2,0): u=1->0, v=2->0 => self-loop ignore.
// (0,2,4): u=0->1, v=2->0 => edge (1,0,4)
// So new edges: (1,0,2) and (1,0,4). Now recursively call dmst(2, root=1, edges). Note: root is 1, non-root vertex is 0.
// Recursion: n=2, root=1.
// Step 1: min_in for v=0 (non-root): incoming edges: (1,0,2) and (1,0,4) -> min=2. total=2.
// Reduce: subtract 2: (1,0,2)->0, (1,0,4)->2.
// Selected inc_edge[0] = (1,0,0) (the first min edge). parent[0]=1.
// Cycle detection: none (since only root and one other).
// So return total = 2.
// Back to first call: total_initial = 9, plus recursive 2 = 11. That matches expected min arborescence (0->1 (5) + 1->2 (6) = 11? Wait 5+6 = 11. Our result 11. Good. Note that initial total (9) was sum of min_in (3+6=9) plus recursive (2) = 11. But is that correct? Let's see actual selected edges after expanding: In cycle, we selected originally 2->1 (3) and 1->2 (6) within cycle. After contraction, we selected edge from root to cycle with reduced cost 2 (which came from original edge (0,1,5) reduced to 2). The reduced cost 2 means that replacing the min_in edge of vertex 1 (which was 2->1 weight 3) with edge 0->1 weight 5 adds extra cost 2. So final tree: we keep edge from root to 1 (0->1, weight 5) and edge 1->2 (weight 6), and we drop 2->1. So total 5+6=11. Yes.
// So algorithm works.
// Edge Cases: multiple cycles, nested cycles, etc. Should be fine.
// Implementation details:
// Use recursion; base case: if n <= 1 return 0. However, we should also handle the case where after contraction we have a single node (root only) and then return 0.
// For the recursion, we need to be careful about the fact that we modify the edges list (reducing weights) before passing to recursion. That's fine as we create a new vector.
// Potential pitfalls:
// - When we subtract min_in[v] from edges, we modify the original edges list which will be used later for contraction and building new edges. That's okay as long as we pass the reduced weights to the next recursion.
// - However, careful: In the recursion, we will again compute min_in on the reduced graph, and subtract again, etc. That's correct.
// - In the contraction step, we use the edges after reduction. That's fine.
// - After contraction, we create new edges with the same weights (reduced). The recursive call will add its own min_in values, which correspond to additional costs.
// - Need to ensure that we don't exceed recursion depth: V max 100, recursion depth at most 100, fine.
// - Use 64-bit integers for total to avoid overflow.
// - Since edges list can be up to 1000, recursion will not blow memory.
// - The function signature: long long dmst(int n, int root, const vector<Edge>& edges). But we will need to modify edges (reduce) inside the function. So we'll work on a copy. Actually we should pass a copy? In recursion we will create new contracted edges, so we can pass by value. At start of function, we receive edges. We'll compute min_in based on them, then reduce them, then detect cycles, etc. But reducing modifies the edges in place; that's okay because we don't need original values afterwards. However, if we later need the original weights for something else? No, we only need reduced weights for contraction. So we can take edges by value (copy) or modify a local copy. But recursion will call with new edges anyway. So we can declare the function as:
// long long dmst(int n, int root, vector<Edge> edges) // pass by value, so we have a copy to modify.
// Alternatively, we can pass by reference but careful not to modify original if needed later. Since we don't need original after, passing by value is simpler and safe, though might copy edges each time. With max recursion depth 100 and edges up to 1000, total copies 100*1000=100k edges, each edge 3 ints, it's fine.
// So we'll do that.
// Implementation steps in code:
// #include <bits/stdc++.h>
// using namespace std;
// struct Edge { int u, v; long long w; };
// long long dmst(int n, int root, vector<Edge> edges) {
// if (n <= 1) return 0;
// const long long INF = 1e18;
// vector<long long> min_in(n, INF);
// vector<int> inc_edge_idx(n, -1);
//
// // find min incoming edge for each vertex (excluding root)
// for (int i = 0; i < edges.size(); ++i) {
// int v = edges[i].v;
// if (v == root) continue;
// if (edges[i].w < min_in[v]) {
// min_in[v] = edges[i].w;
// inc_edge_idx[v] = i;
// }
// }
//
// // Check for unreachable vertices (should not happen)
// for (int v = 0; v < n; ++v) {
// if (v != root && min_in[v] == INF) {
// // No arborescence
// // In contest, maybe return INF or -1, but problem guarantees existence.
// // For safety, we can return a large number or assert.
// }
// }
//
// long long total = 0;
// for (int v = 0; v < n; ++v) {
// if (v != root) {
// total += min_in[v];
// }
// }
//
// // Build parent array from chosen edges
// vector<int> parent(n, -1);
// for (int v = 0; v < n; ++v) {
// if (v != root && inc_edge_idx[v] != -1) {
// parent[v] = edges[inc_edge_idx[v]].u;
// }
// }
//
// // Subtract min_in from all incoming edges (to get reduced costs)
// for (auto& e : edges) {
// if (e.v != root) {
// e.w -= min_in[e.v];
// }
// }
//
// // Detect cycles using parent
// vector<int> used(n, 0); // 0 = unvisited
// vector<int> cycle_id(n, -1);
// int cycles = 0;
//
// for (int i = 0; i < n; ++i) {
// if (i == root || used[i] != 0) continue;
// int v = i;
// while (v != root && used[v] == 0) {
// used[v] = i+1;
// v = parent[v];
// }
// if (used[v] == i+1) { // found a cycle
// int u = v;
// do {
// cycle_id[u] = cycles;
// u = parent[u];
// } while (u != v);
// cycles++;
// }
// }
//
// if (cycles == 0) {
// return total; // no cycles, we have the answer
// }
//
// // Contract cycles
// vector<int> new_id(n, -1);
// int new_n = 0;
// vector<int> cycle_new_idx(cycles, -1);
// // assign ids for vertices in cycles
// for (int i = 0; i < n; ++i) {
// if (cycle_id[i] != -1) {
// int cid = cycle_id[i];
// if (cycle_new_idx[cid] == -1) {
// cycle_new_idx[cid] = new_n++;
// }
// new_id[i] = cycle_new_idx[cid];
// }
// }
// // assign ids for non-cycle vertices
// for (int i = 0; i < n; ++i) {
// if (cycle_id[i] == -1) {
// new_id[i] = new_n++;
// }
// }
//
// int new_root = new_id[root];
//
// // Build new edges
// vector<Edge> new_edges;
// for (auto& e : edges) {
// int u2 = new_id[e.u];
// int v2 = new_id[e.v];
// if (u2 != v2) {
// new_edges.push_back({u2, v2, e.w});
// }
// }
//
// return total + dmst(new_n, new_root, new_edges);
// }
// This should work.
// But careful: In the while loop for detecting cycles, we have condition while (v != root && used[v] == 0). However, if v becomes root, we exit loop, and then used[root] is whatever (maybe 0) and the condition used[v] == i+1 will be false. Good. But we also need to consider case where parent[v] is -1? That shouldn't happen for non-root because min_in finite, so parent set. But if a vertex v has min_in INF (should not), then parent[v] = -1, and in while loop if used[v]==0, v != root, we set used[v]=i+1, then v = parent[v] = -1. That would cause out-of-range. So we should check if parent[v] == -1, break. To be safe, we can add condition: if (parent[v] == -1) break; before updating v. But as argued, not needed given guarantee. However, let's include a check to avoid segfault: while (v != root && used[v] == 0) { used[v] = i+1; if (parent[v] == -1) break; else v = parent[v]; } But if parent[v]==-1 and v!=root, we break; then after loop, used[v]? v is -1? Actually we assign v = parent[v] after using it; but if we break, we don't update v again. In code, we would need to break out of while completely. Simpler: we can ensure parent is defined for all non-root vertices by initializing parent for all non-root vertices (even if min_in INF, we could set parent to -1, but then while will attempt to go to parent -1. So to be safe, before entering while, we can check if parent[i] == -1, skip? But it shouldn't happen. Since problem guarantee, we can assume.
// I'll still include a condition to avoid infinite loops: while (v != root && used[v] == 0 && parent[v] != -1) { used[v] = i+1; v = parent[v]; } But if parent[v]==-1 and v!=root and used[v]==0, then the loop would stop because condition parent[v]!=-1 fails, so we exit. After loop, used[v] might be 0? Actually v remains as is, but we haven't set used[v] because we only set when entering loop. If parent[v]==-1 and v != root, we would not enter the loop? Because condition includes parent[v]!=-1? But then we would never mark v as used. That could cause it to be considered again later? But we are iterating over i, and for that i we would skip because used[i] may still be 0? Actually we start with v = i, if parent[i]==-1, then the while condition fails (since parent[i]==-1). So we do nothing, then move to next i. That's okay because vertex i has no parent and no cycle; it's isolated? But not possible for arborescence. So we can accept.
// For simplicity, given constraints guarantee existence, we'll not overcomplicate.
// Let's also note that the root may be 0 based indexing. The input vertices are from 0 to |V|-1.
// Now, test with provided examples.
// We'll run through example 1:
// Input:
// 4 6 0
// edges as above.
// n=4, root=0.
// Compute min_in: [inf,3,2,1] (v=0 ignored)
// total = 3+2+1 =6.
// parent: 1->0, 2->0, 3->2.
// reduce: subtract accordingly.
// used detection: cycles=0, return total=6. Output 6.
// Example 2: total=11, cycles=0, return 11.
// Works.
// Additional tests: Cases where cycles exist.
// Let's test a known case from book: n=4, root=0. Edges:
// 0->1 2
// 0->2 3
// 1->2 1
// 2->1 4
// 1->3 5
// 2->3 6
// Expected minimum arborescence? Possibly 0->1 (2), 1->2 (1), 1->3 (5) total 8? But need to cover all. That includes 0,1,2,3: 0->1, 1->2, 1->3 = 2+1+5=8. Alternative: 0->2 (3), 2->1 (4), 2->3 (6) = 13. Another: 0->1 (2), 2->1 (4) not connected. So min 8. Let's run algorithm:
// Step1: min_in[1]: edges: 0->1 (2), 2->1 (4) -> min=2 (0->1)
// min_in[2]: edges: 0->2 (3), 1->2 (1) -> min=1 (1->2)
// min_in[3]: edges: 1->3 (5), 2->3 (6) -> min=5 (1->3)
// total = 2+1+5=8.
// reduce: subtract min_in[1]=2: 0->1:0, 2->1:2
// subtract min_in[2]=1: 0->2:2, 1->2:0
// subtract min_in[3]=5: 1->3:0, 2->3:1
// parent: 1->0, 2->1, 3->1
// used: no cycles (0->1,1->2,1->3), so return 8. So algorithm gives correct answer without cycle contraction.
// Now a case with cycle:
// Graph: root 0, vertices 1,2,3. Edges:
// 0->1 (10), 0->2 (9), 1->2 (8), 2->1 (5), 1->3 (4), 2->3 (3).
// Expected min arborescence? We need to reach all. Options:
// Option A: 0->1(10), 1->2(8), 1->3(4) = 22.
// Option B: 0->2(9), 2->1(5), 2->3(3) = 17.
// Option C: 0->1(10), 2->1(5), 2->3(3) but 2 not reached; can't.
// Option D: 0->2(9), 1->2(8), 1->3(4) but 1 not reached.
// So min is 17. Let's run algorithm.
// Step1: min_in[1]: edges: 0->1(10), 2->1(5) -> min=5 (2->1)
// min_in[2]: edges: 0->2(9), 1->2(8) -> min=8 (1->2) or 9? 8 is smaller, so min=8 (1->2)
// min_in[3]: edges: 1->3(4), 2->3(3) -> min=3 (2->3)
// total = 5+8+3=16.
// reduce: subtract min_in[1]=5: 0->1:5, 2->1:0
// subtract min_in[2]=8: 0->2:1, 1->2:0
// subtract min_in[3]=3: 1->3:1, 2->3:0
// parent: 1->2 (since inc_edge[1] is (2,1) with weight 0 after reduction? Actually min_in[1] was 5 from edge (2,1) originally weight 5. After reduction, its weight becomes 0, so inc_edge[1] points to that edge, parent[1]=2.)
// parent[2]: inc_edge[2] = (1,2) weight 0, parent[2]=1.
// parent[3]: inc_edge[3] = (2,3) weight 0, parent[3]=2.
// So we have a cycle? Let's see: parent[1]=2, parent[2]=1 -> cycle between 1 and 2. Also parent[3]=2, so 3 points to 2 which is in the cycle.
// used detection: start from i=1: v=1, while: used[1]=2, v=parent[1]=2; used[2]=0 -> used[2]=2, v=parent[2]=1; used[1] is 2, so condition used[v]==i+1? i+1=2, used[1]==2, so cycle found. cycle includes nodes 1 and 2? Actually start at v=2? Let's follow: after while loop, we exit when used[v] != 0? In code: while (v != root && used[v] == 0) { used[v] = i+1; v = parent[v]; } For i=1, start v=1: used[1]==0, set used[1]=2, v=parent[1]=2. used[2]==0, set used[2]=2, v=parent[2]=1. Now used[1]==2 !=0, so while condition fails because used[1] != 0, exit loop. After loop, v = 1 (since we set v=1 after last assignment? Actually we updated v to 1, then loop condition checks used[1] (which is 2) != 0, so we exit without entering the body again). So after loop, v=1. Then check if used[v] == i+1: used[1] == 2, true, so cycle found starting at v=1. Then we do do-while: u = v=1; do { cycle_id[u]=cycles; u=parent[u]; } while (u != v). parent[1]=2, cycle_id[2]=cycles; u=parent[2]=1, loop ends. So cycle includes 1 and 2.
// cycles = 1. cycle_id[1]=0, cycle_id[2]=0. Vertex 3 not in cycle.
// Now contract: assign new ids: cycle gets new id 0 (cycle_new_idx[0]=0, new_n=1). Then non-cycle vertices: root 0 (cycle_id=-1) -> new_id[0]= new_n++ => 1. Vertex 3 (cycle_id=-1) -> new_id[3]= new_n++ => 2. So new_n = 3. new_root = new_id[0] = 1.
// Build new edges from reduced edges list:
// Reduced edges:
// (0,1,5)
// (2,1,0)
// (0,2,1)
// (1,2,0)
// (1,3,1)
// (2,3,0)
// Map to new ids:
// (0,1,5): u=0->1, v=1->0 => edge (1,0,5)
// (2,1,0): u=2->0, v=1->0 => self-loop ignore.
// (0,2,1): u=0->1, v=2->0 => edge (1,0,1) (but note v=2 is cycle? Actually vertex 2 is in cycle, new_id=0. So (1,0,1))
// (1,2,0): u=1->0, v=2->0 => self-loop ignore.
// (1,3,1): u=1->0, v=3->2 => edge (0,2,1)
// (2,3,0): u=2->0, v=3->2 => edge (0,2,0)
// So new edges: (1,0,5), (1,0,1), (0,2,1), (0,2,0).
// Recursive call: dmst(3, root=1, edges). Now we have vertices: 0 (cycle), 1 (root), 2 (vertex 3). Edges: from root (1) to 0 with weights 5 and 1; from 0 to 2 with weights 1 and 0.
// Recursion: n=3, root=1. Compute min_in for non-root vertices: v=0, v=2.
// For v=0: incoming edges: (1,0,5), (1,0,1) -> min=1. inc_edge[0] could be (1,0,1).
// For v=2: incoming edges: (0,2,1), (0,2,0) -> min=0. inc_edge[2] = (0,2,0).
// total = 1+0=1.
// Reduce: subtract min_in[0]=1: (1,0,5)->4, (1,0,1)->0. subtract min_in[2]=0: (0,2,1)->1, (0,2,0)->0.
// parent: parent[0] = 1 (from inc_edge[0]), parent[2] = 0.
// used detection: check cycles: start i=0? Actually vertices 0 and 2. Since parent[2]=0, parent[0]=1 (root). So no cycles.
// So recursion returns total=1.
// Back to first call: total_initial = 16, plus 1 = 17. Expected answer 17. Good.
// So algorithm works.
// Now complexity: In the worst case, each recursion reduces at least one node (since a cycle of at least 2 nodes contracts into 1, reducing node count). So recursion depth <= V. Each step processes O(E) edges. So O(VE) = 100*1000=100k, fine.
// Implementation details: Need to be careful about large INF: use something like 1e18.
// Also, the input may have multiple edges, loops? Loops (u==v) should be ignored? Typically loops are not useful for arborescence because a node cannot have an incoming edge from itself, but they can be present. In the algorithm, they are just edges with u==v, but when v != root, min_in might consider them? A loop edge (v->v) is not helpful because it doesn't connect from another node; but it could be considered as incoming to v. However, an arborescence cannot include a loop because it would not be a tree. But the algorithm might treat it as a valid incoming edge; that could cause issues? Actually the algorithm expects that for each vertex v != root, the selected incoming edge must come from a different vertex (since otherwise it would be a loop). But if a loop is the minimum incoming edge, then parent[v]=v, leading to a self-cycle? That would be a cycle of length 1. However, a loop edge is not allowed in arborescence because it would not be a tree. But the algorithm as described would still work? Self-loop would be a cycle of one vertex; contraction would treat it as a cycle, but the edge would be a self-loop, and after contraction, it might cause issues? Usually in directed MST, we assume no self-loops because they are irrelevant. However, the input might include them? The problem statement doesn't forbid, but typical graph may have them. Since constraints say G has arborescence(s) with root r, meaning there exists at least one arborescence. If there is a self-loop, it doesn't affect existence. However, if a vertex's minimum incoming edge is a self-loop, then that would be selected, leading to a cycle of length 1, and then the algorithm would contract it. But is that correct? In the theory, self-loop edges are not considered because they don't help connect the vertex to the rest; but the algorithm might still produce a valid answer? Let's think: The initial step picks min_in for each vertex v. If the minimum weight incoming edge is a self-loop (v->v), then min_in[v] is that weight. Then total adds that weight. But then in the selected edges, v has parent = v (self-loop). This creates a cycle of length 1. When we contract that cycle, we treat it as a supernode. However, the resulting contracted graph would have the same number of nodes? Actually contracting a single node into a supernode reduces node count by 0 (since one node becomes one supernode). That would not reduce node count, causing infinite recursion? Actually if we contract a cycle of length 1, we would map that vertex to a new supernode, but that supernode is just the same as the vertex itself, no reduction. The algorithm expects that each contraction reduces the number of nodes, otherwise it could loop. Typically, self-loops are ignored or not considered because they cannot be part of any arborescence. The standard Chu-Liu/Edmonds algorithm assumes that there are no self-loops (or they are removed) because they are irrelevant. In practice, we can simply ignore edges where u == v when building the graph, as they cannot be used in an arborescence (since each node except root needs exactly one incoming edge from a distinct node, and a loop does not provide connectivity). So we can safely discard self-loops from the input edges. The problem might not include them, but to be safe, we can filter them out.
// Similarly, edges with source = target should be ignored because they are useless for spanning arborescence. So in reading edges, we can skip if s == t? But the problem may not have such edges. However, it's better to ignore them because they could cause issues. So while reading, we can only add edge if s != t.
// Also, note that multiple edges are fine.
// Implementation:
// int main() {
// int V, E, r;
// cin >> V >> E >> r;
// vector<Edge> edges;
// for (int i=0; i<E; i++) {
// int s, t, w;
// cin >> s >> t >> w;
// if (s == t) continue; // ignore self-loop
// edges.push_back({s, t, (long long) w});
// }
// long long ans = dmst(V, r, edges);
// cout << ans << endl;
// return 0;
// }
// That's it.
// One more nuance: In the dmst function, we used 'int' for node indices. But after contraction, the number of nodes could be up to V. We'll use int.
// Also, we need to be careful about using 'new_id' array of size n (original number). In recursion, the input n might be less than original V, but we allocate arrays based on that n. That's fine.
// Edge case: When n is 0? Not possible; at least 1.
// Let's code.
// I'll write the function dmst.
// Let's implement now in the final answer.</think> ```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
struct Edge {
int u, v;
ll w;
};
// Minimum Cost Arborescence (Directed MST) rooted at root
// using Chu–Liu/Edmonds' algorithm.
ll dmst(int n, int root, vector edges) {
if (n <= 1) return 0;
code
const ll INF = 1e18;
// ---------- step 1: minimum incoming edge for each vertex ----------
vector<ll> min_in(n, INF); // minimum weight entering v
vector<int> inc_edge_idx(n, -1); // index of that edge
for (size_t i = 0; i < edges.size(); ++i) {
int v = edges[i].v;
if (v == root) continue;
if (edges[i].w < min_in[v]) {
min_in[v] = edges[i].w;
inc_edge_idx[v] = i;
}
}
// The problem guarantees an arborescence exists, so every min_in[v] is finite.
ll total = 0;
for (int v = 0; v < n; ++v) {
if (v != root) {
total += min_in[v];
}
}
// ---------- step 2: reduce weights and build parent array ----------
vector<int> parent(n, -1); // predecessor in the chosen 0‑weight subgraph
for (int v = 0; v < n; ++v) {
if (v != root && inc_edge_idx[v] != -1) {
parent[v] = edges[inc_edge_idx[v]].u;
}
}
// subtract min_in from every incoming edge (except to the root)
for (auto& e : edges) {
if (e.v != root) {
e.w -= min_in[e.v];
}
}
// ---------- step 3: find cycles in the 0‑weight chosen edges ----------
vector<int> used(n, 0); // 0 = unvisited, otherwise start‑index+1
vector<int> cycle_id(n, -1); // which cycle a vertex belongs to
int cycles = 0;
for (int i = 0; i < n; ++i) {
if (i == root || used[i] != 0) continue;
int v = i;
// walk along parent pointers
while (v != root && used[v] == 0) {
used[v] = i + 1;
v = parent[v];
}
// if we returned to a vertex visited in this walk → cycle
if (used[v] == i + 1) {
int u = v;
do {
cycle_id[u] = cycles;
u = parent[u];
} while (u != v);
++cycles;
}
}
// if no cycles, the current selection is already optimal
if (cycles == 0) {
return total;
}
// ---------- step 4: contract each cycle into a supernode ----------
vector<int> new_id(n, -1); // mapping from old vertex to new index
int new_n = 0;
vector<int> cycle_new_idx(cycles, -1);
// assign one new id per cycle
for (int i = 0; i < n; ++i) {
if (cycle_id[i] != -1) {
int cid = cycle_id[i];
if (cycle_new_idx[cid] == -1) {
cycle_new_idx[cid] = new_n++;
}
new_id[i] = cycle_new_idx[cid];
}
}
// assign ids to vertices not in any cycle
for (int i = 0; i < n; ++i) {
if (cycle_id[i] == -1) {
new_id[i] = new_n++;
}
}
int new_root = new_id[root];
// build the contracted graph (discard self‑loops)
vector<Edge> new_edges;
for (auto& e : edges) {
int u2 = new_id[e.u];
int v2 = new_id[e.v];
if (u2 != v2) {
new_edges.push_back({u2, v2, e.w});
}
}
// ---------- recursive call ----------
return total + dmst(new_n, new_root, new_edges);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int V, E, r;
cin >> V >> E >> r;
vector<Edge> edges;
for (int i = 0; i < E; ++i) {
int s, t, w;
cin >> s >> t >> w;
if (s == t) continue; // self‑loops are useless
edges.push_back({s, t, (ll)w});
}
ll ans = dmst(V, r, edges);
cout << ans << "\n";
return 0;