contest algorithms january 2016 dr. andrew davison dept. of computer engineering prince of songkla...
TRANSCRIPT
Contest Algorithms 1
Contest AlgorithmsJanuary 2016
Dr. Andrew DavisonDept. of Computer Engineering
Prince of Songkla [email protected]
1. Introduction
http://fivedots.coe.psu.ac.th/Software.coe/ContestAlgs/
Contest Algorithms 2
Knowledge of Java e.g. 241-211. Object Oriented Programming
Intro to big-Oh and algorithms e.g. 241-303 / 242-313 Discrete Mathematics 242-310 Intro to Algorithms and Complexity
Prerequisites
Contest Algorithms 3
Makes you a better programmer and thinker in many situations
Develop skills that will set you apart in the workforce
It's fun
Why Compete?
ACM-ICPC
ICPC is a tiered competition among teams of students representing institutions of higher education.
Teams compete in local contests, then Regional Contests, from which top scoring teams advance to the ACM-ICPC World Finals
4
Contest Algorithms 5
Contest Algorithms 6
Format: 3 people 1 computer 5 hours 10 problems 25 page team reference document
Rules: http://www.acmicpc-thailand.org/asia/2015/contest https://icpc.baylor.edu/
What is ACM?
ACM: Association for Computing Machinery http://www.acm.org/ the world’s largest educational and scientific computing
society
ACM ICPC ACM International Collegiate Programming Contest http://en.wikipedia.org/wiki/ACM_International_Collegiate_Prog
ramming_Contest
7
Contest Algorithms 8
Know your teammates Delegating problems to each other
Share the computer time effectively Create test cases for each other Communicate well Pair programming
Teamwork
Producing Winning Solution
Write a team programming plan Read through all the problems first Order the problems: shortest first, in terms of your effort Outline the algorithms,data structures, tricky details Do the math! (space & time complexity) Write the code to be fast and correct Try to break the algorithm - use tricky test cases
9
Contest Algorithms 10
Problem description/statement can be unnecessarily long or misleading
Input and output description usually very precise assume that all input will be formatted like this
Sample input and output one or more inputs and expected outputs
Problem Statement/Recipe
Contest Algorithms 11
Searching / Sorting Dynamic programming Greedy Maths
number theory, big integer, etc
String processing Computational geometry
Complete search also known as brute force backtracking
Divide and conquer Graph
traversal minimal spanning tree
(MST) shortest paths maxflow
Quickly identify problem types
Coding a Problem
Brute force algorithm tends to be the easiest to implement.
KISS: Keep It Short & Simple Use more memory space if it makes the code faster Don't delete your debugging output, comment it out Optimize step-by-step, and only as much as needed Keep all working versions
12
Only start coding after you decide on the algorithm Code the input routine and test it
write extra output routines to show data
Code the output routine and test it Write comments outlining the program logic Code and debug one section at a time
13
Coding style: white space is good use meaningful variable names develop code in small steps add useful comments
Try not to use floating point, or be aware of inaccuracy e.g. instead of $12.34, use 1234 cents double x = ...;if (x == 4) // badif (Math.abs(x-4) < 1e-9) // good
14
Contest Algorithms 15
Read the problem Decide whether or not you know how to solve it
If you think you can solve it: Parse the input Write the code Check that the program works on the sample input/output Submit!
If you're not sure, move onto the next problem
Steps to solving a problem
Contest Algorithms 16
import java.io.*;
public class Main { public static void main(String[] args) // throws Exception { BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); int nCases = Integer.parseInt(in.readLine()); for (int caseNum = 0; caseNum < nCases; caseNum++) { // Parse the input number int n = Integer.parseInt(in.readLine()); :
Parts to a (OLD style IO) Program
INPUT &PARSING
standard name
Contest Algorithms 17
: // Calculate the answer n *= 567; n /= 9; n += 7492; n *= 235; n /= 47; n -= 498;
// Digit in the tens column int tens = (n / 10) % 10;
System.out.println(tens); } } // end of main()
} // end of Main class
PROCESSING /ALGORITHM
OUTPUT
Contest Algorithms 18
public static int parseInt(String s) { if (s == null) return 0; try { return Integer.parseInt(s); } catch (NumberFormatException ex){ System.out.println(s + " could not be parsed as an int; using 0"); return 0; } } // end of parseInt()
Parsing String to int
Scanner s = new Scanner(System.in);while (s.hasNextLine()) { String line = s.nextLine(); // process line ...}
Console r = System.console();String line = null;while ((line = r.readLine()) != null) { // process line ...}
Two modern ways
use this one
Contest Algorithms: 1. Intro 20
import java.util.Scanner;
public class ScannerAdd // use Main in contests{ public static void main(String[] args) throws Exception { Scanner s = new Scanner( System.in ); System.out.print("Enter first integer: "); int x = s.nextInt(); System.out.print("Enter second integer: "); int y = s.nextInt(); s.close(); System.out.println("Adding gives: " + (x+y) ); }} // end of ScannerAdd class
Adding Two Numbers see ScannerAdd.java
Contest Algorithms: 1. Intro 21
Compile & Execute
Contest Algorithms: 1. Intro 22
import java.io.*;import java.util.Scanner;
public class AddDoubles // use Main in contests{ public static void main(String[] args) throws Exception { double total = 0; Scanner sc = new Scanner(System.in);
while ( sc.hasNextDouble() ) total += sc.nextDouble();
sc.close(); System.out.println("Total = " + total ); }} // end of AddDoubles class
Adding any number of Numberssee AddDoubles.java
Contest Algorithms: 1. Intro 23
Compile & Execute
ctrl-D and<enter>
inaccuracy infloating point
Contest Algorithms 24
import java.io.*;import java.util.*;
public class UseGraph // use Main in contests{ public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new File("graphData.txt")); // for testing
int numVs = sc.nextInt(); int[][] adjMat = new int[numVs][]; // use numVs as no. of rows for (int i = 0; i < numVs; i++) { adjMat[i] = new int[numVs]; // create ith row array for (int j = 0; j < numVs; j++) // fill row adjMat[i][j] = sc.nextInt(); } :
Fill an Integer Matrix see UseGraph.java
Contest Algorithms: 1. Intro 25
// print it out for (int i = 0; i < numVs; i++) { for (int j = 0; j < numVs; j++) System.out.printf(" %3d", adjMat[i][j]); System.out.println(); } System.out.println(); } // end of main()
} // end of UseGraph class
Contest Algorithms: 1. Intro 26
Compile & ExecuteReading from graphData.txt
Contest Algorithms 27
6 0 10 0 0 100 0 10 0 7 0 8 0 0 7 0 9 0 00 0 9 0 20 5100 8 0 20 0 0 0 0 0 5 0 0
graphData.txt
Reading Data Using Scanner
28
java.util.Scanner
+Scanner(source: File)
+Scanner(source: String)
+close()
+hasNext(): boolean
+next(): String
+nextByte(): byte
+nextShort(): short
+nextInt(): int
+nextLong(): long
+nextFloat(): float
+nextDouble(): double
+useDelimiter(pattern: String): Scanner
Creates a Scanner that produces values scanned from the specified file.
Creates a Scanner that produces values scanned from the specified string.
Closes this scanner.
Returns true if this scanner has another token in its input.
Returns next token as a string.
Returns next token as a byte.
Returns next token as a short.
Returns next token as an int.
Returns next token as a long.
Returns next token as a float.
Returns next token as a double.
Sets this scanner’s delimiting pattern.
Contest Algorithms 29
Almost the same as C's printf(). The main formating operations:
Java's printf()
Format specifier Description
%d Displays a decimal (base 10 ) integer
%f Display a floating point value in decimal format
%e or %E Display a floating point number in exponential notation
%c or %C Display characters%s or %S Display Strings%b or %B Display boolean values%% Display a % sign
Contest Algorithms 30
1 page quick reference: https://www.cs.colostate.edu/~cs160/.Fall15/resources/
Java_printf_method_quick_reference.pdf
More words, but still 1 page: http://www.javawithus.com/tutorial/displaying-text-using-
printf-method
More information on printf
Contest Algorithms 31
import java.util.Scanner;
public class Main { // save as Main.java public static void main(String[] args) { Scanner in = new Scanner(System.in); int i = in.nextInt(); double d = in.nextDouble();
String s = in.next(); // There is no nextChar(), use next() and charAt() char c = s.charAt(2); // third char // Read whole line (or rest of the line past '\n') String line = in.nextLine(); System.out.printf("%4d, %6.2f, %s, %c\n", i, d, s, c); // Use %f for double (not %lf) // Don't forget to print the '\n' }}
Template for ICPC Online Judge
https://www3.ntu.edu.sg/home/ ehchua/programming/ icpc/icpc_getting_started.html
see Main.java
Contest Algorithms: 1. Intro 32
Analyze your algorithm
Is your algorithm correct?
What is its time/space complexity?
Given the maximum input (usually given in the problem), can your algorithm stay inside the time limit for the contest?
33
Some rules of thumb
The biggest Java integer data structure long can store 263-1 ≈ 9*1018 (up to 18 digits)
If you have k nested loops, each doing about n iterations, then the program has O(nk) runtime
The best times for sorting n elements is O(n log n) quicksort, mergesort use Java’s Arrays.sort()
34
Contest Algorithms:12. Maths 35
Java Primitive Types
More info:https://docs.oracle.com/javase/tutorial/java/ nutsandbolts/datatypes.html
2 x 109
9 x 1018
Contest Algorithms 36
Dynamic programming algorithms involving a table/matrix usually have O(n3) runtime
Aim to use O(n log n) algorithms e.g. binary search Java’s Array.binarySearch()
Testing your code
The sample input in the problem description is usually too simple for testing
Design tricky test cases, test them on your machine. Boundary cases Big input Badly formatted input Random test cases
37
38
Submission Error (SE) Output Limit Exceeded (OL) Restricted Function (RF)
There are many ways to fail:
Presentation Error (PE) Wrong Answer (WA) Compile Error (CE) Runtime Error (RTE) Time Limit Exceeded (TLE) Memory Limit Exceeded
(MLE)
Judged code
Contest Algorithms
Contest Algorithms 39
Accepted (AC) – Congratulations!
Accepted (PE) – Your program has a minor presentation error, but the judge is letting you off with a warning.
Stop here and declare victory!
Presentation Error (PE) – Check for spaces, left/right justification, line feeds, etc.
Meanings
Contest Algorithms 40
Wrong Answer (WA) – Your program returned an incorrect answer to one or more secret test cases.
Compile Error (CE) – The compiler could not figure out how to compile your program.
The resulting compiler messages will be returned to you. Warning messages are ignored by the judge.
Runtime Error (RTE) – Your program failed during execution due to a segmentation fault, floating point exception, or similar problem.
Check for invalid pointer references or division by zero.
Contest Algorithms 41
Submission Error (SE) – You did not correctly specify one or more of the information fields, perhaps giving an incorrect user ID or problem number.
Time Limit Exceeded (TL) – Your program took too much time on at least one of the test cases, so you likely have a problem with efficiency.
Memory Limit Exceeded (ML) – Your program tried to use more memory than the judge’s default settings.
Contest Algorithms 42
For Java, the judges compile and execute your code using:
javac -encoding UTF-8 -sourcepath . -d . $* java -client -Xss8m -Xmx1024m $*
see https://icpc.baylor.edu/worldfinals/programming-environment
max heap sizefor object creation
thread stack sizefor storing its localexecution state
Contest Algorithms 43
Output Limit Exceeded (OL) – Your program tried to print too much output, perhaps trapped in a infinite loop.
Restricted Function (RF) – Your source program tried to use an illegal system function. Probably a file operation.
Contest Algorithms 44
Verdict by Language
from "Programming Challenges", Skiena, 2003;Java only allowed 1 year before
Contest Algorithms 45
https://github.com/alexjbest/icpc-tcr University of Warwick TCR docs
https://github.com/i8r/icpc-tcr University of of Lübeck, Germany
Java Team Contest Reference Docs
Contest Algorithms 46
Each contestant may bring a copy Up to 25 pages of ref materials, single-sided, letter
or A4 size, with pages numbered in the top right-hand corner and your university name in the top left-hand corner.
It may include hand-written comments and corrections on the fronts of pages only.
In a notebook or folder with the name of your institution on the front
TCR Doc Rules
Contest Algorithms 47
Write code using a programming font in a text editor with color highlighting:
e.g. Source Code Pro https://github.com/adobe-fonts/source-code-pro
e.g. Notepad++ https://notepad-plus-plus.org/
Use fineprint printer driver to print 4 or 8 pages/sheet: http://fineprint.com/fp/
Generating a TCR Doc
Contest Algorithms 48
Do not combine all the code files into one it makes it harder to change, test, regenerate the TCR
Install the "Print all" plugin into Notepad++ Go to Plugins -> Plugin Manager -> Show Plugin Manager,
then click on Available, then go down to Print all, check it, and install
Contest Algorithms 49
https://www3.ntu.edu.sg/home/ehchua/programming/icpc/icpc_getting_started.html
http://www.ahmedshamsularefin.id.au/ acm-icpc/tutorials/16-links
great collection of links
https://en.wikipedia.org/wiki/ ACM_International_Collegiate_Programming_Contest
links to blogs, training
ICPC Help
Contest Algorithms 50
Talking about programming contests only get you so far Past problems:
https://icpc.baylor.edu/worldfinals/problems
UVa Online Judge http://uva.onlinejudge.org
TopCoder http://topcoder.com
Project Euler http://projecteuler.net/
Practice
Available Online Judges (OJs) There are many famous online judges
Valladolid OJ (http://acm.uva.es/p) Ural OJ (http://acm.timus.ru) Saratov OJ (http://acm.sgu.ru) ZJU OJ (http://acm.zju.edu.cn) ZJUT OJ (http://acm.zjut.edu.cn) Official ACM Live Archive (http://cii-judge.baylor.edu/) Peking University Online Judge (
http://acm.pku.edu.cn/JudgeOnline/) Programming Challenges
(http://www.programming-challenges.com)
51
Contest Algorithms 52
TopCoder Weekly online individual competitions
Google Code Jam
Internet Problem Solving Competition Annual, fun, diferent style of problems
IOI, USACO
Other Programming Contests
Contest Algorithms 53
Competitive ProgrammingSteven and Felix Halim, Third Edition
http://cpbook.net/
Programming ChallengesSteven S. Skiena and Miguel Revilla
http://www.programming-challenges.com/
Textbooks
Contest Algorithms 54
From Baylor to BaylorMiguel A. Revilla
https://icpcarchive.ecs.baylor.edu/
Contest Algorithms 55
Intro to Java Programming, Comprehensive, 10th ed.Y. Daniel Liang
http://www.cs.armstrong.edu/liang/intro10e/
Topics 2D arrays, String, BigInteger, bitwise ops,
regexs Generics, Collections (lists, stack, queues,,
sets, maps) Sorting, searching graph algorithms (2 chapters)
Contest Algorithms 56
Algorithms, 4th ed.Robert Sedgewick, Kevin Wayne
http://algs4.cs.princeton.edu/
Introduction to Algorithms, 3rd ed.Thomas Cormen, Charles Leiserson, Ronald Rivest, Clifford Stein
lots of resources online; see video section
Contest Algorithms 57
การออกแบบและวิเคราะห์�อ�ลกอรทึ�ม ผู้��แต่�ง : สมชาย ประสทึธิ์�จู�ต่ระก�ล
http://www.chulabook.com/http://www.cp.eng.chula.ac.th/~somchai/books/
โครงสร�างข้�อม�ลและอ�ลกอรทึ�ม Data Structures and Algorithms)
ผู้��แต่�ง : ส"ธิ์# พงศาสก"ลช�ย & ณั�ฐพงษ์�วิาร#ประเสรฐhttp://ktpbook.com
MIT 6.046J / 18.410J Intro. to Algorithms, Fall 2005 http://ocw.mit.edu/6-046JF05
original course website for Cormen book
http://videolectures.net/mit6046jf05_introduction_algorithms/
video and slides side-by-side
http://www.catonmat.net/category/introduction-to-algorithms
notes taken while watching the videos
Videos
Contest Algorithms 59
Skiena's Algorithms Lectures http://www3.cs.stonybrook.edu/~algorith/video-lectures/ 1997, 2007, 2012
Contest Algorithms 60
Eclipse tutorials: http://eclipsetutorial.sourceforge.net/
totalbeginnerlessons.html 16 videos uses v3.3 (current is 4.5) from 2007
Various Youtube videos: Eclipse IDE Tutorial, luv2code (many videos) Eclipse IDE Tutorial, Norm Krumpe