Code Conventions
Authors: Nathan Wang, Benjamin Qi, Michael Cao, Nathan Chen, Allen Li
Prerequisites
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.
Resources | |||
---|---|---|---|
CF |
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 | |||
---|---|---|---|
Aryansh | |||
Benq | what 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.
#include <bits/stdc++.h> // see C++ Tips & Tricksusing namespace std;using ll = long long;using vi = vector<int>;#define pb push_back#define rsz resize#define all(x) begin(x), end(x)#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)
import java.io.*; // Imports necessary classes to read and write filesimport java.util.*; // Imports many useful data structures and algorithms librariespublic class Main { // Name your program whatever you like.// Note the class name must match the file name// (e.g. this file would be "Main.java")public static void main(String[] args) throws Exception {// The code below reads from stdin and also uses a slow input method.// Read "General - Fast I/O" for other Java I/O techniques.Scanner sc = new Scanner(System.in);
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 IO support.
import sys # Necessary for sys.stdin and sys.stdoutdef main(file):sys.stdin = open(file + ".in", "r") # redirects standard input to filesys.stdout = open(file + ".out", "w") # redirects standard output to file# your code hereif __name__ == "__main__":main("") # calls main method