Explanation
It's a bit hard to know where to start with this problem, so let's try a way simpler case: what if all s are either or ?
In this case, means that is the chosen node (which we can only have one of), and means that it's a direct neighbor (which we can have at most of).
Now we can extend this to include possibilities where . These nodes have to be neighbors of the nodes where , so we try to link them up with the direct neighbors of the chosen node.
The only way Valera could've made a mistake is if the number of nodes that are away is greater than times the number of nodes that are away, since that would force us to allocate more edges than the constraints would allow.
If you know what BFS Trees are, we're basically constructing one of these.
Implementation
Time Complexity:
Python
import sysnode_num, max_adj = [int(i) for i in input().split()]dists = [[] for _ in range(node_num)]for n, d in enumerate(input().split()):dists[int(d)].append(n)if len(dists[0]) != 1:print(-1) # only one node can have distance 0
Java
import java.io.*;import java.util.*;public class RestoreGraph {public static void main(String[] args) throws IOException {BufferedReader read = new BufferedReader(new InputStreamReader(System.in));StringTokenizer initial = new StringTokenizer(read.readLine());int nodeNum = Integer.parseInt(initial.nextToken());int maxAdj = Integer.parseInt(initial.nextToken());
C++
#include <algorithm>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;int main() {int node_num;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!