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
PREFACE c Steven, Felix, Suhendry
Topics in Book 2
Math: Big Integer, Modular Inverse, Probability Theory, Game Theory
String Processing: Suffix Trees/Arrays, KMP, String Hashing/Rabin-Karp
(Computational) Geometry: Various Geometry-specific library routines
Graph: Network Flow, Harder Matching problems, Rare NP-hard/complete Problems
More than half of the Rare Topics
xvi
PREFACE c Steven, Felix, Suhendry
To ICPC Contestants
You are the primary readers of this CP4. Both Book 1 and Book 2 are for you.
We know that one cannot probably win an ICPC Regional Contest just by mastering
the contents of the current version of this book (CP4). While we have included a lot of
materials in this book—much more than in the first three editions (CP1 ✓ CP2, then CP2
✓ CP3, and finally CP3 ✓ CP4)—we are aware that much more than what this book can
o↵er 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 ICPCs during your University days.
This book is mainly 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 lesson plan mentioned in Table 2 (we abbreviate “Week” as “Wk”
in Table 2). Fellow teachers/coaches should feel free to modify the lesson plan to suit your
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 for your local contest problems (of course, you have to solve them first!).
xvii
PREFACE c Steven, Felix, Suhendry
To All Readers
Due to its diversity of coverage and depth of discussion, this book is not meant to be
read once, but several times. There are many written (⇡ 258) and programming exercises
(⇡ 3458) listed and spread across almost every section. You can skip these exercises at
first if the solution is too difficult or requires further knowledge and technique, and revisit
them after studying other chapters of this book. Solving these exercises will strengthen
your understanding of the concepts taught in this book as they usually involve interesting
applications, twists or variants of the topic being discussed. Make an e↵ort to attempt
them—time spent solving these problems will definitely not be wasted.
We believe that this book is and will be relevant to many high school students, University
students, and even for those who have graduated from University but still love problem solv-
ing using computers. Programming competitions such as the IOI and ICPC are here to stay,
at least for many years ahead. New students should aim to understand and internalize the
basic knowledge presented in this book before hunting for further challenges. However, the
term ‘basic’ might be slightly misleading—please check the table of contents to understand
what we mean by ‘basic’.
As the title of this book may imply, the purpose of this book is clear: we aim to improve
the reader’s programming and problem solving abilities and thus increase the lower bound
of programming competitions like the IOI and ICPC in the future. With more contestants
mastering the contents of this book, we believe that the year 2010 (CP1 publication year) was
a watershed marking an accelerated improvement in the standards of programming contests.
We hope to help more contestants to achieve greater scores ( 70 – at least ⇡ 6 ⇥ 10 points
for solving all subtask 1 of the 6 tasks of the IOI) in future IOIs and help more teams
solve more problems ( 2 – at least 1 more than the typical 1 giveaway problem per ICPC
problemset) in future ICPCs. We also hope to see many IOI/ICPC coaches around the world
adopt this book for the aid it provides in mastering topics that students cannot do without
in competitive programming contests. If such a proliferation of the required ‘lower-bound’
knowledge for competitive programming is continued in this 2020s decade, then this book’s
primary objective of advancing the level of human knowledge will have been fulfilled, and
we, as the authors of this book, will be very happy indeed.
Convention
There are lots of C/C++, Java, Python, and occasionally OCaml code included in this book.
If they appear, they will be typeset in this monospace font. All code have 2 spaces per
indentation level except Python code (4 spaces per indentation level).
For the C/C++ code in this book, we have adopted the frequent use of typedefs and
macros—features that are commonly used by competitive programmers for convenience,
brevity, and coding speed. However, we may not always be able to use those techniques in
Java, Python, and/or OCaml as they may not contain similar or analogous features. Here
are some examples of our C/C++ code shortcuts:
typedef long long ll; // common data types
typedef pair<int, int> ii; // comments that are mixed
typedef vector<int> vi; // in with code are placed
typedef vector<ii> vii; // on the right side
memset(memo, -1, sizeof memo); // to init DP memo table
vi memo(n, -1); // alternative way
memset(arr, 0, sizeof arr); // to clear array of ints
xviii
PREFACE c Steven, Felix, Suhendry
The following shortcuts are frequently used in both our C/C++ and Java code (not all of
them are applicable in Python or OCaml):
Problem Categorization
As of 19 July 2020, Steven, Felix, Suhendry—combined—have solved 2278 UVa problems
(⇡ 45.88% of the entire UVa problemset as of publication date). Steven has also solved
5742.7 Kattis points (⇡ 1.4K other problems and ⇡ 55.46% of the entire Kattis problemset
as of publication date). There are ⇡ 3458 problems have been categorized in this book.
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 limit each category to at most 35 (THIRTY-FIVE) problems, splitting
them into separate categories when needed. In reality, each category has ⇡ 17 problems on
average. Thus, we have ⇡ 3458/17 ⇡ 200+ categories scattered throughout the book.
Utilize this categorization feature for your training! Solving at least a few problems from
each category is a great way to diversify your problem solving skillset. For conciseness, we
have limited ourselves to a maximum of 4 UVa + 3 Kattis (or 3 UVa + 4 Kattis) = 7 starred
* (must try) problems per category and put the rest as extras (the hints for those extras
can be read online at ‘Methods to Solve’ page of https://cpbook.net). You can say that
you have ‘somewhat mastered’ CP4 if you have solved at least three (3) problems per
category (this will take some time).
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/Kattis problems, ordered by problem number/id (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 CP4, we allow
the hints to span more than one line (but not more than two lines) so that they can be a bit
more meaningful. Of course you can always challenge yourself by not reading the hints first.
xix
PREFACE c Steven, Felix, Suhendry
• Obviously, we have fixed all known typos, grammatical errors, and bugs that were
found and reported by CP3 readers since 2013. It does not mean that this edition is
100% free from any bug though. We strive to have only very few errors in CP4.
• We have updated many sample code into C++17, Java 11, Python 3, and even some
OCaml. Many of the sample code become simpler with a few more years of program-
ming language update (e.g., C++17 structured binding declaration), the upgraded cod-
ing skills/styles of the authors, and various interesting contributions from our readers
over these past few years.
• We have digitized all hints of the ⇡ 3458 problems that we have solved at https:
//cpbook.net/methodstosolve, including the extras that are not fully shown in the
printed version of this book to save space. The online version has search/filter feature
and will always be more up-to-date than the printed version as time goes on. The
750+ problems in Kattis online judge with the lowest points [1.1..3.5] as of 19 July
2020 have been solved by us and are discussed in this book.
• A few outdated problem categories have been adjusted/removed (e.g., Combining Max
1D/2D Range Sum, etc). A few/emerging problem categories have been opened (e.g.,
Pre-calculate-able, Try All Possible Answer(s), Fractions, NP-hard/complete, etc).
• To help our readers avoid the “needle in a haystack” issue, we usually select only top
4 UVa+3 Kattis (or top 3 UVa+4 Kattis), totalling 7 starred problems, per category.
This reduce clutter and will help new competitive programmer to prioritize their train-
ing time on the better quality practice problems. This also saves a few precious pages
that can be used to improve the actual content of the book.
2
Including 10 ICPC Asia Regional Wins in between the release of CP3 (2013) and CP4 (2020).
xx
PREFACE c Steven, Felix, Suhendry
• We have re-written almost every existing topic in the book to enhance their presen-
tation. We have integrated our freely accessible https://visualgo.net algorithm
visualization tool3 as far as possible into this book. Obviously, the content shown in
VisuAlgo will always be more up-to-date than the printed version as time goes on. All
these new additions may be subtle but may be very important to avoid TLE/WA in
the ever increasing difficulties of programming contest problems [17]. Many starred
exercises in CP3 that are now deemed to be ‘standard’ by year 2020 have been inte-
grated into the body text of this CP4 so do not be surprised to see a reduction of the
number of written exercises in some chapters.
3
VisuAlgo is built with modern web programming technologies, e.g., HTML5 SVG, canvas, CSS3,
JavaScript (jQuery, D3.js library), PHP (Laravel framework), MySQL, etc. It has e-Lecture mode for basic
explanations of various data structures and algorithms and Online Quiz mode to test basic understanding.
4
Note that the IOI syllabus is an evolving document that is updated yearly.
xxi
PREFACE c Steven, Felix, Suhendry
• Chapter 1 changes:
1. We add short writeups about the IOI and ICPC, the two important international
programming competitions that use material in this book (and beyond).
2. We include Python (3) as one of the supported programming languages in this
book, especially for easier, non runtime-critical problems, Big Integer, and/or
string processing problems. If you can save 5 minutes of coding time on your first
Accepted solution and your team eventually solves 8 problems in the problem set,
this is a saving of 8 ⇥ 5 = 40 total penalty minutes.
3. We add some OCaml implementations (it is not yet used in the IOI or ICPC).
4. We use up-to-date Competitive Programming techniques as of year 2020.
• Chapter 2 changes:
1. Throughout this data structure chapter, we add much closer integration with our
own freely accessible visualization tool: VisuAlgo.
2. We add Python (3) and OCaml libraries on top of C++ STL and Java API.
3. We significantly expand the discussion of Binary Heap, Hash Table, and (bal-
anced) Binary Search Tree in Non-linear Data Structures section that are typically
discussed in a “Data Structures and Algorithms” course.
xxii
PREFACE c Steven, Felix, Suhendry
4. We emphasize the usage of the faster Hash Tables (e.g., C++ unordered map)
instead of balanced BST (e.g., C++ map) if we do not need the ordering of keys
and the keys are basic data types like integers or strings. We also recommend the
simpler Direct Addressing Table (DAT) whenever it is applicable.
5. We highlight the usage of balanced BSTs as a powerful (but slightly slower)
Priority Queue and as another sorting tool (Tree Sort).
6. We discuss ways to deal with graphs that are not labeled with [0..V -1] and on
how to store some special graphs more efficiently.
7. We enhance the presentation of the UFDS data structure.
8. We add more features of Fenwick Tree data structure: Fenwick Tree as (a variant
of) order statistics data structure, Range Update Point Query variant, and Range
Update Range Query variant.
9. We add more feature of Segment Tree data structure: Range Update with Lazy
Propagation to maintain its O(log n) performance.
• Chapter 3 changes:
1. We add two additional complete search techniques: Pre-calculate all (or some)
answers and Try all possible answers (that cannot be binary-searched; or when the
possible answers range is small). We also update iterative bitmask implementation
to always use LSOne technique whenever possible. We also add more complete
search tips, e.g., data compression to make the problem amenable to complete
search techniques. We also tried Python for Complete Search problems. Although
Python will mostly get TLE for harder Complete Search problems, there are ways
to make Python usable for a few easier Complete Search problems.
2. We now favor implementation of Binary Search the Answer (BSTA) using for loop
instead of while loop. We also integrate Ternary Search in this chapter.
3. We now consider greedy (bipartite) matching as another classic greedy problem.
We add that some greedy algorithms use Priority Queue data structure to dy-
namically order the next candidates greedily.
4. We now use the O(n log k) LIS solution (‘patience sort’, not DP) as the de-
fault solution for modern LIS problem. We now use LSOne technique inside the
O(2n 1 ⇥ n2 ) DP-TSP solution to allow it to solve n [18..19] faster.
• Chapter 4 changes:
xxiii
PREFACE c Steven, Felix, Suhendry
• Chapter 5 changes:
1. We expand the discussion of this easy but big Ad Hoc Mathematics-related prob-
lems. We identify one more recurring Ad Hoc problems in Mathematics: Fraction.
2. We recognize the shift of trend where the number of pure Big Integer problems
is decreasing and the number of problems that require modular arithmetic is
increasing. Therefore, the discussion on modular arithmetic in Number Theory
section have been significantly expanded and presented earlier before being used
in latter sections, e.g., Fermat’s little theorem/modular multiplicative inverse
is used in the implementation of Binomial Coefficients and Catalan Numbers
in Combinatorics section, modular exponentiation is now the default in Matrix
Power section.
3. We expand the Combinatorics section with more review of counting techniques.
4. We expand the discussion of Probability-related problems.
5. We enhance the explanation of Floyd’s (Tortoise-Hare) cycle-finding algorithm
with VisuAlgo tool.
6. We integrate Matrix Power into this chapter, expanded the writeup about matrix
power, and integrate modular arithmetic techniques in this section.
• Chapter 6 changes:
• Chapter 7 changes:
1. We further enhance the existing library routines, e.g., (the shorter to code) An-
drew’s Monotone Chain algorithm is now the default convex hull algorithm, re-
placing (the slightly longer to code and a bit slower) Graham’s Scan.
2. We redo the explanation and add VisuAlgo screenshots of algorithms on Polygon.
• Chapter 8 changes:
1. We now set the faster O(V 2 ⇥ E) Dinic’s algorithm as the default algorithm,
replacing the slightly slower O(V ⇥ E 2 ) Edmonds-Karp algorithm. We also add
a few more network flow applications.
2. We expand the discussion of Graph Matching and its bipartite/non-bipartite +
unweighted/weighted variants. We augment the Augmenting Path algorithm with
the randomized greedy pre-processing step by default.
3. We add a few more problem decomposition related techniques and listed many
more such problems, ordered by their frequency of appearance.
xxiv
PREFACE c Steven, Felix, Suhendry
• Chapter 9 changes:
1. On top of enhancing previous writeups, we add more collection of new rare data
structures, algorithms, and/or programming problems that have not been listed
in the first eight chapters and did not appear in CP3. These new topics are:
(a) Square Root Decomposition,
(b) Heavy-Light Decomposition,
(c) Tree Isomorphism,
(d) De Bruijn Sequence,
(e) Fast Fourier Transform,
(f) Chinese Remainder Theorem,
(g) Lucas’ Theorem,
(h) Combinatorial Game Theory,
(i) Egg Dropping Puzzle,
(j) Dynamic Programming Optimization,
(k) Push-Relabel algorithm,
(l) Kuhn-Munkres algorithm,
(m) Edmonds’ Matching algorithm,
(n) Constructive Problem,
(o) Interactive Problem,
(p) Linear Programming,
(q) Gradient Descent.
• In summary, someone who only master CP3 (published back in 2013) content can be
easily beaten in a programming contest by someone who only master CP4 content
(published in year 2020).
Supporting Websites
This book has an official companion web site at https://cpbook.net. The Methods to
Solve tool is in this web site too.
We have also uploaded (almost) all source code discussed in this book in the public
GitHub repository of this book: https://github.com/stevenhalim/cpbook-code.
Since the third edition of this book, many data structures and algorithms discussed in
this book already have interactive visualizations at https://visualgo.net.
All UVa Online Judge programming exercises in this book have been integrated in the
https://uhunt.onlinejudge.org/ tool.
All Kattis Online Judge programming exercises in this book can be easily accessed using
the “Kattis Hint Giver” Google Chrome extension (created by Steven’s student Lin Si Jie)
that integrates the content of Methods to Solve directly to Kattis’s problems pages.
xxv
PREFACE c Steven, Felix, Suhendry
Copyright
In order to protect the intellectual property, no part of this book may be reproduced or
transmitted in any form or by any means, electronically or mechanically, including photo-
copying, scanning, uploading to any storage and retrieval system, without official permission
of the authors.
xxvi
Authors’ Profiles
5
PhD Thesis: “An Integrated White+Black Box Approach for Designing and Tuning Stochastic Local
Search Algorithms”, 2009.
xxvii
AUTHORS’ PROFILES c Steven, Felix, Suhendry
6
PhD Thesis: “Solving Big Data Problems: from Sequences to Tables and Graphs”, 2012.
7
PhD Thesis: “Graph Properties and Algorithms in Social Networks: Privacy, Sybil Attacks, and the
Computer Science Community”, 2017.
xxviii
Abbreviations
SA : Suffix Array
SPOJ : Sphere Online Judge
ST : Suffix Tree
STL : Standard Template Library
WA : Wrong Answer
WF : World Finals
xxx
Chapter 1
Introduction
An illustration: UVa Online Judge [44] Problem Number 10911 (Forming Quiz Teams).
Abridged Problem Description:
Let (x, y) be the integer coordinates of a student’s house on a 2D plane. There
are 2N students and we want to pair them into N groups. Let di be the distance
P
between the houses of 2 students in group i. Form N groups such that cost = Ni=1 di
is minimized. Output the minimum cost as a floating point number with 2 digits
precision in one line. Constraints: 1 N 8 and 0 x, y 1000.
Sample input (with explanation):
N = 2; Coordinates of the 2N = 4 houses are {1, 1}, {8, 6}, {6, 8}, and {1, 3}.
Sample output (with explanation):
cost = 4.83.
Can you solve this problem?
If so, how many minutes would you likely require to complete the working code?
Think and try not to flip this page immediately!
1
Some programming competitions are done in a team setting to encourage teamwork as software engineers
usually do not work alone in real life.
2
By hiding the actual test data from the problem statement, competitive programming encourages the
problem solvers to exercise their mental strength to think of many (if not all) possible corner cases of the
problem and test their programs with those cases. This is typical in real life where software engineers have
to test their software a lot to make sure that the software meets the requirements set by clients.
1
1.1. COMPETITIVE PROGRAMMING c Steven, Felix, Suhendry
Now ask yourself: Which of the following best describes you? Note that if you are
unclear with the material or the terminology shown in this chapter, you can re-read it
again after going through this book once.
• Uncompetitive programmer A (a.k.a. the blurry one):
Step 1: Reads the problem and becomes confused. (This problem is new for A).
Step 2: Tries to code something: Reading the non-trivial input and output.
Step 3: A realizes that these two ideas below are not Accepted (AC):
Greedy (Section 3.4): Repeatedly pairing the two remaining students with the
shortest separating distances gives the Wrong Answer (WA).
Naı̈ve Complete Search: Using recursive backtracking (Section 3.2) and trying
all possible pairings yields Time Limit Exceeded (TLE).
• Uncompetitive programmer B (Gives up):
Step 1: Reads the problem and realizes that it is a graph matching problem.
But B has not learned how to solve this kind of problem...
B is not aware of the Dynamic Programming (DP) solution (Section 3.5)...
Step 2: Skips the problem and reads another problem in the problem set.
• (Still) Uncompetitive programmer C (Slow):
Step 1: Reads the problem and realizes that it is a difficult problem: ‘minimum
weight perfect matching on a weighted complete graph’. However, since
the input size is small, this problem is solvable using DP. The DP state is a
bitmask that describes a matching status, and matching unmatched students i
and j will turn on two bits i and j in the bitmask (see Book 2).
Step 2: Codes I/O routine, writes recursive top-down DP, tests, debugs >.<...
Step 3: After 3 hours, C’s solution is AC (passed all the secret test data).
• Competitive programmer D:
Completes all the steps taken by uncompetitive programmer C in 30 minutes.
• Very competitive programmer E:
A very competitive programmer (e.g., the red coders in Codeforces [4]) would
solve this ‘well known’ problem in 10 minutes and possibly also aware of the
various other possible solutions for the (harder) variant(s) of this problem...
Please note that being well-versed in competitive programming is not the end goal, but only
a means to an end. The true end goal is to produce all-rounder computer scientists or pro-
grammers who are much readier to produce better software and to face harder CS research
problems in the future. This is one of the objectives of the International Olympiad in Infor-
matics (IOI) [31] and the vision of the founders of the International Collegiate Programming
Contest (ICPC) [57]. With this book, we play our little role in preparing the current and fu-
ture generations to be more competitive in dealing with well-known CS problems frequently
posed in the recent IOIs and ICPCs.
2
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
Exercise 1.1.1: The greedy strategy of the uncompetitive programmer A above actually
works for the sample test case shown in Figure 1.1 as typically good problem authors do not
put their corner cases as sample test cases. Please give a better counter example!
Exercise 1.1.2: Analyze the time complexity of the naı̈ve complete search solution by
uncompetitive programmer A above to understand why it receives the TLE verdict!
Exercise 1.1.3*: Actually, a clever recursive backtracking solution with pruning can still
solve this problem (with 1 N 8). Solve this problem without using a DP table!
3
1.2. THE COMPETITIONS c Steven, Felix, Suhendry
The International Scientific Committee (ISC) will strive to make the sum of subtask
points to be as diverse as possible to minimize ties7 (especially along medal boundaries). To
make IOI training in various national teams more manageable, the ISC maintains the IOI
syllabus [16].
Coding speed is usually not a di↵erentiating factor in IOI. One can submit a 100 points
(full) solution at time 4h59m and still be rewarded with the same 100 points compared to
one that submits 100 points solution at 30m. Thus IOI emphasizes peak performance, i.e.,
ability to solve the (harder) subtasks instead of how fast one can solve the (easier) subtasks8 .
Historically, to get a gold/silver/bronze medal, one should get 400+/300+/200+ points
(out of possible 600) after two contest days, respectively.
The main purpose of this book is to make the number of IOI participants scoring low total
points (under 70 points) after two contest days to be as low as possible. Not all subtasks in
IOI are hard as the ISC also needs to avoid demoralizing half of the contestants that will go
home without any medal. They are still future Computer Scientists after all.
What’s Next?
Many, but not all, of IOI medalists/alumni continue to study in the field of Computer
Science for their University degree9 . Many of them (but not all ) also join the next level
of Programming Contests: The ICPC (see the next subsection 1.2.2). Thus, if one already
knows this book from high school, he/she can use it throughout University too.
4
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
What’s Next?
Most competitive programmers will likely end their competition career after their last ICPC.
Good performance in ICPC during University days is probably a(n important) requirement
in order to excel in technical interviews in (top) IT companies.
11
Some ex-IOI contestants may need to improve their implementation speed for ICPC.
5
1.3. TIPS TO BE COMPETITIVE c Steven, Felix, Suhendry
6
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
As a little practice, try typing the C++ source code below as fast as possible16 :
int N; // max N = 8
double dist[20][20], memo[1<<16]; // 1<<16 = 2^16
int main() {
int caseNo = 0, x[20], y[20];
while (scanf("%d", &N), N) { // yes, we can do this :)
for (int i = 0; i < 2*N; ++i)
scanf("%*s %d %d", &x[i], &y[i]); // ‘%*s’ skips names
for (int i = 0; i < 2*N-1; ++i) // build distance table
for (int j = i+1; j < 2*N; ++j) // use ‘hypot’ function
dist[i][j] = dist[j][i] = hypot(x[i]-x[j], y[i]-y[j]);
for (int i = 0; i < (1<<16); ++i) memo[i] = -1.0;
printf("Case %d: %.2lf\n", ++caseNo, dp((1<<(2*N)) - 1));
}
return 0;
} // DP to solve min weighted perfect matching on small general graph
For your reference, the explanations of this ‘Dynamic Programming with bitmask’ solution
are gradually given in Section 2.2, 3.5, and later in Book 2. Do not be alarmed if you do not
understand it yet.
16
Notice that the typical Competitive Programming coding style actually violates many good Software
Engineering principles, e.g., over usage of global variables, usage of cryptic and incredibly short variable
names, inclusion of all available header files, over usage of bit manipulation, using namespace std, etc.
7
1.3. TIPS TO BE COMPETITIVE c Steven, Felix, Suhendry
17
In year 2009-2010, IOI had 8 tasks over 2 days with at least 1 (very) easy task per day. However, this
format is no longer continued in favor of eas(ier) subtask 1 of all tasks.
8
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
To be competitive, that is, do well in a programming contest, you must be able to confidently
and frequently classify problems as type A1 and minimize the number of problems that you
classify into type A2 or B. That is, you need to acquire sufficient algorithm knowledge and
develop your programming skills so that you consider many classical problems to be easy –
especially at the start of the contest.
However, to win a programming contest, you will also need to develop sharp problem
solving skills so that you (or your team) will be able to derive the required solution to a
hard/original type C problem in IOI or ICPC and do so within the duration of the contest,
not after the solution(s) is/are revealed by the problem author(s)/contest judge(s). Some of
the necessary problem solving skills are:
• Reducing the given problem into another (easier) problem,
• Reducing a known (NP-)hard problem into the given problem,
• Identifying subtle hints or special properties in the problem,
• Attacking the problem from a non-obvious angle/asking a di↵erent question,
• Compressing the input data,
• Reworking mathematical formulas,
• Listing observations/patterns,
• Performing case analysis of possible subcases of the problem, etc.
Exercise 1.3.2.1: Read the UVa [44] and Kattis [34] problems in Table 1.3 and determine
their problem types. One of them has been identified for you. Filling this table should be
easy after mastering this book as all the techniques required to solve these problems are
discussed in this book.
Exercise 1.3.2.2*: Using the same list of problems shown in Table 1.3 above, please provide
the abridged versions of those problems in at most three sentences, omitting the irrelevant
details/storyline, but preserving the key points of the problems in such a way that another
competitive programmer who does not read the original problem descriptions can still write
correct solutions for those problems. See the first page of this book for an example!
9
1.3. TIPS TO BE COMPETITIVE c Steven, Felix, Suhendry
10
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
• Basic time and space complexity analysis for iterative and recursive algorithms:
– An algorithm with k-nested loops of about n iterations each has O(nk ) complexity.
– If your algorithm is recursive with b recursive calls per level and has L levels, the
algorithm has roughly O(bL ) complexity, but this is a only a rough upper bound.
The actual complexity depends on what actions are done per level and whether
pruning is possible.
– A Dynamic Programming algorithm or other iterative routine which processes a
2D n ⇥ n matrix in O(k) per cell runs in O(k ⇥ n2 ) time. This is explained in
further detail in Section 3.5.
– Binary searching over a range of [1..n] has O(log n) complexity.
11
1.3. TIPS TO BE COMPETITIVE c Steven, Felix, Suhendry
Many novice programmers would skip this phase and immediately implement the first (naı̈ve)
algorithm that they can think of only to realize that the chosen data structure and/or
algorithm is/are not efficient enough (or wrong). Our advice for ICPC contestants22 : refrain
from coding until you are sure that your algorithm is both correct and fast enough.
To help you understand the growth of several common time complexities, and thus help
you judge how fast is ‘enough’, please refer to Table 1.4. Variants of such tables are also
found in many other books on data structures and algorithms. This table is written from
a programming contestant’s perspective. Usually, the input size constraints are given in a
(good) problem description. With the assumption that a typical year 2020 CPU can execute
a hundred million (108 ) operations in around 1 second23 (the typical time limit in most
UVa/Kattis problems [44, 34]), we can predict the ‘worst’ algorithm that can still pass the
time limit24 . Usually, the simplest algorithm has the poorest time complexity, but if it can
already pass the time limit, just use it!
Table 1.4: Rule of Thumb for the ‘Worst AC Algorithm’ for various single-test-case input
sizes n, assuming that a year 2020 CPU can compute 100M operations in 1 second.
From Table 1.4, we see the importance of using good algorithms with small orders of growth
as they allow us to solve problems with larger input sizes25 . But a faster algorithm is usually
non-trivial and sometimes substantially harder to implement. In Section 3.2.3, we discuss a
few tips that may allow the same class of algorithms to be used with larger input sizes. In
subsequent chapters, we also explain efficient algorithms for various computing problems.
22
Unlike ICPC, the IOI tasks can usually be solved (partially or fully) using several possible solutions,
each with di↵erent time complexities and subtask scores. To gain valuable points, it may be good to initialy
use a brute force solution to score a few points especially if it is easy/short to code and to understand the
problem better. There will be no significant time penalty as IOI is not a speed contest. Then, iteratively
improve the solution to gain more points.
23
In CP3, the previous assumption was 108 operations in 3s. Notice that CPU speed does not double
every one/two year(s) recently and Competitive Programming has not venture into multi-threading yet.
24
Try problem Kattis - tutorial *.
25
It will be hard for the programming contest judges to di↵erentiate fast or slow solutions automatically
when the highly variable I/O speed heavily influences the overall runtime speed measurements and hence
they will not set insanely large test cases (typically, n 1M ).
12
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
Exercise 1.3.3.1: Please answer the questions below using your current knowledge about
classic algorithms and their time complexities. After you have finished reading this book
once, it may be beneficial to attempt this exercise again.
1. There are n webpages (1 n 10M ). Page i has a page rank ri . A new page can
be added or an existing page can be removed frequently. You want to pick the current
top 10 pages with the highest page ranks, in order. Which method is better?
(a) Load all n webpages’ page rank to memory, sort (Section 2.2) them in descending
page rank order, and obtain the current top 10.
(b) Use a Priority Queue data structure (Section 2.3).
(c) Use the QuickSelect algorithm (Section 2.3.4).
2. Given a list L with 100K integers, you need to frequently obtain sum(i, j), i.e., the
sum of L[i] + L[i+1] + ...+ L[j]. Which data structure should you use?
(a) Simple Array pre-processed with Dynamic Programming (Section 2.2 & 3.5).
(b) Balanced Binary Search Tree (Section 2.3).
(c) Segment Tree (Section 2.4.4).
(d) Fenwick (Binary Indexed) Tree (Section 2.4.3).
(e) Suffix Tree or its alternative, Suffix Array (Book 2).
(a) Try all possible sub-matrices and check if the mean of each sub-matrix is 7.
This algorithm runs in O(M 3 ⇥ N 3 ).
(b) Try all possible sub-matrices, but in O(M 2 ⇥ N 2 ) with this technique: .
(a) Try all possible O(M 2 ) pairs of integers and insert their sums into a hash table
(O(1) per insertion). Finally, report the final size of the hash table.
(b) Perform an algorithm as above, but after performing this technique: .
5. You have to compute the shortest path between two vertices on a weighted Directed
Acyclic Graph (DAG) with |V |, |E| 100K. Which algorithm(s) can be used?
13
1.3. TIPS TO BE COMPETITIVE c Steven, Felix, Suhendry
6. Which algorithm produces a list of the first 10M prime numbers with the best time
complexity? (Book 2)
(a) Test if n! % m == 0.
(b) The naı̈ve approach above will not work, use: (Book 2).
10. See Question above, but now with a larger set of points: 2 N 200K and one
additional constraint: The points are randomly scattered on a 2D plane.
11. See the same Question above. We still have a set of 2 N 200K points. But this
time there is no guarantee that the points are randomly scattered on a 2D plane.
14
CHAPTER 1. INTRODUCTION c Steven, Felix, Suhendry
import math
print(math.factorial(40)) # all built-in
The Java code for this task is also simple (more details in Section 2.2.4):
import java.util.Scanner;
import java.math.BigInteger;
class Main { // default class name
public static void main(String[] args) {
BigInteger fac = BigInteger.ONE;
for (int i = 2; i <= 40; ++i)
fac = fac.multiply(BigInteger.valueOf(i)); // it is in the library!
System.out.println(fac);
}
}
Mastering and understanding the full capability of your favourite programming language is
also important. Take this problem with a non-standard input format: The first line of input
is an integer N . This is followed by N lines, each starting with the character ‘0’, followed
by a dot ‘.’, then followed by an unknown number of target digits (up to 100 digits), and
finally terminated with three dots ‘...’. Your task is to extract these target digits.
26
[This is a personal opinion]. In IOI 2019 competition rules, the programming languages allowed in IOI
are C++ and Java (two older programming languages: Pascal and C have been retired recently). The ICPC
World Finals 2019 (and thus most Regionals) allows C, C++, Java, and Python (partially) to be used in the
contest. Therefore, it seems that the ‘best’ language to master as of year 2020 is still C++ (std=gnu++17)
as it is supported in both competitions, a fast language, and has strong STL support. If IOI contestants
choose to master C++, they will have the benefit of being able to use the same language (with an increased
level of mastery) for ICPC in their University level pursuits. Note that OCaml is not currently used in the
IOI or ICPC.
15
Discovering Diverse Content Through
Random Scribd Documents
The Project Gutenberg eBook of Footprints of the
Red Men
This ebook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms of
the Project Gutenberg License included with this ebook or online at
www.gutenberg.org. If you are not located in the United States, you will
have to check the laws of the country where you are located before
using this eBook.
Language: English
Credits: Produced by Roger Burch with scans provided by the Internet Archive.
BY
E. M. RUTTENBER,
Author of "History of the Indian Tribes of Hudson's River."
"Indian place-names are not proper names, that is unmeaning words, but
significant appellatives each conveying a description of the locality to which it
belongs."—Trumbull.
OF THE
1906.
{INDEX p. 237}
Primary Explanations.
The locatives of the Indian geographical names which have been handed
down as the names of boundmarks or of places or tribes, are properly a subject
of study on the part of all who would be familiar with the aboriginal geography
of a district or a state. In many cases these names were quite as designative of
geographical centers as are the names of the towns, villages and cities which
have been substituted for them. In some cases they have been wisely retained,
while the specific places to which they belonged have been lost. In this work
special effort has been made, first, to ascertain the places to which the names
belonged as given in official records, to ascertain the physical features of those
places, and carry back the thought to the poetic period of our territorial history,
"when the original drapery in which nature was enveloped under the dominion
of the laws of vegetation, spread out in one vast, continuous interminable
forest," broken here and there by the opened patches of corn-lands and the
wigwams and villages of the redmen; secondly, to ascertain the meanings of the
aboriginal names, recognizing fully that, as Dr. Trumbull wrote, "They were not
proper names or mere unmeaning marks, but significant appellatives conveying
a description of the locatives to which they were given." Coming down to us in
the crude orthographies of traders and unlettered men, they are not readily
recognized in the orthographies of the educated missionaries, and especially are
they disguised by the varying powers of the German, the French, and the
English alphabets in which they were written by educated as well as by
uneducated scribes, and by traders who were certainly not very familiar with the
science of representing spoken sounds by letters. In one instance the same name
appears in forty-nine forms by different writers. Many names, however, have
been recognized under missionary standards and their meanings satisfactorily
ascertained, aided by the features of the localities to which they were applied;
the latter, indeed, contributing very largely to their interpretation. Probably the
reader will find geographical descriptions that do not apply to the places where
the name is now met. The early settlers made many transfers as well as
extensions of names from a specific place to a large district of country. It must
be remembered that original applications were specific to the places which they
described even though they were generic and applicable to any place where the
same features were referred to. The locatives in Indian deeds and original
patents are the only guide to places of original application, coupled with
descriptive features where they are known.
A considerable number of record names have been included that are not
living. They serve to illustrate the dialect spoken in the valley as handed down
by European scribes of different languages, as well as the local geography of the
Indians. The earlier forms are mainly Dutch notations. A few Dutch names that
are regarded by some as Indian, have been noticed, and also some Indian names
on the Delaware River which, from the associations of that river with the history
of the State, as in part one of its boundary streams, as well as the intimate
associations of the names with the history of the valley of Hudson's River,
become of especial interest.
Credit has been given for interpretations where the authors were known,
and especially to the late eminent Algonquian authority, J. Hammond Trumbull.
Special acknowledgment of valuable assistance is made to the late Dr. D. G.
Brinton, of Philadelphia; to the late Horatio Hale, M. A., of Clinton, Ontario,
Canada; to the late Prof. J. W. Powell, of the Bureau of Ethnology, Washington,
D. C, and his successor, William H. Holmes, and their co-laborers, Dr. Albert S.
Gatschet and J. B. N. Hewitt, and to Mr. William R. Gerard, of New York.
E. M. RUTTENBER.
[FN] Presumed to have been at what is now known as Scho-lac, which see.
Father Jogues, the French-Jesuit martyr-missionary, wrote in 1646, Oi-o-
gué as the Huron-Iroquoian name of the river, given to him at Sarachtoga, with
the connection "At the river." "Ohioge, river; Ohioge-son, at the long river,"
wrote Bruyas. Arent van Curler wrote the same name, in 1634, Vyoge, and gave
it as that of the Mohawk River, correcting the orthography, in his vocabulary, to
"Oyoghi, a kill" or channel. It is an Iroquoian generic applicable to any principal
stream or current river, with the ancient related meaning of "beautiful river."
It is said that the Mohawks called the river Cohohataton. I have not met
that name in records. It was quoted by Dr. Schoolcraft as traditional, and of
course doubtful. He wrote it Kohatatea, and in another connection wrote "-atea,
a valley or landscape." It is suspected that he coined the name, as he did many
others. Shate-muck is quoted as a Mohegan [FN-1] name, but on very obscure
evidence, although it may have been the name of an eel fishing-place, or a great
fishing-place (-amaug). Hudson called the stream "The River of the
Mountains." On some ancient maps it is called "Manhattans River." The Dutch
authorities christened it "Mauritus' River" in honor of their Staat-holder, Prince
Maurice. The English recognized the work of the explorer by conferring the title
"Hudson's River." It is a fact established that Verrazano visited New York harbor
in 1524, and gave to the river the name "Riviere Grande," or Great River; that
Estevan Gomez, a Spanish navigator who followed Verrazano in 1525, called it
"St. Anthony's River," a name now preserved as that of one of the hills of the
Highlands, and it is claimed that French traders visited the river, in 1540, and
established a château on Castle [FN-2] Island, at Albany, [FN-3] and called the
river "Norumbega." It may be conceded that possibly French traders did have a
post on Castle Island, but "Norumbega" was obviously conferred on a wide
district of country. It is an Abnaki term and belonged to the dialect spoken in
Maine, where it became more or less familiar to French traders as early as 1535.
That those traders did locate trading posts on the Penobscot, and that Champlain
searched for their remains in 1604, are facts of record. The name means "Quiet"
or "Still Water." It would probably be applicable to that section of Hudson's
River known as "Stillwater," north of Albany, but the evidence is wanted that it
was so applied. Had it been applied by the tribes to any place on Hudson's
River, it would have remained as certainly as Menaté remained at New York.
[FN-1] "Mohegans is an anglicism primarily applied to the small band of Pequots under
Uncas." (Trumbull.) While of the same linguistic stock, neither the name or the history of
Uncas's clan should be confused with that of the Mahicani of Hudson's River.
[FN-2] Introduced by the Dutch—Kasteel. The Indians had no such word. The Delawares
called a house or hut or a town that was palisaded, Moenach, and Zeisberger used the same
word for "fence"—an enclosure palisaded around. Eliot wrote Wonkonous, "fort."
[FN-3] It is claimed that the walls of this fort were found by Hendrick Christiansen, in
1614; that they were measured by him and found to cover an area of 58 feet; that the fort
was restored by the Dutch and occupied by them until they were driven out by a freshet,
occasioned by the breaking up of the ice in the river in the spring of 1617; that the Dutch
then built what was subsequently known as Fort Orange, at the mouth of the Tawalsentha,
or Norman's Kill, about two miles south of the present State street, Albany, and that Castle
Island took that name from the French château—all of which is possible, but for conclusive
reasons why it should not be credited, the student may consult "Norumbega" in Winsor's
"Narrative and Critical History of America." Wrote Dr. Trumbull: "Theuet, in La
Cosmographie Universella, gives an account of his visit, in 1656, to 'one of the finest rivers
in the whole world, which we call Norumbeque, and the aboriginees Agoncy,' now
Penobscot Bay."
Manhattan, now so written, does not appear in the Journal of Hudson's
exploration of the river in 1609. On a Spanish-English map of 1610, "Made for
James I," and sent to Philip III by Velasco in letter of March 22, 1611, [FN-1]
Mannahatin is written as the name of the east side of the river, and Mannahata
as that of the west side. From the former Manhattan, and from it also the name
of the Indians "among whom" the Dutch made settlement in 1623-4, otherwise
known by the general name of Wickquaskecks, as well as the name of the entire
Dutch possessions. [FN-2] Presumably the entries on the Spanish-English map
were copied from Hudson's chart, for which there was ample time after his
return to England. Possibly they may have been copied by Hudson, who wrote
that his voyage "had been suggested" by some "letters and maps" which "had
been sent to him" by Capt. Smith from Virginia. Evidently the notations are
English, and evidently, also, Hudson, or his mate, Juet, had a chart from his own
tracing or from that of a previous explorer, which he forwarded to his
employers, or of which they had a copy, when he wrote in his Journal: "On that
side of the river called Mannahata," as a reference by which his employers
could identify the side of the river on which the Half-Moon anchored, [FN-3]
Presumably the chart was drawn by Hudson and forwarded with his report, and
that to him belongs the honor of reducing to an orthographic form the first
aboriginal name of record on the river which now bears his name. Five years
after Hudson's advent Adriaen Block wrote Manhates as the name of what is
now New York Island, and later, De Vries wrote Manates as the name of Staten
Island, both forms having the same meaning, i. e., "Small island." There have
been several interpretations of Mannahatin, the most analytical and most
generally accepted being by the late Dr. J. H. Trumbull: "From Menatey (Del.),
'Island'—Mannahata 'The Island,' the reference being to the main land or to
Long Island as the large island. Menatan (Hudson's Mannah-atin, -an or -in, the
indefinite or diminutive form), 'The small island,' or the smaller of the two
principal islands, the Manhates of Adriaen Block. [FN-4] Manáhtons, 'People of
the Island,' Manáhatanesen, 'People of the small islands.'" [FN-5] The Eastern-
Algonquian word for "Island" (English notation), is written Munnoh, with
formative -an (Mun-nohan). It appears of record, occasionally, in the vicinity of
New York, presumably introduced by interpreters or English scribes. The usual
form is the Lenape Menaté, Chippeway Minnis, "Small island," classed also as
Old Algonquian, or generic, may be met in the valley of the Hudson, but the
instances are not clear. It is simply a dialectic equivalent of Del. Ménates. (See
Monach'nong.) Van Curler wrote in his Mohawk vocabulary (1635), "Kanon-
newaga, Manhattan Island." The late J. W. Powell, Director of the Bureau of
Ethnology, wrote me: "In the alphabet of this office the name may be
transliterated Kanoñnò'ge. It signifies 'Place of Reeds.'" Perhaps what was
known as the "Reed Valley" was referred to, near which Van Twiller had a
tobacco plantation where the Indians of all nations came to trade. (See
Saponickan.) The lower part of the island was probably more or less a district of
reed swamps.
[FN-1] Brown's "Genesis of the United States," 327, 457, 459, ii, 80.
[FN-3] Hudson anchored in the bay near Hoboken. Near by his anchorage he noticed that
"there was a cliff that looked of the color of white green." This cliff is near Elysian Fields
at Hoboken. (Broadhead.) The cliff is now known as Castle Point.
[FN-4] The reference to Adriaen Block is presumably to the "Carte Figurative" of 1614-16,
now regarded as from Block's chart.
[FN] Denton's "Description of New York," p. 29. Ward's and Blackwell's islands were sold
to the Dutch by the Marechawicks, of Long Island, in 1636-7. Governor's Island was sold
in the same year by the Tappans, Hackinsacks and Nyacks, the grantors signing themselves
as "hereditary owners." Later deeds were signed by chiefs of the Raritans and Hackinsacks.
Minnisais is not a record name. It was conferred on Bedloe's Island by Dr.
Schoolcraft from the Ojibwe or Chippeway dialect, [FN] in which it means
"Small island."
[FN] The Objibwe (Objibwai) were a nation of three tribes living northwest of the great
lakes, of which the Ojibwai or Chippeway represented the Eagle totem. It is claimed by
some writers that their language stands at the head of the Algonquian tongues. This claim is
disputed on behalf of the Cree, the Shawanoe, and the Lenape or Delaware. It is not
assumed that Ojibwe (Chippeway) terms are not Algonquian, but that they do not strictly
belong to the dialects of the Hudson's river families. Rev. Heckewelder saw no particular
difference between the Ojibwe and the Lenape except in the French and the English forms.
Ojibwe terms may always be quoted in explanations of the Lenape.
[FN] The Dutch called the island Onvruchtbaar, "Unfruitful, barren." The English adopted
the signification, "Barren," which soon became corrupted to "Barrent's," to which was
added "Great" to distinguish it from Randal's Island, which was called "Little Barrent's
Island." Barn Island is another corruption. Both islands were "barren" no doubt.