Skip to content

Instantly share code, notes, and snippets.

@volyx
Created March 5, 2017 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volyx/dc2afb6defb1f89ae6db7a3700822aae to your computer and use it in GitHub Desktop.
Save volyx/dc2afb6defb1f89ae6db7a3700822aae to your computer and use it in GitHub Desktop.
Vk Cup 2017 B
import javafx.util.Pair;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.function.ToIntFunction;
public class Main2 {
public static void main(String[] args) throws FileNotFoundException {
// try (Scanner scanner = new Scanner(new FileInputStream("3"))) {
try (Scanner scanner = new Scanner(System.in)) {
PriorityQueue<Node> nodes = new PriorityQueue<>((o1, o2) -> {
int compare = Integer.compare(o1.weight, o2.weight);
if (compare != 0) {
return compare;
}
return - Integer.compare(o1.index, o2.index);
});
int n = scanner.nextInt();
Node p = null;
for (int i = 0; i < n; i++) {
int weight = scanner.nextInt();
if (i == 0 && weight == 0) {
System.out.println(-1);
return;
}
if (i == 0) {
p = new Node(i + 1, weight);
} else {
nodes.add(new Node(i + 1, weight));
}
}
// System.out.println("n=" + n);
List<Pair<Integer, Integer>> order = new ArrayList<>();
while (!nodes.isEmpty()) {
Node node = nodes.remove();
Node parent = findNodeMinWeight(nodes, p);
if (parent == null) {
System.out.println(-1);
return;
}
// System.out.println(parent.index + " send " + node.index);
parent.weight--;
order.add(new Pair<>(parent.index, node.index));
if (parent.index == 1 && nodes.size() == 0) {
break;
}
}
System.out.println(order.size());
for (int i = order.size() - 1; i >= 0; i--) {
Pair<Integer, Integer> pair = order.get(i);
System.out.println(pair.getKey() + " " + pair.getValue());
}
}
}
public static Node findNodeMinWeight(PriorityQueue<Node> nodes, Node p) {
if (nodes.size() == 0) {
return p;
}
Iterator<Node> it = nodes.iterator();
while (it.hasNext()) {
Node node = it.next();
if (node.weight > 0 ) {
return node;
}
}
if (p.weight > 1) {
return p;
}
return null;
}
public static class Node {
int index;
int weight;
public Node(int index, int weight) {
this.index = index;
this.weight = weight;
}
@Override
public String toString() {
return "{" + index +
", " + weight +
'}';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment