Published: 21.04.2014 - 17.35, Author: Christian "flyrev" Neverdal Jonassen
Here are some useful code snippets for programming contests like IDI Open. Feel free to use these during the contest. Remember that copy/paste from electronic sources is not allowed, so we recommend you print these out and bring to the contest for re-typing.
One way of dealing with input in a contest, is through the example code below. The methods readInt() and readString() returns the next int/String. If there are no more tokens on the line, it tokenizes the next line and returns the first int/String. The StringTokenizer (Java) is a class that takes one String as input to the constructor, and splits it into tokens/substrings (whitespace marks the place to split). You can call nextToken() on the StringTokenizer to get the next token. In C++ we simply use cin for input.
When dealing with floating-point numbers, you're often asked to print the result using a given precision, for example 3 digits.
One way of doing this in Java is using a class called DecimalFormat, which takes as an argument a string defining the format.
To print in another format, just change the string argument of the DecimalFormat constructor.
When we then want to print out the number, we call format() on the DecimalFormat. This method returns a string we print out using System.out.println().
In C++, one way to achieve this is using the setiosflags and setprecision functions from the header iomanip before printing. Here's an example:
To change the number of decimals again, simply call setprecision again the same way as above, with the desired number of decimals.