Under construction

Still being built. Things may change

Minimum Spanning Arborescence

Time limit2sMemory limit1024 MB

Summary
Find the minimum total weight of a spanning arborescence rooted at r in a directed weighted graph, or report -1 if none exists.
Level

Hard8 of 10

Topics
Minimum spanning tree, Graph, Union-find, Heap
Solved
No attempts yet

Problem

An arborescence G=(V,A)G=(V,A) is a directed graph that satisfies the following conditions.

  • There is a vertex r∈Vr \in V such that for every vertex v∈Vv \in V, there is a path from rr to vv. This vertex rr is called the root node.
  • Let EE be the set of edges of AA with their directions removed. The undirected graph G′=(V,E)G'=(V,E) is a tree.

You are given a directed graph G=(V,A)G=(V,A) with weighted edges and no cycles, along with a vertex rr. Each vertex is numbered from 11 to NN. You need to find the minimum total edge weight among all spanning arborescences whose root node is rr.

The Chu-Liu-Edmonds' algorithm runs in O(∣V∣∣A∣)O(|V||A|), and Tarjan's improvement of it runs in O(∣A∣log⁡∣V∣)O(|A| \log |V|). However, this problem does not ask you to use that algorithm.

Find the minimum total weight of a spanning arborescence rooted at rr in the given graph.

Input

The first line contains the number of vertices NN, the number of edges MM, and the root vertex rr, separated by spaces. (1≤N≤500 0001 \le N \le 500\,000; 0≤M≤1 000 0000 \le M \le 1\,000\,000; 1≤r≤N1 \le r \le N)

From the second line through the (M+1)(M+1)-th line, each line contains three integers uu, vv, and cc, separated by spaces. This means there is an edge from vertex uu to vertex vv with weight cc. (1≤u,v≤N1 \le u, v \le N; u≠vu \ne v; 1≤c≤1 000 000 0001 \le c \le 1\,000\,000\,000)

Any two vertices are connected by at most one edge in the given graph, and the graph has no cycles.

Output

Print the minimum total edge weight of a spanning arborescence rooted at rr. If no spanning arborescence rooted at rr exists, print -1.

Examples3

  1. Example 1

    Input
    3 3 1
    1 2 1
    1 3 2
    2 3 3
    
    Expected output
    3
    
  2. Example 2

    Input
    3 3 1
    1 2 1
    1 3 4
    2 3 3
    
    Expected output
    4
    
  3. Example 3

    Input
    2 1 1
    2 1 10
    
    Expected output
    -1