




























































































Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!





























































































Foreword vi
Preface viii
Authors’ Profiles xix
List of Abbreviations xx
List of Tables xxi
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.
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
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
Table 2: Lesson Plan of Steven’s CS
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
// 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)
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
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:
xiii
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
From Steven: I want to thank
From Steven: Additionally, I also want to thank
xvi
To a better future of humankind, Steven and Felix Halim Singapore, 24 May 2013
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
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 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