Skip to content

Reading input, writing output

This guide covers the part of algo you will touch in almost every solution: reading the input shape from the statement and writing the answer back out.

Use input: when the statement gives you a fixed shape

Section titled “Use input: when the statement gives you a fixed shape”
input:
n, m: int
a: [int][n]
edges: [(int, int, int)][m]

This reads values in declaration order. It is the default choice when the input format is known up front.

Common forms:

input:
n: int
s: str
a: [int][n]
mat: matrix[int][n][m]
edges: [(int, int)][m]
input q: int
input l, r: int

This is useful inside loops or after you already declared the surrounding state.

input T: int
each T:
input:
n: int
a: [int][n]
println solve(a)

Use each when the first value in the file is a test count and each iteration reads one self-contained case.

Use repeat n: for counted loops without an index

Section titled “Use repeat n: for counted loops without an index”
input:
n, m: int
g = graph(n, undirected = true)
repeat m:
input:
u, v: int
g.add(u, v)

Use repeat when you want “do this n times” and do not need the loop variable.

println x
print a, b, c
println arr
output arr
output arr, sep=" "
newline

What they are for:

  • println x: one value and a trailing newline
  • print a, b, c: multiple values separated by spaces
  • println arr: all array elements on one line
  • output arr: one element per line
  • output arr, sep=" ": custom separator
  • newline: emit a blank line

Interpolated strings are useful for debugging and for problems that require formatted text output.

println "dist[{i}] = {dist[i]}"
println "edge {u} -> {v} (weight {w})"
input:
n, m: int
g = wgraph(n, undirected = true)
repeat m:
input:
u, v, w: int
g.add(u, v, w)
input q: int
repeat q:
input:
l, r: int
println st.query(l, r)
input:
R, C: int
grid: matrix[char][R][C]
  • Use input: for declared shapes
  • Use inline input for local reads
  • Use each for test cases
  • Use repeat for counted loops
  • Use println unless the problem format forces something else