package javafr;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
try {
while (true) {
int vertices
= Integer.
parseInt(nextToken
()); int root
= Integer.
parseInt(nextToken
());
int u, v, cost;
List<List<Integer>> neigh = new ArrayList<List<Integer>>(vertices + 1);
List<Node> nodes = new ArrayList<Node>();
for (int i = 0; i <= vertices; i++) {
nodes.add(new Node());
}
for (int i = 0; i < vertices - 1; i++) {
cost
= Integer.
parseInt(nextToken
()); nodes.get(u).children.add(nodes.get(v));
nodes.get(v).children.add(nodes.get(u));
nodes.get(u).edges.add(cost);
nodes.get(v).edges.add(cost);
}
for (Node n : nodes)
n.ctr = n.children.size() - 1;
nodes.get(root).ctr = nodes.get(root).children.size();
Deque<Node> queue = new ArrayDeque<Node>();
queue.push(nodes.get(root));
while (!queue.isEmpty()) {
Node node = queue.pop();
for (int i = 0; i < node.children.size(); i++) {
Node child = node.children.get(i);
child.parent = node;
child.cost = node.edges.get(i);
child.childrenCost = 0;
int index = child.children.indexOf(node);
child.children.remove(index);
child.edges.remove(index);
queue.push(child);
}
}
PriorityQueue<Node> pq = new PriorityQueue<Main.Node>();
for (int i = 1; i < nodes.size(); i++) {
if (nodes.get(i).children.size() == 0)
nodes.get(i).childrenCost = nodes.get(i).cost;
pq.add(nodes.get(i));
}
while (!pq.isEmpty()) {
Node n = pq.poll();
if (n.childrenCost < n.cost)
n.cost = n.childrenCost;
if (n.parent != null) {
n.parent.childrenCost += n.cost;
n.parent.ctr--;
pq.remove(n.parent);
pq.add(n.parent);
}
}
System.
out.
println(nodes.
get(root
).
childrenCost);
}
// lol
}
}
while (!st.hasMoreTokens()) {
}
return st.nextToken();
}
private static final class Node implements Comparable<Node> {
Node parent;
List<Node> children = new ArrayList<Node>();
List<Integer> edges = new ArrayList<Integer>();
int cost, childrenCost;
int ctr;
public int compareTo(Node arg0) {
return ctr - arg0.ctr;
}
}
}