Table of Contents
Standard I/OMethod 1 - <iostream>Method 2 - <cstdio>Example Problem - Weird AlgorithmSolution - Weird AlgorithmHow to Submit Your SolutionFile I/OMethod 1 - freopenMethod 2 - <fstream>Example Solution - Fence PaintingMethod 1 - freopenMethod 2 - <fstream>USACO Note - Extra WhitespaceC++Input & Output
Authors: Darren Yao, Benjamin Qi, Allen Li
How to read input and print output for USACO contests.
Prerequisites
Table of Contents
Standard I/OMethod 1 - <iostream>Method 2 - <cstdio>Example Problem - Weird AlgorithmSolution - Weird AlgorithmHow to Submit Your SolutionFile I/OMethod 1 - freopenMethod 2 - <fstream>Example Solution - Fence PaintingMethod 1 - freopenMethod 2 - <fstream>USACO Note - Extra WhitespaceC++C++
Resources | ||||
---|---|---|---|---|
IUSACO | module is based off this | |||
CPH | cin, getline, files | |||
PAPS | cin, getline |
Java
Resources | ||||
---|---|---|---|---|
IUSACO | module is based off this |
Python
The code snippets below will read in three integers as part of a single line and output their sum. For example, given the input
1 2 3
the output will be as follows:
The sum of these three numbers is 6
Feel free to test them out at ide.usaco.guide.
Out of the methods below, which one should I use?
It doesn't matter. Whichever you're most comfortable with!
Standard I/O
In most websites (such as Codeforces and CSES), and in USACO problems after December 2020, input and output are standard.
C++
<iostream>
Method 1 - More straightforward to use. Calling the extraction operator operator>>
on
cin
reads
whitespace-separated data from standard input. Similarly, calling the insertion
operator operator<<
on
cout
writes to standard
output. The escape sequence
\n
represents a new line.
#include <iostream>using namespace std;int main() {int a;int b;int c;cin >> a >> b >> c;// "\n" can be replaced with endl as wellcout << "The sum of these three numbers is " << a + b + c << "\n";}
<cstdio>
Method 2 - This library includes the
scanf
and
printf
functions, which
are slightly more complicated to use.
#include <cstdio>using namespace std;int main() {int a;int b;int c;/** %d specifies that a value of type int is being input.* To input a 64-bit (long long) number,
Input Speed
The second method is significantly faster (generally only an issue with large input sizes). However, the first method can be sped up so that the difference in speed is not significant; see Fast I/O for details.
Java
Scanner
and System.out.print
Method 1 - In your CS classes, you've probably implemented input and output using standard
input and standard output, or using Scanner
to read input and
System.out.print
to print output.
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int a = sc.nextInt();int b = sc.nextInt();int c = sc.nextInt();System.out.print("The sum of these three numbers is ");System.out.println(a + b + c);}}
This works, but Scanner
and System.out.print
are slow when we have to handle
inputting and outputting tens of thousands of lines.
Input Speed
See the Fast I/O module for a comparison of input speeds as well as faster methods of input than those described in this module.
BufferedReader
and PrintWriter
Method 2 - USACO
This is the recommended I/O method for USACO contests. Feel free to refer to this section in-contest as it provides information about basic Java functionality.
These are faster because they buffer the input and output and handle it all at
once as opposed to parsing each line individually. However, BufferedReader
is
harder to use than Scanner
. It has quite a few more methods and the io
library must be imported for its use as well. A
StringTokenizer
is used to split the input line by whitespace into tokens, which are then
accessed individually by the nextToken()
method.
import java.io.*;import java.util.StringTokenizer;public class Main {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new InputStreamReader(System.in));PrintWriter pw = new PrintWriter(System.out);StringTokenizer st = new StringTokenizer(r.readLine());int a = Integer.parseInt(st.nextToken());
Method 3 - I/O Template
Warning!
Since the code in this section could potentially be considered more than just basic Java functionality, you should not refer to this during a USACO contest.
The following template (a shortened version of Kattis's
Kattio.java
) wraps BufferedReader
and
PrintWriter
and takes care of the string processing for you. You may or may
not find this more convenient than method 2.
import java.io.*;import java.util.*;/*** Simple yet moderately fast I/O routines.* Some notes:** - When done, you should always do io.close() or io.flush() on the* Kattio-instance, otherwise, you may lose output.*
Optional: extends
extends
is used so that Kattio
inherits methods from PrintWriter
(including print()
, println()
and close()
). If you're interested, see
here for more details.
The input methods in our Kattio
class mimic those of Scanner
. Given an
instance io
:
Method | Description |
---|---|
io.next() | Reads the next token (up to a whitespace) and returns a String |
io.nextInt() | Reads the next token (up to a whitespace) and returns as an int |
io.nextLong() | Reads the next token (up to a whitespace) and returns as a long |
io.nextDouble() | Reads the next token (up to a whitespace) and returns as a double |
io.print(arg) | Prints arg to designated output stream |
io.println(arg) | Prints arg to designated output stream and adds a newline |
io.close() | Closes the output stream and flushes the output. Make sure to call this (or io.flush() ) at the end, or you won't see any output! |
PrintWriter Buffering
The original Kattio
code had super(new BufferedOutputStream(o));
on line 23.
But since PrintWriter
will automatically wrap an OutputStream
with a
BufferedWriter
(source),
including BufferedOutputStream
is unnecessary.
Similarly, you may see PrintWriter
s for file output initialized like the
following (ex.
here):
PrintWriter pw =new PrintWriter(new BufferedWriter(new FileWriter("problemname.out")));
This is equivalent to what we use in this module:
PrintWriter pw = new PrintWriter("problemname.out");
Python
input()
and print()
Method 1 - The most intuitive way to do input/output is using the built in input()
and
print()
methods. The input()
method will return the next line, and can be
processed using various Python methods. The print()
method takes in a string
and an optional string end
(defaults to '\n'
). Below is an annotated
demonstration on different input/output scenarios.
# Read in a stringmy_str = input()# Prints the string on its own lineprint(my_str)# Take in an integer n on a single linen = int(input())# Prints n with " test" (no newline) after itprint(n, end=" test")
stdin
and stdout
Method 2 - The first method of reading input can be far slower (sometimes hundreds of times
slower!) than using stdin
. Coupled with Python's relatively slow execution
speed, reading input quickly becomes incredibly important.
# Import the sys module to use stdin/stdoutimport sys# sys.stdin/stdout is similar to a file in that we read lines for input/outputmy_str = sys.stdin.readline()sys.stdout.write(str(myStr) + "\n")# Renaming the read/write methods for convenienceinput = sys.stdin.readlineprint = sys.stdout.write
We can also use
split
,
map
or a
list comprehension
to read in multiple whitespace-separated integers on the same line.
import sys# Read in a series of numbers on one line into a listnums = [int(x) for x in input().split()]# This does the same thingnums = list(map(int, input().split()))# stdin/stdout, just replace input() with sys.stdin.readline()nums = list(map(int, sys.stdin.readline().split()))
We can use something similar to the above if we are unpacking a fixed number of integers.
import sys# Read in integers n and m on the same line with a list comprehensionn, m = [int(x) for x in input().split()]# Do the same thing but with map insteadn, m = map(int, input().split())# stdin and stdoutn, m = map(int, sys.stdin.readline().split())
So taking three integers as input and printing their sum is quite simple. On a larger scale (thousands of integers), using stdin and stdout becomes far more important for speed:
import sysa, b, c = map(int, input().split())print("The sum of these three numbers is", a + b + c)# stdin and stdouta, b, c = map(int, sys.stdin.readline().split())print("The sum of these three numbers is", a + b + c)
Example Problem - Weird Algorithm
Focus Problem – try your best to solve this problem before continuing!
Try to implement this yourself!
Resources | ||||
---|---|---|---|---|
GCP | example C++ solution for this problem |
Solution - Weird Algorithm
C++
#include <iostream>using namespace std;int main() {long long x;cin >> x;while (x != 1) {cout << x << " ";if (x % 2 == 0) {x /= 2;
Java
Scanner
and System.out.print
Method 1 - import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner r = new Scanner(System.in);long x = r.nextLong();while (x != 1) {System.out.print(x + " ");if (x % 2 == 0) {x /= 2;
BufferedReader
and PrintWriter
Method 2 - import java.io.*;public class Main {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new InputStreamReader(System.in));PrintWriter pw = new PrintWriter(System.out);long x = Long.parseLong(r.readLine());while (x != 1) {pw.print(x + " ");if (x % 2 == 0) {
Kattio
With import java.io.*;import java.util.*;public class Main {public static void main(String[] args) {Kattio io = new Kattio();long x = io.nextLong();while (x != 1) {io.print(x + " ");if (x % 2 == 0) {
Python
x = int(input())while x != 1:print(x, end=" ")if x % 2 == 0:x //= 2else:x = 3 * x + 1print(x)
C++
Warning!
As noted in the resource above, this problem requires 64-bit integers.
The following solution, which uses int
instead of long long
, does
not pass all of the test cases.
#include <iostream>using namespace std;int main() {int x;cin >> x;while (x != 1) {cout << x << " ";if (x % 2 == 0) {x /= 2;
This happens because numbers in the sequence may exceed the maximum possible
value for the int
data type (, as mentioned in the
prerequisite module).
Java
Python
C++
Java
As noted in the resource above, this problem requires 64-bit integers.
The following solution, which uses int
instead of long
, does
not pass all of the test cases.
import java.util.Scanner;public class Main {public static void main(String[] args) {Scanner r = new Scanner(System.in);int x = r.nextInt();while (x != 1) {System.out.print(x + " ");if (x % 2 == 0) {x /= 2;
This happens because some numbers in the sequence can exceed the maximum possible
value for the int
data type (, as mentioned in the
prerequisite module).
Python
How to Submit Your Solution
Choice of IDE
We assume in this section that you are using an online IDE, such as the USACO Guide IDE. The instructions for using a local IDE are similar, except you skip the download step.
Do the following to submit on CSES. Submitting on other platforms (such as USACO) is similar.
- Run your solution code with the sample input, and make sure that it produces the sample output.
- Download your solution code into a file. The file extension should be one of
.cpp
,.java
,.py
or their equivalents, depending on your programming language. - Open the problem statement. Log in if you aren't already logged in.
- Press the submit tab (for USACO, scroll to the bottom of the page).
- Upload your solution file. For CSES, assuming the file had the proper extension, the language should be automatically detected (for USACO, select the language yourself). Some platforms (such as Codeforces) allow you to paste your code into a text box instead of uploading a file.
- Submit your solution. For CSES, you will be redirected to the results page (for USACO, results will appear at the top of the page). If your solution is correct on all the test cases, you're done! Otherwise, fix your code and start again from step 1.
C++
Java
Warning: File Naming for Java Users
The name of the file you submit must match the name of your public class.
For example, if your public class is named PublicClassName
, then the name of the
file you submit must be PublicClassName.java
.
Python
Submitting to Past USACO Problems
If you are using the USACO Guide IDE, you can submit to some past USACO problems through that (Settings -> Judge). You cannot use this to submit during a live contest.
File I/O
USACO File I/O
USACO problems from December 2020 onwards use standard I/O rather than file I/O. You'll still need to use file I/O to submit to earlier problems.
In older USACO problems, the input and output file names are given and follow
the convention problemname.in
. After the program is run, output must be
printed to a file called problemname.out
.
Focus Problem – try your best to solve this problem before continuing!
You must use the correct file names when opening the .in
and .out
files,
depending on the problem. The file names are given on USACO problems which
require file opening. For example, you would open paint.in
and paint.out
in
the above problem.
C++
freopen
Method 1 - You will need the <cstdio>
library. The freopen
statements reuse standard
I/O for file I/O. Afterwards, you can simply use cin
and cout
(or scanf
and printf
) to read and write data.
#include <cstdio>#include <iostream>using namespace std;int main() {freopen("problemname.in", "r", stdin);// the following line creates/overwrites the output filefreopen("problemname.out", "w", stdout);// cin now reads from the input file instead of standard input
To test your solution locally without file I/O, just comment out the lines with
freopen
.
For convenience, we can define a function that will redirect stdin
and
stdout
based on the problem name:
#include <cstdio>#include <iostream>using namespace std;// the argument is the input filename without the extensionvoid setIO(string s) {freopen((s + ".in").c_str(), "r", stdin);freopen((s + ".out").c_str(), "w", stdout);}
<fstream>
Method 2 - You cannot use C-style I/O (scanf
, printf
) with this method.
#include <fstream>using namespace std;int main() {ifstream fin("problemname.in");ofstream fout("problemname.out");int a;int b;int c;fin >> a >> b >> c;fout << "The sum of these three numbers is " << a + b + c << "\n";}
Java
Java
Again, BufferedReader
and PrintWriter
should be used. Note how static
initialization of r
and pw
is slightly different.
import java.io.*;import java.util.StringTokenizer;public class Main {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new FileReader("problemname.in"));PrintWriter pw = new PrintWriter("problemname.out");StringTokenizer st = new StringTokenizer(r.readLine());int a = Integer.parseInt(st.nextToken());
Kattio
With import java.io.*;import java.util.*;public class Main {public static void main(String[] args) throws IOException {Kattio io = new Kattio("problemname");int a = io.nextInt();int b = io.nextInt();int c = io.nextInt();io.print("The sum of these three numbers is ");
Python
Python
See here for documentation about file I/O.
The most intuitive way to do file I/O in Python is by redirecting the system
input and output to files. After doing this, you can then use the above
input()
and print()
methods as usual.
import syssys.stdin = open("problemname.in", "r")sys.stdout = open("problemname.out", "w")
A different approach to file I/O in Python is to still use the open()
method,
but use the built-in functions .readline()
or .readlines()
:
"""Note: The second argument can be omitted in the open()command for read-only files"""fin = open("problemname.in", "r")fout = open("problemname.out", "w")# One way to read the file using .readline()line1 = fin.readline()# readline() will pick up where you left off
fin.readline()
will return the next line as a string. This method is useful for problems where you only have to read a short amount of lines but you still need to map each value to a variable.fin.readlines()
returns all of the file's content as a list, separated by newlines ("\n"
). Combined with a for loop, this method provides a concise way to separate variables in the same line in a problem. Keep in mind that each line entry in the list will still have a"\n"
at the end.fout.write(data)
will write the variabledata
to the file.data
must be a string, and you can convert non-string variables withstr(my_var)
. Thewrite()
method will NOT write a new line at the end. You must also runfout.write("\n")
if you wish to write a new line.f-strings were added in Python 3.6, and generally look nicer than concatenating (adding) strings. To define an f-string, simply add the letter
f
right before the start of the string, and any variables or expressions enclosed in curly braces ({}
) will be put into the string. As an example,fout.write(f"{var1} {var2} {var3+var4}")
looks much cleaner thanfout.write(str(var1)+" "+str(var2)+" "+str(var3+var4))
After you read a line, you may wish to process it further. Python has many built-in string methods and functions:
str.strip()
removes any trailing or leading whitespace. You should always run this method after reading a line, to ensure that there is no extra whitespace:line = fin.readline().strip()
map(func, iterable)
will run a function (thefunc
argument) against each element of an iterable (list) you pass it. This is useful for changing a list of strings into a list of ints:nums = list(map(int, ["1", "2", "3"]))
. Please note thatmap()
returns a Map object, and you need to convert it into a list withlist()
.str.split(delim)
will split the string. If no argument is passed, it will split by space. This is useful if you want to separate a string of space-separated integers into ints:nums = list(map(int, line.split()))
Example Solution - Fence Painting
Resources | ||||
---|---|---|---|---|
USACO | Make sure to read this. |
For an explanation of the solutions below, check the Rectangle Geometry module.
C++
freopen
Method 1 - #include <iostream>#include <vector>using namespace std;int main() {// Use standard input to read from "paint.in"freopen("paint.in", "r", stdin);// Use standard output to write to "paint.out"freopen("paint.out", "w", stdout);
<fstream>
Method 2 - #include <fstream>#include <vector>using namespace std;int main() {ifstream fin("paint.in");ofstream fout("paint.out");vector<bool> cover(100);int a, b, c, d;
Java
Scanner
and PrintWriter
Method 1 - import java.io.*;import java.util.Scanner;public class Main {public static void main(String[] args) throws IOException {Scanner r = new Scanner(new File("paint.in"));PrintWriter pw = new PrintWriter("paint.out");int a = r.nextInt();int b = r.nextInt();
BufferedReader
and PrintWriter
Method 2 - import java.io.*;import java.util.StringTokenizer;public class Main {public static void main(String[] args) throws IOException {BufferedReader r = new BufferedReader(new FileReader("paint.in"));PrintWriter pw = new PrintWriter("paint.out");StringTokenizer st = new StringTokenizer(r.readLine());int a = Integer.parseInt(st.nextToken());
Kattio
With import java.io.*;import java.util.*;public class Main {public static void main(String[] args) throws IOException {Kattio io = new Kattio("paint");int a = io.nextInt();int b = io.nextInt();int c = io.nextInt();int d = io.nextInt();
Python
Method 1
with open("paint.in", "r") as inp:lines = [line for line in inp]a, b = map(int, lines[0].split())c, d = map(int, lines[1].split())cover = [0] * 100for i in range(a, b):cover[i] = 1for i in range(c, d):cover[i] = 1
Method 2
Redirecting file input using sys
, as mentioned above.
import syssys.stdin = open("paint.in", "r")sys.stdout = open("paint.out", "w")a, b = map(int, input().split())c, d = map(int, input().split())cover = [0] * 100for i in range(a, b):
USACO Note - Extra Whitespace
Importantly, USACO will automatically add a newline to the end of your file if it does not end with one.
Warning!
Occasionally, there is a period of time near the beginning of the contest window where the model outputs do not end in newlines. This renders the problem unsolvable.
Make sure not to output trailing spaces, or you will get an error such as the following:
Here are some examples of what is allowed and what isn't when the intended
output consists of a single integer ans
:
C++
C++
cout << ans; // OK, no newlinecout << ans << endl; // OK, newlinecout << ans << "\n"; // OK, newlinecout << ans << " "; // NOT OK, extra spacecout << ans << "\n\n"; // NOT OK, extra newline
Java
Java
pw.print(ans); // OK, no newlinepw.println(ans); // OK, newlinepw.print(ans + "\n"); // OK, newlinepw.print(ans + " "); // NOT OK, extra spacepw.print(ans + "\n\n"); // NOT OK, extra newline
Python
Python
print(ans, end="") # OK, no newlineprint(ans) # OK, newlineprint(str(ans) + "\n", end="") # OK, newlineprint(str(ans) + " ", end="") # NOT OK, extra spaceprint(str(ans) + "\n") # NOT OK, extra newline
Module Progress:
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!