Docsity

Dynamic Programming and Graph Problems in Programming Contests, Apuntes de Matemáticas

Vista previa parcial del texto

¡Descarga Dynamic Programming and Graph Problems in Programming Contests y más Apuntes en PDF de Matemáticas solo en Docsity!

Contents

Foreword vi

Preface viii

Authors’ Profiles xix

List of Abbreviations xx

List of Tables xxi

Foreword

A long time ago (on the 11th^ of November in 2003, Tuesday, 3:55:57 UTC), I received an e-mail with the following message:

“I should say in a simple word that with the UVa Site, you have given birth to a new CIVILIZATION and with the books you write (he meant “Programming Challenges: The Programming Contest Training Manual” [60], coauthored with Steven Skiena), you inspire the soldiers to carry on marching. May you live long to serve the humanity by producing super-human programmers.”

Although that was clearly an exaggeration, it did cause me to think. I had a dream: to create a community around the project I had started as a part of my teaching job at UVa, with people from all around the world working together towards the same ideal. With a little searching, I quickly found a whole online community running a web-ring of sites with excellent tools that cover and provide whatever the UVa site lacked. To me, ‘Methods to Solve’ by Steven Halim, a very young student from Indonesia, was one of the more impressive websites. I was inspired to believe that the dream would become real one day, because in this website lay the result of the hard work of a genius of algorithms and informatics. Moreover, his declared objectives matched the core of my dream: to serve humanity. Even better, he has a brother with similar interests and capabilities, Felix Halim. It’s a pity that it takes so much time to start a real collaboration, but life is like that. Fortunately, all of us have continued working together in a parallel fashion towards the realization of that dream—the book that you have in your hands now is proof of that. I can’t imagine a better complement for the UVa Online Judge. This book uses lots of examples from UVa carefully selected and categorized both by problem type and solving technique, providing incredibly useful help for the users of the site. By mastering and practicing most programming exercises in this book, a reader can easily solve at least 500 problems in the UVa Online Judge, which will place them in the top 400-500 amongst ≈100000 UVa OJ users. It’s clear that the book “Competitive Programming: Increasing the Lower Bound of Programming Contests” is suitable for programmers who want to improve their ranks in upcoming ICPC regionals and IOIs. The two authors have gone through these contests (ICPC and IOI) themselves as contestants and now as coaches. But it’s also an essential colleague for newcomers—as Steven and Felix say in the introduction ‘the book is not meant to be read once, but several times’. Moreover, it contains practical C++ source code to implement given algorithms. Un- derstanding a problem is one thing, but knowing the algorithm to solve it is another, and implementing the solution well in short and efficient code is tricky. After you have read this extraordinary book three times you will realize that you are a much better programmer and, more importantly, a happier person.

vi

Miguel A. Revilla, University of Valladolid UVa Online Judge site creator; ACM-ICPC International Steering Committee Member and Problem Archivist http://uva.onlinejudge.org; http://livearchive.onlinejudge.org

vii

We know that one cannot probably win the ACM ICPC regional just by mastering the contents of the current version (third edition) of this book. While we have included a lot of materials in this book—much more than in the first two editions—we are aware that much more than what this book can offer is required to achieve that feat. Some additional pointers to useful references are listed in the chapter notes for readers who are hungry for more. We believe, however, that your team will fare much better in future ICPCs after mastering the contents of this book. We hope that this book will serve as both inspiration and motivation for your 3-4 year journey competing in ACM ICPCs during your University days.

To IOI Contestants

Much of our advice for ACM ICPC contestants applies to you too. The ACM ICPC and IOI syllabi are largely similar, except that IOI, for now, currently excludes the topics listed in the following Table 1. You can skip these items until your university years (when you join that university’s ACM ICPC teams). However, learning these techniques in advance may definitely be beneficial as some tasks in IOI can become easier with additional knowledge. We know that one cannot win a medal in IOI just by mastering the contents of the current version (third edition) of this book. While we believe that many parts of the IOI syllabus has been included in this book—hopefully enabling you to achieve a respectable score in future IOIs—we are well aware that modern IOI tasks require keen problem solving skills and tremendous creativity—virtues that we cannot possibly impart through this static textbook. This book can provide knowledge, but the hard work must ultimately be done by you. With practice comes experience, and with experience comes skill. So, keep practicing!

Topic In This Book Data Structures: Union-Find Disjoint Sets Section 2.4. Graph: Finding SCCs, Network Flow, Bipartite Graphs Section 4.2.1, 4.6.3, 4.7. Math: BigInteger, Probability Theory, Nim Games Section 5.3, 5.6, 5. String Processing: Suffix Trees/Arrays Section 6. More Advanced Topics: A/IDA Section 8. Many of the Rare Topics Chapter 9

Table 1: Not in IOI Syllabus [20] Yet

ix

To Teachers and Coaches

This book is used in Steven’s CS3233 - ‘Competitive Programming’ course in the School of Computing at the National University of Singapore. CS3233 is conducted in 13 teaching weeks using the following lesson plan (see Table 2). The PDF slides (only the public version) are given in the companion web site of this book. Fellow teachers/coaches should feel free to modify the lesson plan to suit students’ needs. Hints or brief solutions of the non-starred written exercises in this book are given at the back of each chapter. Some of the starred written exercises are quite challenging and have neither hints nor solutions. These can probably be used as exam questions or contest problems (of course, solve them first!). This book is also used as a supplementary reading in Steven’s CS2010 - ‘Data Struc- tures and Algorithms’ course, mostly for the implementation of several algorithms and writ- ten/programming exercises.

Wk Topic In This Book 01 Introduction Ch 1, Sec 2.2, 5.2, 6.2-6.3, 7. 02 Data Structures & Libraries Chapter 2 03 Complete Search, Divide & Conquer, Greedy Section 3.2-3.4; 8. 04 Dynamic Programming 1 (Basic ideas) Section 3.5; 4.7. 05 Dynamic Programming 2 (More techniques) Section 5.4; 5.6; 6.5; 8. 06 Mid-Semester Team Contest Chapter 1 - 4; parts of Ch 9

  • Mid-Semester Break (homework) 07 Graph 1 (Network Flow) Section 4.6; parts of Ch 9 08 Graph 2 (Matching) Section 4.7.4; parts of Ch 9 09 Mathematics (Overview) Chapter 5 10 String Processing (Basic skills, Suffix Array) Chapter 6 11 (Computational) Geometry (Libraries) Chapter 7 12 More Advanced Topics Section 8.4; parts of Ch 9 13 Final Team Contest Chapter 1-9 and maybe more
  • No final exam -

Table 2: Lesson Plan of Steven’s CS

For Data Structures and Algorithms Courses

The contents of this book have been expanded in this edition so that the first four chapters of this book are more accessible to first year Computer Science students. Topics and exercises that we have found to be relatively difficult and thus unnecessarily discouraging for first timers have been moved to the now bulkier Chapter 8 or to the new Chapter 9. This way, students who are new to Computer Science will perhaps not feel overly intimidated when they peruse the first four chapters. Chapter 2 has received a major update. Previously, Section 2.2 was just a casual list of classical data structures and their libraries. This time, we have expanded the write-up and added lots of written exercises so that this book can also be used to support a Data Structures course, especially in the terms of implementation details. The four problem solving paradigms discussed in Chapter 3 appear frequently in typical Algorithms courses. The text in this chapter has been expanded and edited to help new Computer Science students.

x

// Shortcuts for "common" data types in contests typedef long long ll; // comments that are mixed in with code typedef pair<int, int> ii; // are aligned to the right like this typedef vector vii; typedef vector vi; #define INF 1000000000 // 1 billion, safer than 2B for Floyd Warshall’s

// Common memset settings //memset(memo, -1, sizeof memo); // initialize DP memoization table with - //memset(arr, 0, sizeof arr); // to clear array of integers

// We have abandoned the use of "REP" and "TRvii" since the second edition // in order to reduce the confusion encountered by new programmers

The following shortcuts are frequently used in both our C/C++ and Java code:

// ans = a? b : c; // to simplify: if (a) ans = b; else ans = c; // ans += val; // to simplify: ans = ans + val; and its variants // index = (index + 1) % n; // index++; if (index >= n) index = 0; // index = (index + n - 1) % n; // index--; if (index < 0) index = n - 1; // int ans = (int)((double)d + 0.5); // for rounding to nearest integer // ans = min(ans, new_computation); // min/max shortcut // alternative form but not used in this book: ans <?= new_computation; // some code use short circuit && (AND) and || (OR)

Problem Categorization

As of 24 May 2013, Steven and Felix—combined—have solved 1903 UVa problems (≈ 46 .45% of the entire UVa problemset). About ≈ 1675 of them are discussed and categorized in this book. Since late 2011, some Live Archive problems have also been integrated in the UVa Online Judge. In this book, we use both problem numberings, but the primary sort key used in the index section of this book is the UVa problem number. These problems are categorized according to a ‘load balancing’ scheme: If a problem can be classified into two or more categories, it will be placed in the category with a lower number of problems. This way, you may find that some problems have been ‘wrongly’ categorized, where the category that it appears in might not match the technique that you have used to solve it. We can only guarantee that if you see problem X in category Y, then you know that we have managed to solve problem X with the technique mentioned in the section that discusses category Y. We have also limited each category to at most 25 (TWENTY FIVE) problems, splitting them into separate categories when needed. If you need hints for any of the problems (that we have solved), flip to the handy index at the back of this book instead of flipping through each chapter—it might save you some time. The index contains a list of UVa/LA problems, ordered by their problem number (do a binary search!) and augmented by the pages that contain discussion of said problems (and the data structures and/or algorithms required to solve that problem). In the third edition, we allow the hints to span more than one line so that they can be more meaningful. Utilize this categorization feature for your training! Solving at least a few problems from each category (especially the ones we have highlighted as must try *) is a great way to diversify your problem solving skillset. For conciseness, we have limited ourselves to a maximum of 3 highlights per category.

xii

Changes for the Second Edition

There are substantial changes between the first and the second edition of this book. As the authors, we have learned a number of new things and solved hundreds of programming problems during the one year gap between these two editions. We also have received feedback from readers, especially from Steven’s CS3233 class Sem 2 AY2010/2011 students, and have incorporated these suggestions in the second edition.

Here is a summary of the important changes for the second edition:

  • The first noticeable change is the layout. We now have a greater information density on each page. The 2nd^ edition uses single line spacing instead of the 1.5 line spacing used in the 1st^ edition. The positioning of small figures is also enhanced so that we have a more compact layout. This is to avoid increasing the number of pages by too much while still adding more content.
  • Some minor bugs in our code examples (both the ones displayed in the book and the soft copies provided in the companion web site) have been fixed. All code samples now have much more meaningful comments to aid in comprehension.
  • Several language-related issues (typographical, grammatical or stylistic) have been corrected.
  • Besides enhancing the discussion of many data structures, algorithms, and program- ming problems, we have also added these new materials in each chapter: 1. Many new Ad Hoc problems to kick start this book (Section 1.4). 2. A lightweight set of Boolean (bit-manipulation) techniques (Section 2.2), Implicit Graphs (Section 2.4.1), and Fenwick Tree data structures (Section 2.4.4). 3. More DP: A clearer explanation of bottom-up DP, the O(n log k) solution for the LIS problem, the 0-1 Knapsack/Subset Sum, and DP TSP (using the bitmask technique) (Section 3.5.2). 4. A reorganization of the graph material into: Graph Traversal (both DFS and BFS), Minimum Spanning Tree, Shortest Paths (Single-Source and All-Pairs), Maximum Flow, and Special Graphs. New topics include Prim’s MST algorithm, a discussion of DP as a traversal on implicit DAGs (Section 4.7.1), Eulerian Graphs (Section 4.7.3), and the Augmenting Path algorithm (Section 4.7.4). 5. A reorganization of mathematical techniques (Chapter 5) into: Ad Hoc, Java BigInteger, Combinatorics, Number Theory, Probability Theory, Cycle-Finding, Game Theory (new), and Powers of a (Square) Matrix (new). Each topic has been rewritten for clarity. 6. Basic string processing skills (Section 6.2), more string-related problems (Section 6.3), including string matching (Section 6.4), and an enhanced Suffix Tree/Array explanation (Section 6.6). 7. More geometry libraries (Chapter 7), especially on points, lines and polygons. 8. A new Chapter 8, which contains discussion on problem decomposition, advanced search techniques (A, Depth Limited Search, Iterative Deepening, IDA), ad- vanced DP techniques (more bitmask techniques, the Chinese Postman Problem, a compilation of common DP states, a discussion of better DP states, and some harder DP problems).

xiii

  • We now have proof that capable CS students can achieve ≥ 500 AC problems (from 0) in the UVa Online Judge in just one University semester (4 months) with this book.
  • The new (or revised) materials, chapter by chapter:
    1. Chapter 1 contains a gentler introduction for readers who are new to competitive programming. We have elaborated on stricter Input/Output (I/O) formats in typical programming problems and common routines for dealing with them.
    2. We add one more linear data structure: ‘deque’ in Section 2.2. Chapter 2 now contains a more detailed discussion of almost all data structures discussed in this chapter, especially Section 2.3 and 2.4.
    3. In Chapter 3, we have a more detailed discussions of various Complete Search techniques: Nested loops, generating subsets/permutations iteratively, and recur- sive backtracking. New: An interesting trick to write and print Top-Down DP solutions, Discussion of Kadane’s algorithm for Max 1D Range Sum.
    4. In Chapter 4, we have revised white/gray/black labels (legacy from [7]) to their standard nomenclature, renaming ‘max flow’ to ‘network flow’ in the process. We have also referred to the algorithm author’s actual scientific paper for a better understanding of the original ideas of the algorithm. We now have new diagrams of the implicit DAG in classical DP problems found in Section 3.5.
    5. Chapter 5: We have included greater coverage of Ad Hoc mathematics prob- lems, a discussion of an interesting Java BigInteger operation: isProbablePrime, added/expanded several commonly used Combinatorics formulae and modified sieve algorithms, expanded/revised sections on Probability Theory (Section 5.6), Cycle-finding (Section 5.7), and Game Theory (Section 5.8).
    6. Chapter 6: We rewrite Section 6.6 to have a better explanation of Suffix Trie/Tree/ Array by reintroducing the concept of terminating character.
    7. Chapter 7: We trim this chapter into two core sections and improve the library code quality.
    8. Chapter 8: The harder topics that were listed in Chapter 1-7 in the 2nd^ edition have now been relocated to Chapter 8 (or Chapter 9 below). New: Discussion of harder backtracking routine, State-Space search, meet in the middle, trick of using balanced BST as memo table, and a more comprehensive section about problem decomposition.
    9. New Chapter 9: Various rare topics that appear once a while in programming contests have been added. Some of them are easy, but many of them are hard and can be somewhat important score determinants in programming contests.

Supporting Websites

This book has an official companion web site at sites.google.com/site/stevenhalim, from which you can obtain a soft copy of sample source code and the (public/simpler version) of the) PDF slides used in Steven’s CS3233 classes.

All programming exercises in this book are integrated in the uhunt.felix-halim.net tool and can be found in the UVa Online Judge at uva.onlinejudge.org

New in the third edition: Many algorithms now have interactive visualizations at: www.comp.nus.edu.sg/~stevenha/visualization

xv

Acknowledgments for the First Edition

From Steven: I want to thank

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

Acknowledgments for the Second Edition

From Steven: Additionally, I also want to thank

  • the first ≈ 550 buyers of the 1st edition as of 1 August 2011 (this number is no longer updated). Your supportive responses encourage us!

xvi

  • fellow Teaching Assistant of CS3233 @ NUS in the past two years: Harta Wijaya, Trinh Tuan Phuong, and Huang Da.
  • my CS3233 students in Sem2 AY2011/2012 who contributed in both technical and presentation aspects of the second edition of this book, in alphabetical order: Cao Sheng, Chua Wei Kuan, Han Yu, Huang Da, Huynh Ngoc Tai, Ivan Reinaldo, John Goh Choo Ern, Le Viet Tien, Lim Zhi Qin, Nalin Ilango, Nguyen Hoang Duy, Nguyen Phi Long, Nguyen Quoc Phong, Pallav Shinghal, Pan Zhengyang, Pang Yan Han, Song Yangyu, Tan Cheng Yong Desmond, Tay Wenbin, Yang Mansheng, Zhao Yang, Zhou Yiming, and two other students who prefer to be anonymous.
  • the proof readers: Six of CS3233 students in Sem2 AY2011/2012 (underlined) and Hubert Teo Hua Kian.
  • my CS3233 students in Sem2 AY2012/2013 who contributed in both technical and presentation aspects of the second edition of this book, in alphabetical order: Arnold Christopher Koroa, Cao Luu Quang, Lim Puay Ling Pauline, Erik Alexander Qvick Faxaa, Jonathan Darryl Widjaja, Nguyen Tan Sy Nguyen, Nguyen Truong Duy, Ong Ming Hui, Pan Yuxuan, Shubham Goyal, Sudhanshu Khemka, Tang Binbin, Trinh Ngoc Khanh, Yao Yujian, Zhao Yue, and Zheng Naijia.
  • the NUS Centre for Development of Teaching and Learning (CDTL) for giving the initial funding to build the algorithm visualization website.
  • my wife Grace Suryani and my daughter Jane Angelina for your love in our family.

To a better future of humankind, Steven and Felix Halim Singapore, 24 May 2013

Copyright

No part of this book may be reproduced or transmitted in any form or by any means, elec- tronically or mechanically, including photocopying, scanning, uploading to any information storage and retrieval system.

xviii

Authors’ Profiles

Steven Halim, PhD^1

[email protected]

Steven Halim is currently a lecturer in School of Computing, National University of Singapore (SoC, NUS). He teaches sev- eral programming courses in NUS, ranging from basic programming methodology, inter- mediate data structures and algorithms, and also the ‘Competitive Programming’ module that uses this book. He is the coach of both the NUS ACM ICPC teams and the Singa- pore IOI team. He participated in several ACM ICPC Regional as student (Singapore 2001, Aizu 2003, Shanghai 2004). So far, he and other trainers @ NUS have success- fully groomed two ACM ICPC World Final- ist teams (2009-2010; 2012-2013) as well as two gold, six silver, and seven bronze IOI medalists (2009-2012). Steven is happily married with Grace Suryani Tioso and currently has one daugh- ter: Jane Angelina Halim.

Felix Halim, PhD^2

[email protected]

Felix Halim now holds a PhD degree from SoC, NUS. In terms of programming contests, Felix has a much more colourful reputation than his older brother. He was IOI 2002 contestant (representing Indonesia). His ICPC teams (at that time, Bina Nusantara Univer- sity) took part in ACM ICPC Manila Regional 2003-2004-2005 and obtained rank 10th, 6th, and 10th respectively. Then, in his final year, his team finally won ACM ICPC Kaohsiung Regional 2006 and thus became ACM ICPC World Finalists @ Tokyo 2007 (44th place). Today, he actively joins TopCoder Single Round Matches and his highest rating is a yellow coder. He now works at Google, Mountain View, United States of America.

(^1) PhD Thesis: “An Integrated White+Black Box Approach for Designing and Tuning Stochastic Local Search Algorithms”, 2009. (^2) PhD Thesis: “Solving Big Data Problems: from Sequences to Tables and Graphs”, 2012.

xix