public class PowerOutage {
public static void main(String args[]) {
new PowerOutage();
}
public int Count = 0;
public int TotalCount = 0;
boolean[] walked = new boolean[50];
public PowerOutage() {
int[] from = { 0, 1, 0 };
int[] to = { 1, 2, 3 };
int[] length = { 10, 10, 10 };
System.out.println(estimateTimeOut(from, to, length));
}
public int estimateTimeOut(int[] fromJunction, int[] toJunction,
int[] ductLength) {
Node[] roots = new Node[50];
for (int i = 0; i < fromJunction.length; i++) {
walked[i] = false;
if (TotalCount < toJunction[i])
TotalCount = toJunction[i];
if (roots[fromJunction[i]] == null) {
// link head
roots[fromJunction[i]] = new Node();
roots[fromJunction[i]].number = toJunction[i];
roots[fromJunction[i]].length = ductLength[i];
roots[fromJunction[i]].next = null;
} else {
// add node
Node toAdd = new Node();
toAdd.number = toJunction[i];
toAdd.length = ductLength[i];
toAdd.next = roots[fromJunction[i]];
roots[fromJunction[i]] = toAdd;
}
}
TotalCount++;
Count++;
walked[0] = true;
int result = traverse(0, roots);
return result;
}
private int traverse(int start, Node[] roots) {
// TODO Auto-generated method stub
Node root = roots[start];
if (root == null)
return 0;
int min = -1;
boolean firstChild = true;
while (root != null) {
if (firstChild) {
firstChild = false;
if (!walked[root.number])
Count++;
if (Count < TotalCount)
min = 2 * (traverse(root.number, roots) + root.length);
else
min = traverse(root.number, roots) + root.length;
} else {
if (!walked[root.number])
Count++;
int temp = traverse(root.number, roots) + root.length;
if (Count < TotalCount) {
if (min > 2 * temp) {
min = 2 * temp;
}
} else {
if (min > temp) {
min = temp;
}
}
}
root = root.next;
}
return min;
}
class Node {
public int number;
public int length;
public Node next;
public Node() {
number = -1;
length = -1;
next = null;
}
}
}