PrevNext

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.

Method 1 - input() and print()

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 string
my_str = input()
# Prints the string on its own line
print(my_str)
# Take in an integer n on a single line
n = int(input())
# Prints n with " test" (no newline) after it
print(n, end=" test")

Method 2 - stdin and stdout

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/stdout
import sys
# sys.stdin/stdout is similar to a file in that we read lines for input/output
my_str = sys.stdin.readline()
sys.stdout.write(str(myStr) + "\n")
# Renaming the read/write methods for convenience
input = sys.stdin.readline
print = 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 list
nums = [int(x) for x in input().split()]
# This does the same thing
nums = 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 comprehension
n, m = [int(x) for x in input().split()]
# Do the same thing but with map instead
n, m = map(int, input().split())
# stdin and stdout
n, 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 sys
a, b, c = map(int, input().split())
print("The sum of these three numbers is", a + b + c)
# stdin and stdout
a, 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

x = int(input())
while x != 1:
print(x, end=" ")
if x % 2 == 0:
x //= 2
else:
x = 3 * x + 1
print(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 (231โˆ’12^{31}-1, 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 (231โˆ’12^{31}-1, 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.

  1. Run your solution code with the sample input, and make sure that it produces the sample output.
  2. 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.
  3. Open the problem statement. Log in if you aren't already logged in.
  4. Press the submit tab (for USACO, scroll to the bottom of the page).
  5. 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.
  6. 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!

View Internal Solution

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.

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 sys
sys.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 variable data to the file. data must be a string, and you can convert non-string variables with str(my_var). The write() method will NOT write a new line at the end. You must also run fout.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 than fout.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 (the func 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 that map() returns a Map object, and you need to convert it into a list with list().

  • 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.

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] * 100
for i in range(a, b):
cover[i] = 1
for i in range(c, d):
cover[i] = 1

Method 2

Redirecting file input using sys, as mentioned above.

import sys
sys.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] * 100
for 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:

bad

Here are some examples of what is allowed and what isn't when the intended output consists of a single integer ans:

Python

print(ans, end="") # OK, no newline
print(ans) # OK, newline
print(str(ans) + "\n", end="") # OK, newline
print(str(ans) + " ", end="") # NOT OK, extra space
print(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!

PrevNext