Problem:
Minimum-Cost Arborescence

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

|V| |E| r
s0 t0 w0
s1 t1 w1
:
s|E|-1 t|E|-1 w|E|-1

, 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.

Constraints

1 ≤ |V| ≤ 100

0 ≤ |E| ≤ 1,000

0 ≤ wi ≤ 10,000

G has arborescence(s) with the root r

Sample Input 1

4 6 0
0 1 3
0 2 2
2 0 1
2 3 1
3 0 1
3 1 5

Sample Output 1

6

Sample Input 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

Sample Output 2

11

Solution in JAVA (judge verdict: Wrong Answer)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;

public class Main {

	static List<edge>[] graph;
	static int V;
	static int R;

	static int total;

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String[] V_E_R = br.readLine().split(" ");

		V = Integer.parseInt(V_E_R[0]);

		int E = Integer.parseInt(V_E_R[1]);

		R = Integer.parseInt(V_E_R[2]);

		graph = new List[V];

		for (int i = 0; i < V; i++) {
			graph[i] = new ArrayList<>();
		}

		for (int i = 0; i < E; i++) {
			String[] edge = br.readLine().split(" ");

			int from = Integer.parseInt(edge[0]);

			int to = Integer.parseInt(edge[1]);

			int cost = Integer.parseInt(edge[2]);

			graph[from].add(new edge(from, to, cost));

		}

		prim();
		System.out.println(total);

	}

	static void prim() {

		boolean[] visited = new boolean[V];

		Queue<edge> edges = new PriorityQueue<>();
		edges.offer(new edge(0, R, 0));

		while (!(edges.isEmpty())) {
			edge e = edges.poll();

			if (visited[e.to]) {
				continue;
			}
			visited[e.to] = true;

			total += e.cost;

			for (edge ed : graph[e.to]) {
				edges.offer(ed);
			}

		}

	}

	static class edge implements Comparable<edge> {
		int from;
		int to;
		int cost;

		edge(int a, int b, int c) {
			this.from = a;
			this.to = b;
			this.cost = c;

		}

		@Override
		public int compareTo(edge o) {
			// TODO ?????????????????????????????????????????????
			return this.cost - o.cost;
		}
	}

}