Competitive Programming 4 Book 1 4th Edition Steven Halim pdf download
Competitive Programming 4 Book 1 4th Edition Steven Halim pdf download
https://ebookmeta.com/product/competitive-
programming-4-book-1-4th-edition-steven-halim/
https://ebookmeta.com/product/competitive-
programming-4-book-1-steven-halim/
https://ebookmeta.com/product/competitive-programming-4-the-
lower-bound-of-programming-contests-in-the-2020s-4th-edition-
steven-halim-2/
https://ebookmeta.com/product/competitive-programming-4-the-
lower-bound-of-programming-contests-in-the-2020s-4th-edition-
steven-halim/
https://ebookmeta.com/product/love-other-inconveniences-1st-
edition-catherine-cloud/
Collapsing Structures and Public Mismanagement 1st
Edition Wolfgang Seibel
https://ebookmeta.com/product/collapsing-structures-and-public-
mismanagement-1st-edition-wolfgang-seibel/
https://ebookmeta.com/product/ethos-logos-and-perspective-
studies-in-late-byzantine-rhetoric-first-edition-florin-leonte/
https://ebookmeta.com/product/ride-me-a-curvy-girl-military-mc-
romance-men-of-valor-mc-1st-edition-fern-fraser-2/
https://ebookmeta.com/product/applied-mathematics-class-xi-3rd-
edition-neeraj-raj-jain-m-l-aggarwal/
CC Certified in Cybersecurity Study Guide Sybex Study
Guide 1st Edition Chapple
https://ebookmeta.com/product/cc-certified-in-cybersecurity-
study-guide-sybex-study-guide-1st-edition-chapple/
This is the 100% identical eBook (PDF) version of CP4 Book 1
that was released on 19 July 2020
Please read https://cpbook.net/errata
for the latest known updates to this PDF
c Steven, Felix, Suhendry
ii
Contents
Abbreviations xxix
1 Introduction 1
1.1 Competitive Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 The Competitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 International Olympiad in Informatics (IOI) . . . . . . . . . . . . . . 3
1.2.2 International Collegiate Programming Contests (ICPC) . . . . . . . . 4
1.2.3 Other Programming Contests . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Tips to be Competitive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.1 Tip 1: Type Code Faster! . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3.2 Tip 2: Quickly Identify Problem Types . . . . . . . . . . . . . . . . . 8
1.3.3 Tip 3: Do Algorithm Analysis . . . . . . . . . . . . . . . . . . . . . . 10
1.3.4 Tip 4: Master Programming Languages . . . . . . . . . . . . . . . . . 15
1.3.5 Tip 5: Master the Art of Testing Code . . . . . . . . . . . . . . . . . 18
1.3.6 Tip 6: Practice and More Practice . . . . . . . . . . . . . . . . . . . 21
1.3.7 Tip 7: Team Work (for ICPC) . . . . . . . . . . . . . . . . . . . . . . 22
1.4 Getting Started: The Easy Problems . . . . . . . . . . . . . . . . . . . . . . 23
1.4.1 Anatomy of a Programming Contest Problem . . . . . . . . . . . . . 23
1.4.2 Typical Input/Output Routines . . . . . . . . . . . . . . . . . . . . . 23
1.4.3 Time to Start the Journey . . . . . . . . . . . . . . . . . . . . . . . . 26
1.4.4 Getting Our First Accepted (AC) Verdict . . . . . . . . . . . . . . . 27
1.5 Basic String Processing Skills . . . . . . . . . . . . . . . . . . . . . . . . . . 31
1.6 The Ad Hoc Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.7 Solutions to Non-Starred Exercises . . . . . . . . . . . . . . . . . . . . . . . 41
1.8 Chapter Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
iii
CONTENTS c Steven, Felix, Suhendry
4 Graph 193
4.1 Overview and Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
4.2 Graph Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
4.2.1 Overview and Motivation . . . . . . . . . . . . . . . . . . . . . . . . 195
4.2.2 Depth First Search (DFS) . . . . . . . . . . . . . . . . . . . . . . . . 195
4.2.3 Breadth First Search (BFS) . . . . . . . . . . . . . . . . . . . . . . . 197
4.2.4 Finding Connected Components (Undirected Graph) . . . . . . . . . 198
4.2.5 Flood Fill (Implicit 2D Grid Graph) . . . . . . . . . . . . . . . . . . 199
4.2.6 Topological Sort (Directed Acyclic Graph) . . . . . . . . . . . . . . . 200
4.2.7 Bipartite Graph Check (Undirected Graph) . . . . . . . . . . . . . . 202
4.2.8 Cycle Check (Directed Graph) . . . . . . . . . . . . . . . . . . . . . . 203
4.2.9 Finding Articulation Points and Bridges (Undirected Graph) . . . . . 205
4.2.10 Finding Strongly Connected Components (Directed Graph) . . . . . . 208
iv
CONTENTS c Steven, Felix, Suhendry
Bibliography 276
v
CONTENTS c Steven, Felix, Suhendry
vi
Forewords for CP4
Bill Poucher
Introduction
In 1970, the Texas A&M UPE Honor Society hosted the first university competitive pro-
gramming competition in the history of the ICPC. The first Finals was held in 1977 in
Atlanta in conjunction with the Winter Meeting of the ACM Computer Science Conference.
The ICPC International Collegiate Programming Contest hosted regional competitions at
643 sites in 104 countries for 59 000 team members and their 5043 coaches from over 3400
universities that span the globe. The top 135 teams of three will advance to the ICPC World
Finals in Moscow hosted by MIPT scheduled for June 2021.
ICPC alumni number over 400,000 worldwide, many playing key roles in building the
global digital community for many decades. The ICPC is the root of competitive program-
ming that reaches out through the global digital community to persons from all cultures and
in increasingly-younger generations.
The UVa Online Judge opened the doors for online competition and access to ICPC prob-
lems under the direction of Professor Miguel Ángel Revilla. Three of the star-studded team
are Steven Halim, Felix Halim, and Suhendry E↵endy, authors of Competitive Programming
4, Book 1 and Book 2. Their work will be honored at the ICPC World Finals in Moscow
hosted by MIPT with a special award from the ICPC Foundation.
Competitive Programming
What is competitive programming and why should you get involved? First and foremost, it’s
a mind sport. It more fully develops your algorithmic reasoning skills and bridges the gap
between theory and application in bite-sized chunks. Full participation develops problem-
solving intuition and competence. Get ready for the Digital Renaissance that will shape
your world in the coming decades. To understand the landscape, it is important to shape
your mind beyond a swarm of buzzwords. Do it as a team sport.
vii
FOREWORDS Bill Poucher
and the new program ICPC University Commons that will provide a spectrum of activities
that happen outside of the classroom. You can visit https://icpc.global for details.
Best, Bill
Dr. William B. “Bill” Poucher, Ph.D., ACM Fellow
Professor of Computer Science, Baylor University
Executive Director, ICPC International Collegiate Programming Contest
President, ICPC Foundation
July 13th, 2020.
viii
FOREWORDS Miguel Revilla Rodrı́guez
“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” [53], 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.”
What, in my father’s words, was “clearly an exaggeration”, caused some thinking. And it’s
not a secret that thoughts can easily lead to dreams. His dream was to create a community
around the project he had started, as part of is teaching job at the University of Valladolid,
Spain, that gathered people from all around the world working together towards the same
ideal, the same quest. With a little searching, on the primitive Internet of the first years of
our century, a whole online community of excellent users and tools, built around the UVa
site, came to light.
The website Methods to Solve 1 , created by a very young student from Indonesia, was one
of the most impressive among them. There was the result of the hard work of a real genius
of algorithms and computer science. The seed was planted to believe that the dream could
come true. Moreover, it was not only that the leaves of that growing tree were a perfect
match, but the root of both projects were exactly the same: to serve the humanity. That
young student, the author of the e-mail and the website that put my father to dream, was
Steven Halim. Later he would discover that Steven was not alone in his quest, as his younger
brother, Felix, shared his view, his interests, and his extraordinary capabilities.
After 15 years of fruitful collaboration and, more important, friendship with Steven and
Felix, my father sadly passed away in 2018. His work, and his dreams, now belong to us,
the next generation. This book is the living proof that the dream has become true.
“I can’t imagine a better complement for the UVa Online Judge”, are my father’s words.
Now, with this fourth version of Competitive Programming in my hands, I can add that I
can’t imagine the very existence of the Online Judge without this book. Both projects have
grown in parallel and are, no doubt, perfect complements and companions to each other.
By practicing and mastering most programming exercises in this book, the reader can learn
how to solve hundreds of tasks and find a place in the top 500 best Online Judge coders.
You have in your hands over 2000 (yes, two thousand!) selected, classified, and carefully
commented problems from the Online Judge.
The authors, in the past two decades, have grown from contestants, to coaches and,
finally, masters in the art of competitive programming. They perfectly know every curve
and crossroad in that long path, and they can put themselves in the skins of the young
IOI contestant, the ICPC newcomer or the seasoned coach, speaking to each in their own
language. This book is, for that very reason, the perfect reading for all of them. No matter
if you are starting as a competitive programmer in your local IOI, or are coaching in the
next ICPC World Finals, no doubt this IS the book for you.
1
Please visit https://cpbook.net/methodstosolve
ix
FOREWORDS Miguel Revilla Rodrı́guez
I love movies, I adore classic movies, and I know that what I’m watching is a masterpiece,
when, after the film ends, I can’t wait to start all over again. In Steven and Felix own words
“the book is not meant to be read once, but several times”. And you will find that same
feeling, not only because the authors recommend it, but because you will be anxious to read
and re-read it as, like in the greatest movies, you will find something new and amazing each
time. This book is, by that logic, a masterpiece.
I also have the great honor of being the Spanish language translator of this book. Trans-
lating requires a very meticulous process of converting the words while keeping the spirit.
You have to think as the author would think, and have to perfectly understand not only
what the author is saying, but also what the author is meaning. It is a handcrafting exer-
cise. Having gone forth and back through this text hundreds of times, I have enjoyed every
concept, every new idea, and every tip, not only by what is written in it, but also by what
it wants to achieve. The quest of making better programmers and, behind that, the quest
of serving humanity. This book is, indeed, a truly masterpiece.
Once you’ve read this book several times, you will realize how much a better programmer
you are but, believe it or not, you will realize that you are also a happier person.
Miguel Revilla Rodrı́guez (Miguel Jr)
Online Judge Manager
https://onlinejudge.org
July 1st, 2020, Valladolid.
x
FOREWORDS Fredrik Niemelä
Fredrik Niemelä
I got my first physical copy of this book from Steven at IOI 2012 in Italy. Like so many other
computer scientists, he has a great sense of humor, and named it “Competitive Programming:
Increasing the Lower Bound of Programming Contests.” It was the second edition of the
book and already twice the size of the first edition. Packed with practical advice, it was well-
suited to get beginners started and had useful material for the more seasoned algorithmist.
Steven and Felix’s vision for their book was to teach everybody how to program (As
Gusteau from Ratatouille would put it: “Tout le monde peut programmer”). I had a similar
vision, but instead of writing a book, we created Kattis. “Competitive Programming” and
Kattis share this motivating principle: to make learning computer science and programming
accessible for everyone. In that sense, they are like two of many pieces in the same puzzle.
Kattis is an online tool for teaching computer science and programming, which relies on
a curated library of programming tasks. I managed to convince Steven that he should try
using Kattis for some of his teaching activities. Over the years he has moved from using
Kattis, to pushing us to improve Kattis, to adding high-quality content to Kattis.
From years of teaching algorithms and using similar systems that preceded Kattis, we
learned that the quality of the problems, and their absolute correctness, are paramount for
learning outcomes. So, this is where we put extra e↵ort into Kattis. (If you ever felt that
it’s too much work to add problems to Kattis, this is why). What we did back then is now
standard practice—both the ICPC and IOI use the same kinds of methods for their finals.
In this fourth edition (more than twice as large as the second edition!), Steven and Felix,
now joined by co-author Suhendry, are using problems from Kattis. We are honored to be
included. Finally, our puzzle pieces are directly connected, and I am very excited about
that.
I hope you will find this book informative and helpful and that you will spend the time
it asks of you. You will not be disappointed.
Fredrik Niemelä
Founder of Kattis
ICPC Contest System Director
IOI Technical Committee Founding Member
https://www.kattis.com
July 11th, 2020.
xi
FOREWORDS Brian Christopher Dean
xii
Testimonials of CP1/2/3
xiii
TESTIMONIALS Various Book Readers
“Dr. Steven Halim is one of the best professors I have had in NUS. His intuitive
visualizations and clear explanations of highly complex algorithms make it significantly
easier for us to grasp difficult concepts. Even though I was never fully into Competitive
Programming, his book and his teaching were vital in helping me in job interviews and
making me a better coder. Highly recommend CP4 to anyone looking to impress in
software engineering job interviews.” — Patrick Cho, Machine Learning Scientist, Tesla.
“Flunked really hard at IOI 2017, missing medal cuto↵ by 1 place. Then at the beginning
of 2018 Steven Halim gave me a draft copy of CP3.1 / CP4 and I ended up getting a gold
medal!” — Joey Yu, Student, University of Waterloo, SWE Intern at Rippling,
IOI 2018 Gold Medalist.
“As a novice self-learner, CP-book helped me to learn the topics in both fun and
challenging ways. As an avid and experienced CP-er, CP-book helped me to find a
plentiful and diverse problems. As a trainer, CP-book helped me to plan ahead the
materials and tactical strategies or tricks in competition for the students. As the person
ever in those three di↵erent levels, I must e↵ortlessly say CP-book is a must-have to being
a CP master!” — Ammar Fathin Sabili, PhD Student, National University of Singapore.
“I’ve been in CP for three years. A rookie number for all the competitive programmers out
there. I have a friend (still chatting with him today) who introduced me to this book. He’s
my roommate on our National Training Camp for IOI 2018’s selection. I finally get a grab
of this book in early 2019. To be honest I’m not the ‘Adhoc’ and good at ‘Math’ type of
CP-er. I love data structures, graph (especially trees) And this CP3 book. Is a leap of
knowledge. No joke. I met Dr Felix when I was training in BINUS, I also met Dr Steven
when I competed in Singapore’s NOI and one of my unforgettable moment is, this legend
book got signed by its two authors. Even tho the book is full of marks and stains, truly
one of my favorite. Kudos for taking me to this point of my life.”
— Hocky Yudhiono, Student, University of Indonesia.
“I bought CP3 on 7th April 2014 on my birthday as a gift for myself and it has been the
most worth-it 30USD spent by me on any educational material. In the later years, I was
able to compete in IOI and ICPC WF. I think CP3 played a very big factor in igniting the
interest and providing a strong technical foundation about all the essential topics required
in CP.” — Sidhant Bansal, Student, National University of Singapore.
“I have always wanted to get involved in competitive programming, but I didn’t know how
and where to get started. I was introduced to this book while taking Steven’s companion
course (CS3233) in NUS as an exchange student, and I found the book to be really helpful
in helping me to learn competitive programming. It comes with a set of Kattis exercises as
well. This book provides a structured content for competitive programming, and can be
really useful to anyone ranging from beginners to experts. Just like CLRS for algorithms,
CP is THE book for competitive programming.” — Jay Ching Lim,
Student, University of Waterloo.
“My memories about CP3 is me reading it in many places, the bus, my room, the library,
the contest floor...not much time had passed since I start in competitive programming
reading CP3 until I got qualified to an ICPC World Final.”
— Javier Eduardo Ojeda Jorge, ICPC World Finalist, Universidad Mayor de San Simón,
Software Engineer at dParadig, Chile
xiv
Preface for CP4
This Competitive Programming book, 4th edition (CP4) is a must have for every compet-
itive programmer. Mastering the contents of this book is a necessary (but admittedly not
sufficient) condition if one wishes to take a leap forward from being just another ordinary
coder to being among one of the world’s finest competitive programmers.
Typical readers of Book 1 (only) of CP4 would include:
1. Secondary or High School Students who are competing in the annual International
Olympiad in Informatics (IOI) [31] (including the National or Provincial Olympiads)
as Book 1 covers most of the current IOI Syllabus [16],
2. Casual University students who are using this book as supplementary material for
typical Data Structures and Algorithms courses,
3. Anyone who wants to prepare for typical fundamental data structure/algorithm part
of a job interview at top IT companies.
1. University students who are competing in the annual International Collegiate Program-
ming Contest (ICPC) [57] Regional Contests (including the World Finals) as Book 2
covers much more Computer Science topics that have appeared in the ICPCs,
2. Teachers or Coaches who are looking for comprehensive training materials [21],
3. Anyone who loves solving problems through computer programs. There are numerous
programming contests for those who are no longer eligible for ICPC, including Google
CodeJam, Facebook Hacker Cup, TopCoder Open, CodeForces contest, Internet Prob-
lem Solving Contest (IPSC), etc.
Prerequisites
This book is not written for novice programmers so that we can write much more about
Competitive Programming instead of repeating the basic programming methodology con-
cepts that are widely available in other Computer Science textbooks. This book is aimed
at readers who have at least basic knowledge in programming methodology, are familiar
with at least one of these programming languages (C/C++, Java, Python, or OCaml) but
preferably more than one programming language, have passed (or currently taking) a basic
data structures and algorithms course and a discrete mathematics course (both are typically
taught in year one of Computer Science university curricula or in the NOI/IOI training
camps), and understand simple algorithmic analysis (at least the big-O notation). In the
next subsections, we will address the di↵erent potential readers of this book.
xv
Another Random Scribd Document
with Unrelated Content
And it appearing to me to be particularly essential to the interests of
this country, that an observance of the order and prohibition should
be obtained, I do hereby call upon all civil and military officers, who
now are, or hereafter may be appointed, to use their best endeavors
for detecting and bringing to justice every person who shall violate
the same. And, whereas, it appears to me to be expedient that
government should receive information of all characters, foreigners
and others, coming into the Territory, I do hereby order and direct
that any person arriving at this, or any of the military posts of the
United States within the same, should present himself to the
commanding officer of the troops in two hours next after his arrival;
and the inhabitants are hereby forbidden to entertain such
characters, whether whites, Indians, or negroes, without immediate
information thereof to the said commanding officers.
Given under my hand and seal at the town of Post Vincennes, and
county of Knox, this 28th day of June, A. D. 1790, and of the
Independence of the United States, the fourteenth.
(Signed,) Winthrop Sargent.
No. 5.—Extract of a Letter from the Hon. John Adams, Esq., Minister
Plenipotentiary of the United States at the Court of Great Britain, to
the Hon. John Jay, Esq., Secretary for Foreign Affairs. February 16,
1786.
"The American commerce can be protected from these Africans only
by negotiation, or by war. If presents should be exacted from us, as
ample as those which are given by England, the expense may
amount to sixty thousand pounds sterling a year, an enormous sum
to be sure; but infinitely less than the expense of fighting. Two
frigates of 30 guns each would cost as much to fit them for the sea,
besides the accumulating charges of stores, provisions, pay, and
clothing. The powers of Europe generally send a squadron of men of
war with their ministers, and offer battle at the same time that they
propose treaties and promise presents."
About this date the Algerines lost two or three vessels, stranded or
taken.
December, 1789.—Captain O'Brien furnishes the latest statement.
1 ship of 24 guns, received lately from France.
5 large cruisers.
6 3 galleys, and 60 gun-boats.
In the fall of 1789, they laid the keel of a 40 gun frigate, and they
expect two cruisers from the grand seignior.