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]Use inline input for one-off reads
Section titled “Use inline input for one-off reads”input q: intinput l, r: intThis is useful inside loops or after you already declared the surrounding state.
Use each T: for test cases
Section titled “Use each T: for test cases”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.
Output forms
Section titled “Output forms”println xprint a, b, cprintln arroutput arroutput arr, sep=" "newlineWhat they are for:
println x: one value and a trailing newlineprint a, b, c: multiple values separated by spacesprintln arr: all array elements on one lineoutput arr: one element per lineoutput arr, sep=" ": custom separatornewline: emit a blank line
String interpolation
Section titled “String interpolation”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})"Common patterns
Section titled “Common patterns”Read graph edges
Section titled “Read graph edges”input: n, m: int
g = wgraph(n, undirected = true)repeat m: input: u, v, w: int g.add(u, v, w)Read queries
Section titled “Read queries”input q: intrepeat q: input: l, r: int println st.query(l, r)Read a grid
Section titled “Read a grid”input: R, C: int grid: matrix[char][R][C]Rule of thumb
Section titled “Rule of thumb”- Use
input:for declared shapes - Use inline
inputfor local reads - Use
eachfor test cases - Use
repeatfor counted loops - Use
printlnunless the problem format forces something else