COMPETITIVE PROGRAMMING

Increasing the Lower Bound of Programming Contests

STEVEN HALIM (PhD*, Instructor) FELIX HALIM (PhD candidate)

SCHOOL OF COMPUTING NATIONAL UNIVERSITY OF SINGAPORE

A HANDBOOK FOR ACM ICPC AND IOI CONTESTANTS 2010

Contents
Acknowledgements Preface Authors’ Profiles We Want Your Feedbacks Copyright Abbreviations List of Tables List of Figures 1 Introduction 1.1 Competitive Programming . . . . . . . . . . . . 1.2 Tips to be Competitive . . . . . . . . . . . . . 1.2.1 Tip 1: Quickly Identify Problem Types 1.2.2 Tip 2: Do Algorithm Analysis . . . . . . 1.2.3 Tip 3: Master Programming Languages 1.2.4 Tip 4: Master the Art of Testing Code . 1.2.5 Tip 5: Practice and More Practice . . . 1.3 Getting Started: Ad Hoc Problems . . . . . . . 1.4 Chapter Notes . . . . . . . . . . . . . . . . . . 2 Data Structures and Libraries 2.1 Data Structures . . . . . . . . . . . . . . . 2.2 Data Structures With Built-in Libraries . 2.2.1 Linear Data Structures . . . . . . 2.2.2 Non-Linear Data Structures . . . . 2.3 Data Structures With Our-Own Libraries 2.3.1 Graph . . . . . . . . . . . . . . . . 2.3.2 Union-Find Disjoint Sets . . . . . 2.3.3 Segment Tree . . . . . . . . . . . . 2.4 Chapter Notes . . . . . . . . . . . . . . . 3 Problem Solving Paradigms 3.1 Complete Search . . . . . . 3.1.1 Examples . . . . . . 3.1.2 Tips . . . . . . . . . 3.2 Divide and Conquer . . . . 3.2.1 Interesting Usages of iv v vi vii viii ix x xi 1 1 2 4 5 7 9 10 11 13 14 14 15 15 16 18 18 19 21 24 25 25 26 28 31 31

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Binary Search

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

i

. . . . .1 Overview and Motivation . . . . . . . . . . . . . . . . . .2 Directed Acyclic Graph . . . . . . . . . . 4. . . . . . . . . . . . 109 . . . . . . . .2 Depth First Search . . .3 @ Steven & Felix. . . . . . . . . . 34 34 34 36 39 39 44 46 54 56 57 57 57 66 68 73 74 76 80 84 85 86 87 90 92 92 93 93 96 97 98 99 99 100 100 100 102 104 104 104 106 107 107 107 4 Graph 4. . . . . . . .2 Greatest Common Divisor (GCD) & Lowest Common Multiple (LCM) 5. . . . . . . . 5. . . . . . . . 111 . . .1 Classical Example . . . . . . . . . . . . . . . . . . . . . . . 112 . . . . . . . . . . . . . . . . . 5. . . . . .2 Bonus Features . . . . . . . . . . . .2 Several Classical DP Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . 6. . . .3 Non Classical Examples . . .CONTENTS 3. . . . . . . . 111 . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Breadth First Search . . . . . . . . . .9. . . . . . . . . . . .9. . . . . . . . . .4. . . . . . . . . . . 3. . . . . . . . . . . . . . . . . . . . . . .7 Floyd Warshall’s . . 5. . 6.8 Ford Fulkerson’s/Edmonds Karp’s 4. . . . . 5. . . . . . . . . . . . . . . . . . . . .2. . . 4. . . . . . .4. .6 Fibonacci Numbers . . . . . . . 5. . . .1 DP Illustration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . 4. . . 109 . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . .4 Miscellaneous Mathematics Problems in Contests . . . . .4 Extended Euclid: Solving Linear Diophantine Equation . . .4. . . . .3 Palindrome . . . . . . . . . . . . . . . . . . . . . . . . .1 Overview and Motivation . . . . . . . . . . . ii . . . .3. . . .2. . . . . . .2 Non Classical Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . .9 Special Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . .1 Prime Numbers . . . . . .4 Remarks About Dynamic Programming in Programming Contests Chapter Notes . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . .2 Number Theory . . . . 112 . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . . . . . . . . . . . . .1 Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . NUS 3. . . . . . . . . . .5 Modulo Arithmetic . . . . . . . . . . . . . . . . 3. . 3. . . . . .2. . . .3 Bipartite Graph . . . . . . . . . . 5. . . . . . . . . . .3 Euler’s Totient (Phi) Function . . . . 5. . . . . .4. .2. . . . . . .5 Linear Algebra . . . . . 5. .3 Java BigInteger Class . . . . . . . . . . . . . . .3 Remarks About Greedy Algorithm in Programming Contests . . . . . 5. . . .3. . . . . . . . . . . . . 5. . . . . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . .2 Ad-hoc String Processing Problems . . . . . . . . . 4. . . . . . . . . . . . . . . . . . .1 Combinatorics . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . 3. . . . . . . . . .1 Basic Features . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3. . . . . . . . . . . .4 Kruskal’s . . . 3.1 String Alignment (Edit) . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . .3 Existing (or Fictional) Sequences and Number Systems . .5 Greedy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Mathematics 5. . . . . . . . . . . . . . .5 Chapter Notes . . . . . . . . . . . . . . . 109 . . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . 5. . . 4. . . . . . . . . . . . . .2 Cycle-Finding . . . . . . . . . . . . . . . .1 Overview and Motivation . .4 Probability Theory . .9. . . . . . . . . . . . . .10 Chapter Notes . . . . . . . . . . .4. . . . . . . . . .4 3. . . . . 5. . . .3. . . . . . 5. . .3. . . . . . . .2. . . 6.6 Bellman Ford’s . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . 3. . . Dynamic Programming . . . . . . . . . . 6 String Processing 6. . . . . . .3 String Processing with Dynamic Programming 6. . . . . . . . . . . . . . . .7 Factorial . . . . . . . .2 Longest Common Subsequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . .5 Dijkstra’s . . 5. . . . .

. . . . . . .3 Graham’s Scan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Applications of Suffix Tree 6. . . . . . . 130 . .1 Suffix Tree: Basic Ideas . . . . . . . . .5 Divide and Conquer Revisited . . . . . .3 Suffix Array: Basic Ideas . . . . . . . . . . . . . . . . .2 Geometry Basics . . . . . . . . 120 . . . . . . . . . .5. . . . . . . . . . . . . . . . . 132 133 134 135 iii . . . . . . . . . .4 6. . . . . .4. . . . .CONTENTS @ Steven & Felix. . . . . . . . . . . . . . . . . . . . . . . . . .4. . 6. . . 6. Problem . . . 7. . . . 131 . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 . . .1 Bisection Method for Geometry 7. . . . . . . . . . . . . . . .4 Intersection Problems . . . . . . . . NUS 6. . . . . . . . . . . . . . . . . . . . . . 131 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 . . . . . . . . . . . .5 Suffix Tree and Suffix Array . . . . . . . . . . Chapter Notes . . . .6 Chapter Notes . . . . . . . 113 113 114 115 118 7 (Computational) Geometry 7. . . . . A Code Library B Problem Credits Bibliography . . . . . . . . . . . 7. . . . . . . . 7. .1 Overview and Motivation . . .

Bramandia Ramadhana. • Fellow Teaching Assistants of CS3233 and ACM ICPC Trainers @ NUS: Su Zhan. for employing me and allowing me to teach CS3233 . Dr Sung Wing Kin. for sharing many data structures. Ken. Holy Spirit.CONTENTS @ Steven & Felix. Jesus Christ. • My lovely wife. National University of Singapore. NUS Acknowledgements . Aaron Tan Tuck Choy. Felix Halim. Melvin Zhang Zhiyong. Dr Alan Cheng Holun. • My father Lin Tjie Fong and mother Tan Hoey Lan for raising us and encouraging us to do well in our study and work. iv . Steven wants to thank: • God. etc. algorithms. etc. Dr Tan Sun Teck. Grace Suryani. Ngo Minh Duc.‘Competitive Programming’ module from which this book is born. • My CS3233 students in Sem2 AY2008/2009 who inspired me to come up with the lecture notes and CS3233 students in Sem2 AY2009/2010 who help me verify the content of this book plus the Live Archive contribution. • My younger brother and co-author. • School of Computing. • NUS/ex-NUS professors/lecturers who have shaped my competitive programming and coaching skills: Prof Andrew Lim Leong Chye. for allowing me to spend our precious time for this project. and programming tricks to improve the writing of this book. for giving talent and passion in this competitive programming.

www. But before you assume anything. 3). We hope to see many ICPC and IOI coaches around the world.net/uva/hunting. Beware that this book is not for a novice programmer. and have passed basic data structures and algorithms (or equivalent) typically taught in year one of Computer Science University curriculum. When we wrote the book. adopt this book knowing that without mastering the topics in and beyond this book. We believe this book is and will be relevant to many University and high school students as ICPC and IOI will be around for many years ahead. Use http://felix-halim.sg/~stevenha/programming/acmoj. We will be happy if in year 2010 and beyond. familiar with at least one programming language (C/C++/Java). at least during the middle phase of their programming career: when they want to leap forward from ‘just knowing some programming language commands’ and ‘some algorithms’ to become a top programmer. Hundreds Secondary or High School Students competing in annual International Olympiad in Informatics (IOI) [12].nus. and 4).com v . please check this book’s contents to see what we mean by ‘basic’.php. We know that one probably cannot win an ACM ICPC regional or get a gold medal in IOI just by mastering the current version of this book. While we have included a lot of materials in this book.comp.edu.html to help you to deal with UVa [17] problems listed in this book. are required to achieve that feat.php. Basically anyone who loves problem solving using computer. so make sure to attempt them. especially in South East Asia. Steven and Felix Halim PS: To obtain example source codes and PowerPoint slides/other instructional materials (only for coaches). this book is not meant to be read once. send a personal request email to stevenhalim@gmail. we set it for readers who have knowledge in basic programming methodology.com/problemssolve.CONTENTS @ Steven & Felix. and www. but several times. If such increase in ‘required lowerbound knowledge’ happens. 2). To a better future of humankind. Solving these exercises help strengthening the concepts taught in this book as they usually contain interesting twists or variants of the topic being discussed. this book has fulfilled its objective of advancing the level of human knowledge in this era. the level of competitions in ICPC and IOI increase because many of the contestants have mastered the content of this book. Typical readers of this book will be: 1). NUS Preface This is a book that every competitive programmer must read – and master. their students have no chance of doing well in future ICPCs and IOIs. There are many exercises and programming problems scattered throughout the body text of this book which can be skipped first if solution is not known at that point of time. Due to the diversity of its content. Some pointers are listed throughout this book for those who are hungry for more. New students will require the ‘basic’ knowledge presented in this book before hunting for more challenges after mastering this book. Thousands University students competing in annual ACM International Collegiate Programming Contest (ICPC) [27] regional contests. we are well aware that much more than what this book can offer.uvatoolkit. Their coaches who are looking for a comprehensive training materials [9]. but can be revisited in latter time after the reader has accumulated new knowledge to solve it.

felix. and up to the ‘Competitive Programming’ module that uses this book. Aizu 2003. stevenhalim@gmail. He participated in several ACM ICPC Regional as student (Singapore 2001. and 10th respectively.CONTENTS @ Steven & Felix. Then. Felix has much colorful reputation than his older brother. NUS).com Steven Halim is currently an instructor in School of Computing. felix halim actively joins TopCoder Single Round Matches and his highest rating is a yellow coder. Steven is not yet a PhD at this point of time: April 28. In terms of programming contests. Shanghai 2004). He is the coach of both NUS ACM ICPC teams and Singapore IOI team. intermediate data structures and algorithms. Felix Halim. He teaches several programming courses in NUS. NUS. in his final year. His teams (at that time. To be precise. PhD1. PhD Candidate. NUS Authors’ Profiles Steven Halim.halim@gmail. his team finally won ACM ICPC Kaohsiung Regional 2006 and thus became ACM ICPC World Finalist @ Tokyo 2007 (Honorable Mention). he and other trainers @ NUS have successfully groomed two-times ACM ICPC world finalist team as well as two silver and two bronze IOI medallists. 6. Bina Nusantara University) took part in ACM ICPC Manila Regional 2003-2004-2005 and obtained rank 10. 1 vi . ranging from basic programming methodology. Today.com Felix Halim is currently a PhD student in the same University: SoC. National University of Singapore (SoC. He is currently waiting for his final PhD thesis defense which is scheduled sometime in May 2010. He was IOI 2002 contestant. 2010. So far.

no part of this manuscript may be reproduced or transmitted in any form or by any means. Hundreds of hours have been devoted to write this book. NUS Copyright The manuscript of this book is written mostly during National University of Singapore (NUS) office hours as part of the ‘lecture notes’ for a module titled CS3233 . This arrangement probably will only last until the book is officially published. viii . including photocopying. For now.Competitive Programming. most of the time we will assist you to obtain a copy. we will ask you to get the book via ‘official means’. scanning. uploading to any information storage and retrieval system.com will do). NUS until appropriate arrangements have been made. By then.CONTENTS @ Steven & Felix. When this book goes to official publication. If you email and notify us. So. the copyright at the moment belong to the authors and School of Computing. electronically or mechanically. the new copyright will override this copyright page. without notifying the authors (a simple email to stevenhalim@gmail.

Please note that being well versed in competitive programming is not the end goal. The term ‘well-known CS problems’ implies that in competitive programming. solve them as quickly as possible!”. With this book. y ≤ 1000. we introduce readers to the world of competitive programming. Let di be the distance N between the houses of 2 students in group i. some people (at least the problem setter) have solved these problems before. enthusiastically. Form N groups such that i=1 di is minimized. the authors. The true end goal is to produce an all rounded computer scientists/programmers who are much more ready to produce better software or to face the harder CS research problems in the future. agree with it. Hopefully you enjoy the ride and continue reading and learning until the very last page of this book. Constraints: N ≤ 8. Abridged problem description: Let (x. ‘Solve them’ implies that we must push our CS knowledge to a certain required level so that we can produce working codes that can solve these problems too – in terms of getting the same output as the problem setter using the problem setter’s secret input data. Illustration on solving UVa Problem 10911 (Forming Quiz Teams). Let’s digest the terms one by one.y) be the coordinate of a student’s house on a 2-D plane. Definitely.Chapter 1 Introduction I want to compete in ACM ICPC World Final! — A dedicated student In this chapter. There are 2N students and we want to pair them into N groups. we are dealing with solved CS problems and not research problems (where the solutions are still unknown). The founders of ACM International Collegiate Programming Contest (ICPC) [27] have this vision and we. we play our little roles in preparing current and future generations to be more competitive in dealing with well-known CS problems frequently posed in recent ICPCs and International Olympiad in Informatics (IOI). 0 ≤ x. 1. Think first. ‘As quickly as possible’ is the competitive element which is a very natural human behavior. is this: “Given well-known Computer Science (CS) problems. try not to flip this page immediately! 1 .1 Competitive Programming ‘Competitive Programming’ in summary. it is just the means.

2. but do all those steps above in less than 30 minutes. We will start by giving you few general tips below: Tip 0: Type Code Faster! No kidding! Although this tip may not mean much as ICPC nor IOI are not about typing speed competition. Step 2: Skip the problem and read another problem.. then this book is definitely for you! In subsequent chapters. Complete search using backtracking gives Time Limit Exceeded (TLE). 1. 23. 24] (see Figure 1. • Very Competitive programmer E: Of course.. 13.. • Competitive programmer D: Same as programmer C. In general. you can re-read it after going through this book once..1. • Non-competitive programmer B (Give up): Step 1: Read the problem. test the solution. which one is you? Note that if you are unclear with the materials or terminologies shown in this chapter. 15. a very competitive programmer (e. it is now down to coding skill and . After 5 hours of labor (typical contest time).. you will learn basic to medium data structures and algorithms frequently appearing in recent programming contests.. to qualify in ACM ICPC [27] national.<.. but we have seen recent ICPCs where rank i and rank i + 1 are just separated by few minutes. Not only that.k. confused @-@. this problem must be solved using ‘Edmond’s Blossom Shrinking’. debug >. 5. the red ‘target’ coders in TopCoder [26]) may solve this ‘classical’ problem in less than 15 minutes.5). his solution is judged as AC (passed all secret test data). or in many other programming contests. 2. • (Still) non-competitive programmer C (Slow): Step 1: Read the problem and realize that it is a ‘matching on general graph’ problem.. When you can solve the same number of problems as your competitor. starting from reading non-trivial input and output. this problem is solve-able using Dynamic Programming! Step 2: Code I/O routine. 1. 14.2 Tips to be Competitive If you strive to be like competitive programmer D or E in the illustration above: You want to do well to qualify and get a medal in IOI [12]. but also how to implement them efficiently and apply them to appropriate contest problem.. 2 .. and up to world final.. 16. 21. 46. never see this kind of problem before. write recursive top-down DP. Step 2: Try to code something. Step 3: Realize that all his attempts fail: Greedy solution: pair students based on shortest distances gives Wrong Answer (WA). But also remember that he has not learned how to solve this kind of problem.. He is not aware of a simple solution for this problem: Dynamic Programming (DP).... But you will not just learn the algorithm.g. Step 3: Only after 3 hours. compiled from many sources [19. Then realize that he has seen this kind of problem before. You will also learn many tiny bits of programming tips from our experience that can be helpful in contest situation. • Non-competitive programmer A (a. 6. But since the input size is small. NUS Now. no Accepted (AC) solution is produced. ask yourself. 22. typing speed. etc.a the blurry one): Step 1: Read the problem. 20. TIPS TO BE COMPETITIVE @ Steven & Felix.. regional. 4.

etc to name the few.sgi.sun. a little detour to software engineering books may be worth trying. 13 . SPOJ www. CHAPTER NOTES @ Steven & Felix. e.pl. NUS 1.edu.5: Some Reference Books that Inspired the Authors to Write This Book This and subsequent chapters are supported by many text books (see Figure 1. There are approximately 33 programming exercises discussed in this chapter.edu.spoj.5) and Internet resources. ZOJ acm.com.g.cppreference.1. POJ acm. [4] chapter 1-5.tju. Reference for Tip 3 are www. Tip 1 is an adaptation from introduction text in USACO training gateway [18].cn/toj.4. You can also take a look at Appendix A for some of our examples. 17. More details about Tip 2 can be found in many CS books.edu. There are many other online judges than those mentioned in Tip 5.pku.com/javase/6/docs/api for Java API.4 Chapter Notes Figure 1.cn/JudgeOnline. www.zju.g.com/tech/stl/ for C++ STL and java.cn/onlinejudge/. e. TOJ acm. For more insights to do better testing (Tip 4).

This is done by calling ‘findSet(j)’ – what is the representative of item ‘j’. int j) { pset[findSet(i)] = findSet(j). DATA STRUCTURES WITH OUR-OWN LIBRARIES @ Steven & Felix.1) pset[i] = i.3. i <= int(b). we see what is happening when we call unionSet(i. } Figure 2. Figure 2.2. j)’ which makes both item ‘i’ and ‘j’ to have the same representative item6 – directly or indirectly (see Path Compression below). 0.3: Calling initSet() to Create 5 Disjoint Sets When we want to merge two sets. 6 20 . } There is another heuristic called ‘union-by-rank’ [4] that can further improve the performance of this data structure. REP (i. and assign that value to ‘pset[findSet(i)]’ – update the parent of the representative item of item ‘i’.4.4: Calling unionSet(i. } void unionSet(int i. adjustable by user void initSet(int _size) { pset. NUS #define REP(i. // 1000 is just a rough number. b) \ // all codes involving REP uses this macro for (int i = int(a). int findSet(int i) { return (pset[i] == i) ? i : (pset[i] = findSet(pset[i])).resize(_size). _size . we call ‘unionSet(i. But we omit this enhancing heuristic from this book to simplify this discussion. a. i++) vector<int> pset(1000). j) to Union Disjoint Sets In Figure 2. j): every union is simply done by changing the representative item of one item to point to the other’s representative item.

37 . Suppose we use a certain window length L. The numbers ai and bi are specified in minutes and satisfy 0 ≤ ai ≤ bi ≤ 1440.Problem A . stopping bisection method when error ≤ 1e-3 is enough. we want to highlight another problem solving trick called: Decomposition! While there are only ‘few’ basic algorithms used in contest problems (most of them are covered in this book). bi ] during which the i-th plane can land safely. which occurs between the first two airplanes.3. Divide & Conquer. star = its landing schedule. Compute an order for landing all airplanes that respects these time windows. Print the answer split into minutes and seconds. your task is to: 1.3. For example. We can binary search this L – bisection method – Divide & Conquer. previous landing time + L). if three airplanes land at 10:00am. then the smallest gap is five minutes. but the smallest gap should be as large as possible! HINT: Is this similar to ‘greedy activity selection’ problem [4]? 3. NUS In this special box. the harder problems may require a combination of two (or more) algorithms for their solution.7 for illustration: line = time window of a plane. and 10:15am. which give the beginning and end of the closed interval [ai . This time window is specified by two integers ai . This is the Complete Search portion of the problem which can be easily solved using C++ STL next permutation. For such problem. We can greedily check whether this L is feasible by forcing the first plane to land as soon as possible and the subsequent planes to land in max(a[that plane]. A window length L that is too long/short will overshoot/undershoot b[last plane]. for each specific landing order. an optimal solution can be found by simply trying all 8! = 40320 possible orders for the planes to land. Then. 10:05am. HINT: order = permutation = Complete Search? 2. we want to know the largest possible landing window. See Figure 3. rounded to the closest second. For more details. Furthermore. bi . Now. Each airplane has a time window during which it can safely land. the airplane landings should be stretched out as much as possible so that the minimum achievable time gap between successive landings is as large as possible. and Greedy! ACM ICPC World Final 2009 .7: Illustration for ACM ICPC WF2009 . This is a Greedy Algorithm. We illustrate this decomposition technique using a recent top-level programming problems that combines three problem solving paradigms that we have just recently learned: Complete Search. please study our AC source code shown in the next page.A Careful Approach You are given a scenario of airplane landings.A Careful Approach Solution: Since the number of planes is at most 8. try to decompose parts of the problem so that you can solve different parts of the problem independently. Figure 3. so we have to decrease/increase L.A . There are 2 ≤ n ≤ 8 airplanes in the scenario. As we only want the answer rounded to nearest integer. GREEDY @ Steven & Felix. Not all gaps have to be the same.

Stacking Boxes 2.4. UVa 10029 . SPECIAL GRAPHS @ Steven & Felix.The Largest Clique (find SCC first then longest path on DAG) 5. V in) : (u.9. One matching between (a. PKU 3160 .Edit Step Ladders 4. v) ∈ (V out. This problem has a polynomial solution: Construct a bipartite graph G = (Vout Vin .3 Bipartite Graph Bipartite Graph. LA 3126 . UVa 10000 . UVa 103 . Vin = {v ∈ V : v has positive in-degree}. UVa 10350 . DAG G initially has n vertices. v) ∈ E}. 87 . shown below. Note that path cover in general graph is NP-Complete [41]. LA 2696 .Travel 2. Ural 1450 .Russian pipelines 7. Thus if the max cardinality bipartite matching (MCBM) in G has size m. LA 3294 .Father Christmas flymouse • Min Path Cover in DAG 1.26: Min Path Cover in DAG (from LA 3126 [11]) In general. The solution for bipartite matching is polynomial.Liftless Eme • Single-Source Longest Paths in DAG 1. E ) from G. thus the solution for min path cover in DAG is also polynomial. is a special graph with the following characteristics: the set of vertices V can be partitioned into two disjoint sets V1 and V2 and all edges in (u. then we just need n − m paths to cover each vertex in G. UVa 10166 . NUS Figure 4.Taxi Cab Scheme 4. the min path cover problem in DAG is described as the problem of finding the minimum number of paths to cover each vertex in DAG G = (V. The MCBM in G that is needed to solve this min path cover in G is discussed below.Air Raid 2. where Vout = {v ∈ V : v has positive out-degree}. which can be covered with n paths of length 0 (the vertex itself). This G is a bipartite graph! Finding a matching in bipartite graph G forces us to select at most one outgoing edge from v ∈ Vout (similarly for Vin ).9. v) ∈ E has the property that u ∈ V1 and v ∈ V2 . UVa 11324 . b) says that we can use one less path as it can cover both vertices in a ∈ Vout and b ∈ Vin . The most common application is the (bipartite) matching problem. and E = {(u. E).The Ultimate Bamboo Eater (with 2-D Segment Tree) 6.Longest Paths 3. Programming Exercises related to DAG: • Single-Source Shortest Paths in DAG 1.

in). we have num1 * num2 as: num1 num2 = = 1.valueOf(F))).3.Krakovia */ public static void main(String[] args) { Scanner sc = new Scanner(System. F friends if (N == 0 && F == 0) break.000. Fortunately. Multiplication takes a bit more programming job.000. Anyway.util. combination of division and remainder – divideAndRemainder(BI).000 Addition and subtraction are two simple operations in BigInteger.nextInt(). multiplication – multiply(BI).math. subtraction – subtract(BI). coding these library routines under stressful contest environment can be a buggy affair.000. // for reading next BigInteger! sum = sum. // BigInteger class is inside this package class Main { /* UVa 10925 .000.000.000.divide(BigInteger.000. and power – pow(int exponent). // N bills.000.Krakovia which simply requires BigInteger addition (sum N large bills) and division (divide the large sum to F friends): import java.*.*.+ num1 * num2 = 17. For example we can store 1021 inside a string num1 = “1. remainder – remainder(BI).println(). Java has BigInteger class that we can use for this purpose (as of 2010.000.000” without much problem whereas this is already overflow in 64-bit unsigned long long in C/C++.000.000.000. i++) { // sum the N large bills BigInteger V = sc. BigInteger sum = BigInteger.nextBigInteger().out.000.000. int caseNo = 1.out. BigInteger library uses a kind of digit-by-digit operations to process the two big integer operands.000. modulo – mod(BI) (slightly different with remainder(BI)).5. Then.io.000. Java BigInteger (BI) class supports the following basic integer operations: addition – add(BI).000. // Scanner class is inside this package import java. // this is BigInteger addition } System. C++ STL currently does not have such library thus it is a good idea to use Java for BigInteger problems). F = sc. For example. for common mathematical operations. Efficient division and raising number to a certain power are more complicated.000.000 10.println("Bill #" + (caseNo++) + " costs " + sum + ": each friend should pay " + sum. For example with num2 = “17”. division – divide(BI). while (true) { int N = sc. JAVA BIGINTEGER CLASS @ Steven & Felix.000.00 -----------------------------. // use valueOf to initialize for (int i = 0.nextInt(). the following simple Java code is the solution for UVa 10925 . System.000.000.000. NUS The way BigInteger library works is to simply store the big integer as a (long) string.add(V).000. import java.000.000.000.000.*.000 17 -----------------------------.* 7. // the line above is BigInteger division } } } // divide the large sum to F friends 101 .valueOf(0). i < N.000.000.000.

we can build a generalized Suffix Tree for S1 and S2 with two different ending markers. go along edge label ‘a’. When the Suffix Tree is already built.g. Exercise: Now try to find Q = ’ca’ and Q = ’cat’! Finding Longest Repeated Substring in O(n) With Suffix Tree. right and Q = ’aca’.2. KMP).4. we can simply traverse from root.6. This can be done with just a root to leaf traversal by following the edge label. e.2. Vertex with path-label == Q is the desired vertex x. For example.3: Generalized Suffix Tree of S1 = ’acgat#’ and S2 = ’cgt$’ (Figure from [24]) 4 5 As Suffix Tree is more compact than Suffix Trie. all the leaves in the subtree rooted at x are the occurrences of Q in S. S1 with character ‘#’ and S2 with character ‘$’. in the Suffix Tree of S = ’acacag$’ shown in Figure 6. this approach is faster than many exact string matching algorithms (e. right. we can find all (exact) occurrences of a query string Q in S in O(|Q| + occ) where |Q| is the length of the query string Q itself and occ is the total number of occurrences of Q in S – no matter how long the string S is. In a string ‘abcdef’. we mark each internal vertices with has leaves that represent suffixes of both S1 and S2. Figure 6. With Suffix Tree.2 Applications of Suffix Tree Assuming that Suffix Tree4 for a string S is already built. This can be done with just O(n) tree traversal. we will concentrate on Suffix Tree. Recall that internal vertices represent more than 1 suffices. We simply report the deepest marked vertex as the answer. The leaves of this vertex x point to index 1 (substring: ’acacag$’) and index 3 (substring: ’acag$’). Then. in the Suffix Tree of S = ’acacag$’ shown in Figure 6. ‘bcd’ is substring (contiguous) and ‘bce’ is subsequence (may skip few characters) 114 . For example. the longest repeated substring is ‘aca as it is the path-label of the deepest internal vertex. The deepest internal vertex in the Suffix Tree of S is the answer. our task is to simply search for the vertex x in the Suffix Tree which represents the query string Q. right).2. Exercise: Find the longest repeated substring in S = ’cgacattacatta$’! Finding Longest Common Substring in O(n) The problem of finding Longest Common Substring (not Subsequence)5 of two or more strings can be solved in linear time with Suffix Tree.g. SUFFIX TREE AND SUFFIX ARRAY @ Steven & Felix. We can then read the starting indices of such substrings that are stored in the leaves of Suffix Tree. Consider two strings S1 and S2. NUS 6. Then. we can use it for these applications: Exact String Matching in O(|Q| + occ) With Suffix Tree. then edge label ‘ca’ to find vertex x with path-label ‘aca’ (follow the dashed red arrow in Figure 6.4. we can also find the longest repeated substring in S easily.

GRAHAM’S SCAN @ Steven & Felix.y .t a point called pivot (the bottommost and rightmost point in P .x .y.x. return dx * dx + dy * dy.C. (double)d1x) .A) based on its angle w. NUS Figure 7. b).3. In this section.5. the stack contains (bottom) 11-0-1-4-7-10-11 (top)).y . } bool angle_cmp(point a.r.x. point b) { // function to compute distance between 2 points int dx = a.pivot.b.x . a) < dist2(pivot.5. the stack previously contains (bottom) 11-0-1-2 (top). int dy = a. // global variable vector<point> polygon. so we pop 2. b) == 0) // collinear return dist2(pivot.5. omitting parts that have shown earlier like ccw function. int d2x = b.atan2((double)d2y. int dist2(point a. Each point of P is pushed once to S and points that are not going to be part of CH(P ) will be eventually popped from S (see Figure 7.x.B). When Graham’s Scan terminates.b. The ready implementation of Graham’s Scan. (double)d2x). Now 0-1-3 is a left turn. 1-2-3 is a right turn. // which one closer int d1x = a. point b) { // important angle-sorting function if (area2(pivot.x . double d = atan2((double)d1y. } 128 .pivot.5: Convex Hull CH(P ) of Set of Points P There are several Convex Hull algorithms available. whatever left in S are the points of CH(P ) (see Figure 7. is shown below: point pivot.D.7. see point 0 and the counter-clockwise order of the remaining points in Figure 7.y .y.y. Then. a.pivot. so we insert 3 to the stack. this algorithm maintains a stack S of candidate points. d2y = b. which now contains (bottom) 11-0-1-3 (top)). d1y = a.5. return (d < 0). we choose the simple O(n log n) Ronald Graham’s Scan algorithm. CH.pivot. but when we try to insert 3. This algorithm first sorts all n− points P (Figure 7.

2002. Programming Pearls. McGraw Hill. Ediciones Sello Editorial S. Pearson. Competitive Programming in National University of Singapore.uva. Addison Wesley. http://projecteuler.Bibliography [1] Ahmed Shamsul Arefin. and Otfried Cheong Schwarzkopf. [10] Steven Halim. [13] Jon Kleinberg and Eva Tardos. Algorithm Design. and Felix Halim. [2] Jon Bentley. ACM ICPC Live Archive. Algorithms. Roland Hock Chuan Yap.L. Introduction to The Design & Analysis of Algorithms. Mark Overmars. China. [4] Thomas H. pages 640–645. [14] Anany Levitin. [11] Competitive Learning Institute. Christos Papadimitriou. 2000. 2nd edition. 2007.ksp. 2000. In Principles and Practice of Constraint Programming. Charles E.es/archive/nuevoportal. Engineering Stochastic Local Search for the Low Autocorrelation Binary Sequence Problem. Art of Programming Contest (from Steven’s Website). and Cliff Stein. [15] Rujia Liu. IOI Syllabus. 5th edition. (Presented at Collaborative Learning Initiative Symposium CLIS @ ACM ICPC World Final 2010.org. Addison Wesley.net/. [8] Michal Foriˇek. MIT Press. [5] Sanjoy Dasgupta. http://ioinformatics. Leiserson. 2006. [9] Steven Halim and Felix Halim. 2008. Gyankosh Prokashoni (Available Online). [7] Project Euler. [6] Mark de Berg. 2001. 2008.sk/ misof/ioi-syllabus/ioi-syllabus-2009. Computational Geometry: Algorithms and Applications. 135 .pdf. s http://people. 2006. [12] IOI. Addison Wesley. Marc van Kreveld. 2010. Rivest. Ronald L. Introduction to Algorithm. 2nd edition. [3] Frank Carrano. Harbin. Tsinghua University Press. Springer. 2009. International Olympiad in Informatics. 1st edition. Project Euler. Cormen. Data Abstraction & Problem Solving with C++. and Umesh Vazirani. http://acm. 2nd edition. Algorithm Contests for Beginners (In Chinese).

Algorithms in Bioinformatics: A Practical Introduction. USACO Training Program Gateway. [21] Robert Sedgewick.org/wiki/Cycle detection.wikipedia. Cycle-Finding (Detection). Combinatorics. [25] TopCoder.topcoder.wikipedia. 2003. http://en. 2002. 2008. [33] Wikipedia. Addison Wesley. CRC Press (Taylor & Francis Group).org/wiki/Eight queens puzzle. [31] Wikipedia. Skiena and Miguel A. Catalan number.wikipedia. The Algorithm Design Manual. Programming Challenges. 2000. 2008. [30] Wikipedia. ACM International Collegiate Programming Contest. [34] Wikipedia.a programming contest approach. 3rd edition.org/wiki/Edmonds’s matching algorithm. The Art of Algorithms and Programming Contests (In Chinese).com/tc. [32] Wikipedia.org/wiki/Disjoint-set data structure. 1998. Cambridge University Press. Springer. [17] University of Valladolid. Suffix arrays .org.topcoder.com/tc?d1=tutorials&d2=alg index&module=Static. http://www. http://train. Elementary Number Theory and its applications. NUS [16] Rujia Liu and Liang Huang. Edmond’s matching algorithm. 2003. 136 . Algorithm Tutorials. Part 1-5. Computational Geometry in C. Eight queens puzzle.baylor.wikipedia. Tsinghua University Press. Rosen.wikipedia.edu/icpc.BIBLIOGRAPHY @ Steven & Felix. http://uva. [26] TopCoder. [24] Wing-Kin Sung. http://icpc.org/wiki/Catalan number.org/usacogate.org/wiki/Combinatorics. http://en. 4th edition. http://en. Disjoint-set data structure. [27] Baylor University. Springer. http://en. Algorithms in C++. 1st edition. [19] Joseph O’Rourke. [28] Adrian Vladu and Cosmin Negru¸eri. http://www. [22] Steven S Skiena. http://en. Online Judge. 2010. [18] USA Computing Olympiad. [20] Kenneth H.wikipedia. s [29] Wikipedia. Single Round Match (SRM).usaco. 2nd edition. [23] Steven S. Addison Wesley Longman.onlinejudge. http://en. Revilla.

Miller-Rabin Primality Test. http://en. Tarjan’s Strongly Connected Components Algorithm.BIBLIOGRAPHY @ Steven & Felix. [36] Wikipedia. http://en.wikipedia. [39] Wikipedia.wikipedia. [40] Wikipedia. http://en. http://en. http://en.org/wiki/Euler’s totient function. [37] Wikipedia. Gaussian Elimination for Solving System of Linear Equations.org/wiki/Tarjan’s strongly connected components algorithm.wikipedia.org/wiki/Lowest common ancestor. http://en. http://en. Sieve of Eratosthenes. 137 .wikipedia.wikipedia. NUS [35] Wikipedia. Path Cover. [41] Wikipedia. Programming Book (In Chinese).org/wiki/Pick’s theorem.wikipedia. [38] Wikipedia.org/wiki/Path cover.wikipedia.wikipedia.org/wiki/Gaussian elimination. [44] Wikipedia.org/wiki/http://en. Posts and Telecom Press. 2009. Great-Circle Distance.wikipedia.wikipedia. Lowest Common Ancestor. The Free Encyclopedia. http://en. Pick’s Theorem. [46] Yonghui Wu. [43] Wikipedia. Longest Path Problem. Euler’s totient function.wikipedia.org. [42] Wikipedia.org/wiki/Miller-Rabin primality test.org/wiki/Great circle distance. [45] Wikipedia.org/wiki/Longest path problem. http://en. http://en.

77 Minimax and Maximin. 66 Bridges. 15 Articulation Points. 57 Data Structure. 34 Factorial. 122 Heron’s Formula. 32 bitset. 31 Binary Search Tree. 97 Diophantus of Alexandria. 57 Dijkstra’s. 98 Euclid of Alexandria. 81 Eratosthenes of Cyrene. see String Processing Bisection Method. 1 Complete Search. Delbert Ray. Leonhard. 98 Direct Addressing Table. Edsger Wybe. 17 Heap. 97 Euler. 100 Fibonacci Numbers. 122 138 Gaussian Elimination. 75. 100 Binary Search. 16 Bioinformatics. 59 Floyd Warshall’s. 39 . 80 Edit Distance. 25 CCW Test. 37 Depth First Search. see Bridges Cut Vertex. 99 Flood Fill. 77 Ford Fulkerson’s. 25 Computational Geometry. 104 Competitive Programming. 126 Code Library. 127 Cut Edge. 81 Edmonds. 77 Floyd. 17 Divide and Conquer. 127 Graph. 104 Data Structures. 79 Transitive Closure. 111 Edmonds Karp’s. 80 Fulkerson. 26 Bellman Ford’s. 99 Fibonacci. 96 Extended Euclid. 73 Dijkstra. Leonardo. 73 Hash Table. 120 Graham’s Scan. 94 Euclid Algorithm. 127 Graham. see Euler’s Totient Euler’s Totient. 80 Ford Jr. 78 Area of Polygon. see Geometry Connected Components. 14 Decomposition. 96 Euler’s Phi. 133 Combinatorics. 59 Convex Hull. 61 Brute Force. Jack. 96 Greedy Algorithm. 107 Geometry. Ronald. 31 Dynamic Programming. 94 Breadth First Search. 61 Backtracking. 75 BigInteger seeJava BigInteger Class. 75 Bellman. see Articulation Points Cycle-Finding. 125 Array / Vector. Lester Randolph. 16 Heron of Alexandria. Robert W. Richard. 18 Greatest Common Divisor.Index ACM. 1 All-Pairs Shortest Paths.

93 Palindrome. 127 Pick. 100 Base Number Conversion. 64 Suffix Array. 112 Longest Common Substring. 87 Max Cardinality Bipartite Matching. 86 SSSP. 69 ‘Maximum’ Spanning Tree. Richard.INDEX @ Steven & Felix. Joseph Bernard. 14 Linear Algebra. 93 Prime Factors. 92 Max Flow. 107 Pythagorean Theorem. Georg Alexander. Gene. 85 Diameter of Tree. 107 Linear Diophantine Equation. 69 Kruskal. 110 String Processing. 74 Unweighted. 70 Minimum Spanning ‘Forest’. 102 Karp. see String Matching Strongly Connected Components. 15 Live Archive. 84 Bipartite Graph. 71 Partial ‘Minimum’ Spanning Tree. 93 Primality Testing. 114 139 . 15 String Alignment. 109 String Searching. 69 Law of Cosines. 81 Kruskal’s. 85 Stack. 96 Manber. 115 Mathematics. 85 Articulation Points and Bridges. 84 Min Cut. 99 Myers. 111 String Matching. 102 modPow. 98 Linked List. 83 Min Cost (Max) Flow. 85 APSP. 10 Longest Common Subsequence. 123 Pythagorean Triple. 106 Single-Source Shortest Paths Detecting Negative Cycle. 112 Pick’s Theorem. 67 Weighted. 73 Special Graphs. see Max Flow Number System. see CCW Test Libraries. 115 Network Flow. 115 Suffix Tree. 70 Second Best Spanning Tree. 127 Prime Numbers. 15 Range Minimum Query. 86 Longest Paths. Udi. 71 Modulo Arithmetic. 94 Probability Theory. 113 Applications Exact String Matching. NUS ICPC. 21 Segment Tree. 1 Java BigInteger Class. 1 Intersection Problems. 95 Sieve of Eratosthenes. 103 GCD. 80 Max Edge-Disjoint Paths. 88 Max Weighted Independent Set. 85 Max Weighted Independent Set. 123 Left-Turn Test. 86 Min Path Cover. 86 Tree. 130 IOI. 123 Queue. 85 Lowest Common Multiple. 114 Lowest Common Ancestor. 106 Number Theory. 75 Negative Weight. 85 SSSP. 88 Directed Acyclic Graph. 82 Multi-source Multi-sink Max Flow. 21 Sequences. 83 Max Flow with Vertex Capacities. 83 Minimum Spanning Tree. 83 Max Independent Paths.

10 Warshall. Robert Endre. 62. 19 USACO. 10 UVa. 10 Topological Sort. 77.INDEX @ Steven & Felix. Stephen. 64 TopCoder. 65 Union-Find Disjoint Sets. NUS Longest Common Substring. 78 140 . 114 Longest Repeated Substring. 114 Tarjan.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.