luogu#P4716. 【模板】最小树形图

【模板】最小树形图

Background

This is a template problem.

Problem Description

Given a directed graph with nn nodes and mm directed edges. Find a minimum arborescence rooted at node rr, and output the sum of the weights of all edges in the minimum arborescence. If there is no minimum arborescence rooted at rr, output 1-1.

Input Format

The first line contains three integers n,m,rn, m, r, with the same meanings as described in the statement.

The next mm lines each contain three integers u,v,wu, v, w, indicating that there is a directed edge from uu to vv with weight ww.

Output Format

If the original graph has a minimum arborescence rooted at rr, output the sum of the weights of all edges in the minimum arborescence; otherwise output 1-1.

4 6 1
1 2 3
1 3 1
4 1 2
4 2 2
3 2 1
3 4 1
3
4 6 3
1 2 3
1 3 1
4 1 2
4 2 2
3 2 1
3 4 1
4
4 6 2
1 2 3
1 3 1
4 1 2
4 2 2
3 2 1
3 4 1
-1

Hint

Sample 11 Explanation

The minimum arborescence contains edges 22, 55, and 66, with total weight 1+1+1=31 + 1 + 1 = 3.

Sample 22 Explanation

The minimum arborescence contains edges 33, 55, and 66, with total weight 2+1+1=42 + 1 + 1 = 4.

Sample 33 Explanation

A minimum arborescence cannot be formed, so output 1-1.

Constraints

For all testdata, 1u,vn1001 \leq u, v \leq n \leq 100, 1m1041 \leq m \leq 10^4, 1w1061 \leq w \leq 10^6.

Translated by ChatGPT 5