Sign in

Count In-Degree and Out-Degree

intro

Compute in-degree and out-degree for a directed graph on nodes 0 through n-1 given as a list of directed edges (u, v) meaning u -> v. Implement degrees(n, edges) returning the pair {indeg, outdeg}, where indeg[i] counts edges arriving at i and outdeg[i] counts edges leaving i. A self-loop (u, u) increments both indeg[u] and outdeg[u] by 1 each: it counts toward both, never adding 2 to a single counter. Parallel edges each count separately.

Example: degrees(3, {(0,1), (1,2), (0,0)}) returns indeg = {1, 1, 1}, outdeg = {2, 1, 0}. Node 0 has out-degree 2 (the edge to 1, plus its self-loop) and in-degree 1 (just the self-loop); node 2 receives one edge and sends none.

Input format: each test in tests/*.in is laid out as:

  • Line 1: n e, the node count and the number of directed edges; nodes are numbered 0 to n - 1.
  • Next e lines: u v, one directed edge from u to v. When e is 0 the file is just the header line.

Test 02.in reads:

1 1
0 0

This is one node with one edge, the self-loop 0 -> 0, which counts toward both its in-degree and its out-degree.

Where you'll use it:

✦ Solution & editorial unlock with the pass.

Loading...