PrevNext

Code Conventions

Authors: Nathan Wang, Benjamin Qi, Michael Cao, Nathan Chen, Allen Li

Tips on code style and what you may see in our code samples.

Following the code conventions mentioned in the following link might make your code more readable.

However, since code for the USACO Guide is contributed from several authors, code style will not be uniform. We still strive for code that is readable and understandable! If any code does not compile or is hard to read, please contact us!

Templates

A template consists of code that is assumed to be in every file. Don't be afraid to write your own template or don't use one at all! Below, we'll give an example of what a template might look like.

Warning!

USACO rules prohibit the use of pre-written code, including templates. Therefore, make sure you are able to re-type your template in contest (or just don't use one)!

C++

C++

Resources
AryanshS
Benqwhat it sounds like!!

Templates in C++ can take advantange of more powerful features than the other contest languages, and they can be more customized to each competitor. For example, C++ macros can substitute short code with longer code. Some authors choose to use them or not to use them, and the choice to use them is yours as well.

If you're not familiar with any of the features used in the code below, check Writing Generic Code for more information.

1#include <bits/stdc++.h>
2using namespace std;
3
4using ll = long long;
5
6using vi = vector<int>;
7#define pb push_back
8#define rsz resize
9#define all(x) begin(x), end(x)
10#define sz(x) (int)(x).size()

Java

Java

A normal Java template will contain a main method, helpful imports, and some form of I/O (for USACO, this would probably be File I/O). See Kattio from the I/O module for an example.

Python

Python

A python template is not really necessary; however, it is a good idea to have a main method to keep the structuring of your code clean, and it may be useful to add in easy file I/O support.

1import sys # Necessary for sys.stdin and sys.stdout
2
3def main(file):
4 sys.stdin = open(file + ".in", "r") # redirects standard input to file
5 sys.stdout = open(file + ".out", "w") # redirects standard output to file
6 # your code here
7
8if __name__ == "__main__":
9 main("") # calls main method

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!

Give Us Feedback on Code Conventions!

PrevNext