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 Ruby (judge verdict: Wrong Answer)

def f(v, edges, r)
  mins = []
  edges.each{|s, t, w|
    mins[t] = [w, s] if mins[t] == nil || mins[t][0] > w
  }
  mins[r] = [-1, -1]

  group = Array.new(v){0}
  comp = Array.new(v){0}
  cnt = 0

  used = {}

  v.times{|i|
    unless used[i] then
      chain = []
      cur = i
      while used[i] == nil && cur != -1
        chain << cur
        used[cur] = 1
        cur = mins[cur][1]
      end
      if cur != -1
        cycle = false
        chain.each{|e|
          group[e] = cnt
          if e == cur
            cycle = true
            comp[cnt] = 1
          end
          cnt += 1 unless cycle
        }
      else
        chain.each{|e|
          group[e] = cnt
          cnt += 1
        }
      end
    end
  }
  if cnt == v then
    return mins.map {|w, s| w}.inject(:+) + 1
  end

  res = 0
  v.times{|i|
    next if i == r
    if comp[group[i]] == 1
      res += mins[i][0]
    end
  }

  n_es = []
  ii = 0
  edges.each{|s, t, w|
    gs = group[s]
    gt = group[t]
    next if gs == gt
    if comp[gt]
      n_es[ii] = [gs, gt, w - mins[t][0]]
    else
      n_es[ii] = [gs, gt, w]
    end
    ii += 1
  }
  return res + f(cnt, n_es, group[r])
end

v, e, r = gets.split.map(&:to_i)
edges = []
e.times{|i|
  s, t, w = gets.split.map(&:to_i)
  edges[i] = [s, t, w]
}
puts f(v, edges, r)