Download 01. Introduction

Document related concepts
no text concepts found
Transcript
Contest Algorithms
January 2016
1. Introduction
Dr. Andrew Davison
Dept. of Computer Engineering
Prince of Songkla University
[email protected]
Contest Algorithms
1
Prerequisites
 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
Contest Algorithms
2
Why Compete?
 Makes you a better programmer and thinker in many
situations
 Develop skills that will set you apart in the workforce
 It's fun 
Contest Algorithms
3
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
 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/
Contest Algorithms
6
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_Progr
amming_Contest
7
Teamwork
 Know your teammates
 Delegating problems to each other
 Share the computer time effectively
 Create test cases for each other
 Communicate well
 Pair programming
Contest Algorithms
8
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
Problem Statement/Recipe
 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
Contest Algorithms
10
Quickly identify problem types
 Complete search
 also known as brute force
 backtracking
 Divide and conquer
 Graph
 traversal
 minimal spanning tree (MST)
 shortest paths
 maxflow
Contest Algorithms
 Searching / Sorting
 Dynamic programming
 Greedy
 Maths
 number theory, big integer, etc
 String processing
 Computational geometry
11
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) // bad
if (Math.abs(x-4) < 1e-9) // good
14
Steps to solving a problem
 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
Contest Algorithms
15
Parts to a (OLD style IO) Program
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());
:
Contest Algorithms
16
:
// Calculate the answer n
n /= 9;
n += 7492;
n *= 235;
n /= 47;
n -= 498;
*=
567;
// Digit in the tens column
int tens = (n / 10) % 10;
System.out.println(tens);
}
} // end of main()
}
// end of Main class
Contest Algorithms
17
Parsing String to int
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()
Contest Algorithms
18
Two modern ways
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 ...
}
use this one
Adding Two Numbers
see ScannerAdd.java
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
Contest Algorithms: 1. Intro
20
Compile & Execute
Contest Algorithms: 1. Intro
21
Adding any number of Numbers
import java.io.*;
import java.util.Scanner;
see AddDoubles.java
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
Contest Algorithms: 1. Intro
22
Compile & Execute
ctrl-D and
<enter>
Contest Algorithms: 1. Intro
inaccuracy in
floating point
23
Fill
an
Integer
Matrix
import java.io.*;
see UseGraph.java
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"));
testing
// for
int numVs = sc.nextInt();
int[][] adjMat = new int[numVs][];
for (int i = 0; i < numVs; i++) {
adjMat[i] = new int[numVs];
for (int j = 0; j < numVs; j++)
adjMat[i][j] = sc.nextInt();
}
Contest Algorithms
:
// use numVs as no. of rows
// create ith row array
// fill row
24
// 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
25
Compile & Execute
Reading from graphData.txt
Contest Algorithms: 1. Intro
26
graphData.txt
6
0 10
0 0 100 0
10 0 7 0 8 0
0 7 0 9 0
0
0 0 9 0 20
5
100 8
0 20 0 0
0 00 5 00
Contest Algorithms
27
Reading Data Using Scanner
java.util.Scanner
+Scanner(source: File)
Creates a Scanner that produces values scanned from the specified file.
+Scanner(source: String)
Creates a Scanner that produces values scanned from the specified string.
+close()
Closes this scanner.
+hasNext(): boolean
Returns true if this scanner has another token in its input.
+next(): String
Returns next token as a string.
+nextByte(): byte
Returns next token as a byte.
+nextShort(): short
Returns next token as a short.
+nextInt(): int
Returns next token as an int.
+nextLong(): long
Returns next token as a long.
+nextFloat(): float
Returns next token as a float.
+nextDouble(): double
Returns next token as a double.
+useDelimiter(pattern: String):
Scanner
Sets this scanner’s delimiting pattern.
28
Java's printf()
 Almost the same as C's printf().
 The main formating operations:
Contest Algorithms
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
%s or %S
%b or %B
%%
Display characters
Display Strings
Display boolean values
Display a % sign
29
More information on printf
 1 page quick reference:
 https://www.cs.colostate.edu/~cs160/.Fall15/resources/Java_pri
ntf_method_quick_reference.pdf
 More words, but still 1 page:
 http://www.javawithus.com/tutorial/displaying-text-using-printfmethod
Contest Algorithms
30
Template for ICPC Online Judge
import java.util.Scanner;
see Main.java
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();
https://www3.ntu.edu.sg/home/
ehchua/programming/
icpc/icpc_getting_started.html
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'
}
Contest Algorithms
}
31
Contest Algorithms: 1. Intro
32
Scanner is a bit Slow
https://www.cpe.ku.ac.th/~jim/java-io.html
 I created a file of 10,000 random integers (in
nums10000.txt)
ScannerTest.java
 Scanner takes 80 - 90 ms to read in all the values
 I have found two alternatives to Scanner:
 Kattio.java (https://open.kattis.com/download/Kattio.java)
 FastIntScanner.java (http://codeforces.com/blog/entry/21125)
 Their speeds:
 Kattio: 15 - 25 ms
 FastIntScanner: 5 – 20 ms
Contest Algorithms: 1. Intro
33
Kattio
Kattio.java
 It uses Java's BufferedReader and StringTokenizer classes
for input
 Also uses PrintWriter for output, to replace
System.out.println()
 Offers:
 hasNext(), nextInt(), nextDouble(), nextLong(), next()
 no nextLine()
 See the test client at the end of the class
Contest Algorithms: 1. Intro
34
FastIntScanner
FastIntScanner.java
 It uses only Java's BufferedReader and implements its own
tokenizer for integers.
 It does not use PrintWriter for output
 Offers:
 hasNext(), nextInt(), next(), nextLine()
 no nextDouble(), nextLong()
Contest Algorithms: 1. Intro
35
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?
36
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()
37
More info:
https://docs.oracle.com/javase/tutorial/java/
nutsandbolts/datatypes.html
Java Primitive Types
2 x 109
9 x 1018
Contest Algorithms:12. Maths
38
 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()
Contest Algorithms
39
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
40
Judged code
 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)
Contest Algorithms
 Submission Error (SE)
 Output Limit Exceeded (OL)
 Restricted Function (RF)
41
Meanings
 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.
Contest Algorithms
42
 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
43
 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
44
 For Java, the judges compile and execute your code
using:
 javac -encoding UTF-8 -sourcepath . -d . $*
 java -client -Xss8m -Xmx1024m $*
thread stack size
for storing its local
execution state
max heap size
for object creation
see https://icpc.baylor.edu/worldfinals/programming-environment
Contest Algorithms
45
 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
46
Verdict by Language
from "Programming Challenges", Skiena, 2003;
Java only allowed 1 year before
Contest Algorithms
47
Java Team Contest Reference Docs
 https://github.com/alexjbest/icpc-tcr
 University of Warwick TCR docs
 https://github.com/i8r/icpc-tcr
 University of of Lübeck, Germany
Contest Algorithms
48
TCR Doc Rules
 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
Contest Algorithms
49
Generating a TCR Doc
 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/
Contest Algorithms
50
 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
51
ICPC Help
 https://www3.ntu.edu.sg/home/ehchua/programming/ic
pc/icpc_getting_started.html
 http://umass.acm.org/interest-groups/acm-icpc/
acm-icpc-resources/
 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
Contest Algorithms
52
Practice
 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/
Contest Algorithms
53
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)
54
Other Programming Contests
 TopCoder
 Weekly online individual competitions
 Google Code Jam
 Internet Problem Solving Competition
 Annual, fun, diferent style of problems
 IOI, USACO
Contest Algorithms
55
Textbooks
 Competitive Programming
Steven and Felix Halim, Third Edition
 http://cpbook.net/
 Programming Challenges
Steven S. Skiena and Miguel Revilla
 http://www.programming-challenges.com/
Contest Algorithms
56
 From Baylor to Baylor
Miguel A. Revilla
 https://icpcarchive.ecs.baylor.edu/
Contest Algorithms
57
 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
58
 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
59
การออกแบบและวิเคราะห์อลั กอริทมึ
ผูแ้ ต่ง : สมชาย ประสิทธิ์จูตระกูล
http://www.chulabook.com/
http://www.cp.eng.chula.ac.th/~somchai/books/
โครงสร้างข้อมูลและอัลกอริทมึ
Data Structures and Algorithms)
ผูแ้ ต่ง : สุธี พงศาสกุลชัย
&
ณัฐพงษ์ วารีประเสริฐ
http://ktpbook.com
Contest Algorithms
60
Videos
 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
 Skiena's Algorithms Lectures
 http://www3.cs.stonybrook.edu/~algorith/video-lectures/
 1997, 2007, 2012
Contest Algorithms
62
 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
Contest Algorithms
63