QOJ.ac

QOJ

Time Limit: 5 s Memory Limit: 512 MB Hackable ✓

# 904. 最小树形图

Statistics

Source: Library Checker

Statement

Given a simple weighted directed graph with $N$ vertices and $M$ edges. $i$-th edge is $(a_i, b_i)$ and has a weight of $c_i$.

Find the directed minimum spanning tree whose root is the vertex $S$ (it means that all the vertices have to be reachable from $S$).

$N$ 頂点 $M$ 辺の単純な重み付き有向グラフが与えられる。$i$ 番目の辺は頂点 $a_i$ から $b_i$ に貼られており、重さ $c_i$ である。

頂点 $S$ を根とする(根から全ての頂点に到達できる)有向最小全域木を求めよ。

Constraint

  • $1 \leq N \leq 2 \times 10^5$
  • $N - 1 \leq M \leq 2 \times 10^5$
  • $0 \leq S < N$
  • $0 \leq a_i, b_i < N$
  • $a_i \neq b_i$
  • $(a_i, b_i) \neq (a_j, b_j) (i \neq j)$
  • $0 \leq c_i 10^9$
  • All the vertices are reachable from the vertex $S$ (頂点 $S$ から全ての頂点へ到達可能)

Input

  • $N$ $M$ $S$
  • $a_0$ $b_0$ $c_0$
  • $a_1$ $b_1$ $c_1$
  • :
  • $a_{M - 1}$ $b_{M - 1}$ $c_{M - 1}$

Output

  • $X$
  • $p_0$ $p_1$ $p_2$ ... $p_{N - 1}$

$X$ is the sum of the weights of the edges in the directed MST. $p_i$ is the parent of the vertex $i$ or $p_S = S$.

If there are multiple correct output, print any of them.

ただし、$X$ は木の重みの総和であり、$p_i$ は頂点 $i$ の親である。$p_S = S$ とすること。

解が複数存在する場合、どれを返しても構わない。

Example

Input 1

4 4 0
0 1 10
0 2 10
0 3 3
3 2 4

Output 1

17
0 0 3 0

Input 2

7 8 3
3 1 10
1 2 1
2 0 1
0 1 1
2 6 10
6 4 1
4 5 1
5 6 1

Output 2

24
2 3 1 3 6 4 2