Competitive Programming In Python 128 Algorithms To Develop Your Coding Skills 1st Edition Christoph Drr pdf download
Competitive Programming In Python 128 Algorithms To Develop Your Coding Skills 1st Edition Christoph Drr pdf download
https://ebookbell.com/product/competitive-programming-in-
python-128-algorithms-to-develop-your-coding-skills-1st-edition-
christoph-drr-22000366
https://ebookbell.com/product/competitive-programming-4-the-lower-
bound-of-programming-contests-in-the-2020s-4th-edition-steven-
halim-46503294
https://ebookbell.com/product/competitive-programming-4-the-lower-
bound-of-programming-contests-in-the-2020s-4th-edition-steven-
halim-46503296
https://ebookbell.com/product/competitive-programming-3-the-new-lower-
bound-of-programming-contests-3rd-steven-halim-10205022
https://ebookbell.com/product/competitive-programming-guide-learning-
and-enhancing-algorithms-with-contests-bharat-mishra-55749594
Competitive Programming 4 Book 1 4th Steven Halim Felix Halim
https://ebookbell.com/product/competitive-programming-4-book-1-4th-
steven-halim-felix-halim-46668790
https://ebookbell.com/product/competitive-programming-4-book-2-4th-
steven-halim-felix-halim-46668794
https://ebookbell.com/product/competitive-programming-4-book-1-4th-
edition-steven-halim-felix-halim-46829276
https://ebookbell.com/product/competitive-programming-4-book-2-4th-
edition-steven-halim-felix-halim-46829310
https://ebookbell.com/product/competitive-programming-4-4th-steven-
halim-felix-halim-suhendry-effendy-48055044
Competitive Programming in Python
Want to kill it at your job interview in the tech industry? Want to win that coding
competition? Learn all the algorithmic techniques and programming skills you need
from two experienced coaches, problem-setters, and judges for coding competitions.
The authors highlight the versatility of each algorithm by considering a variety of
problems and show how to implement algorithms in simple and efficient code. What
to expect:
* Master 128 algorithms in Python.
* Discover the right way to tackle a problem and quickly implement a solution of low
complexity.
* Understand classic problems like Dijkstra’s shortest path algorithm and
Knuth–Morris–Pratt’s string matching algorithm, plus lesser-known data structures
like Fenwick trees and Knuth’s dancing links.
* Develop a framework to tackle algorithmic problem solving, including: Definition,
Complexity, Applications, Algorithm, Key Information, Implementation, Variants,
In Practice, and Problems.
* Python code included in the book and on the companion website.
Christoph Dürr is a senior researcher at the French National Center for Scientific
Research (CNRS), affiliated with the Sorbonne University in Paris. After a PhD in
1996 at Paris-Sud University, he worked for one year as a postdoctoral researcher at
the International Computer Science Institute in Berkeley and one year in the School
of Computer Science and Engineering in the Hebrew University of Jerusalem in
Israel. He has worked in the fields of quantum computation, discrete tomography and
algorithmic game theory, and his current research activity focuses on algorithms and
optimisation. From 2007 to 2014, he taught a preparation course for programming
contests at the engineering school École Polytechnique, and acts regularly as a
problem setter, trainer, or competitor for various coding competitions. In addition, he
loves carrot cake.
CHRISTOPH DÜRR
CNRS, Sorbonne University
JILL-JÊNN VIE
Inria
www.cambridge.org
Information on this title: www.cambridge.org/9781108716826
DOI: 10.1017/9781108591928
© Cambridge University Press 2021
Translation from the French language edition:
Programmation efficace - 128 algorithmes qu’il faut avoir compris et codés en Python au cour de sa vie
By Christoph Dürr & Jill-Jênn Vie
Copyright © 2016 Edition Marketing S.A.
www.editions-ellipses.fr
All Rights Reserved
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2021
Printed in the United Kingdom by TJ Books Limited, Padstow Cornwall
A catalogue record for this publication is available from the British Library.
Library of Congress Cataloging-in-Publication Data
Names: Dürr, Christoph, 1969– author. | Vie, Jill-Jênn, 1990– author. |
Gibbons, Greg, translator. | Gibbons, Danièle, translator.
Title: Competitive programming in Python : 128 algorithms to develop your
coding skills / Christoph Dürr, Jill-Jênn Vie ; translated by Greg
Gibbons, Danièle Gibbons.
Other titles: Programmation efficace. English
Description: First edition. | New York : Cambridge University Press, 2020.
| Includes bibliographical references and index.
Identifiers: LCCN 2020022774 (print) | LCCN 2020022775 (ebook) |
ISBN 9781108716826 (paperback) | ISBN 9781108591928 (epub)
Subjects: LCSH: Python (Computer program language) | Algorithms.
Classification: LCC QA76.73.P98 D8713 2020 (print) | LCC QA76.73.P98
(ebook) | DDC 005.13/3–dc23
LC record available at https://lccn.loc.gov/2020022774
LC ebook record available at https://lccn.loc.gov/2020022775
ISBN 978-1-108-71682-6 Paperback
Cambridge University Press has no responsibility for the persistence or accuracy of
URLs for external or third-party internet websites referred to in this publication
and does not guarantee that any content on such websites is, or will remain,
accurate or appropriate.
Contents
Preface page ix
1 Introduction 1
1.1 Programming Competitions 1
1.2 Python in a Few Words 5
1.3 Input-Output 13
1.4 Complexity 17
1.5 Abstract Types and Essential Data Structures 20
1.6 Techniques 28
1.7 Advice 37
1.8 A Problem: ‘Frosting on the Cake’ 39
2 Character Strings 42
2.1 Anagrams 42
2.2 T9—Text on 9 Keys 43
2.3 Spell Checking with a Lexicographic Tree 46
2.4 Searching for Patterns 48
2.5 Maximal Boundaries—Knuth–Morris–Pratt 49
2.6 Pattern Matching—Rabin–Karp 56
2.7 Longest Palindrome of a String—Manacher 59
3 Sequences 62
3.1 Shortest Path in a Grid 62
3.2 The Levenshtein Edit Distance 63
3.3 Longest Common Subsequence 65
3.4 Longest Increasing Subsequence 68
3.5 Winning Strategy in a Two-Player Game 70
4 Arrays 72
4.1 Merge of Sorted Lists 73
4.2 Sum Over a Range 74
4.3 Duplicates in a Range 74
4.4 Maximum Subarray Sum 75
vi Contents
5 Intervals 82
5.1 Interval Trees 82
5.2 Union of Intervals 85
5.3 The Interval Point Cover Problem 85
6 Graphs 88
6.1 Encoding in Python 88
6.2 Implicit Graphs 90
6.3 Depth-First Search—DFS 91
6.4 Breadth-First Search—BFS 93
6.5 Connected Components 94
6.6 Biconnected Components 97
6.7 Topological Sort 102
6.8 Strongly Connected Components 105
6.9 2-Satisfiability 110
10 Trees 171
10.1 Huffman Coding 172
10.2 Lowest Common Ancestor 174
10.3 Longest Path in a Tree 178
10.4 Minimum Weight Spanning Tree—Kruskal 179
11 Sets 182
11.1 The Knapsack Problem 182
11.2 Making Change 184
11.3 Subset Sum 185
11.4 The k-sum Problem 187
13 Rectangles 200
13.1 Forming Rectangles 200
13.2 Largest Square in a Grid 201
13.3 Largest Rectangle in a Histogram 202
13.4 Largest Rectangle in a Grid 204
13.5 Union of Rectangles 205
13.6 Union of Disjoint Rectangles 212
16 Conclusion 245
16.1 Combine Algorithms to Solve a Problem 245
16.2 For Further Reading 245
16.3 Rendez-vous on tryalgo.org 246
material of this text. Thanks to all those who proofread the manuscript, especially
René Adad, Evripidis Bampis, Binh-Minh Bui-Xuan, Stéphane Henriot, Lê Thành
Dũng Nguyễn, Alexandre Nolin and Antoine Pietri. Thanks to all those who improved
the programs on GitHub: Louis Abraham, Lilian Besson, Ryan Lahfa, Olivier Marty,
Samuel Tardieu and Xavier Carcelle. One of the authors would especially like to thank
his past teacher at the Lycée Thiers, Monsieur Yves Lemaire, for having introduced
him to the admirable gem of Section 2.5 on page 52.
We hope that the reader will pass many long hours tackling algorithmic problems
that at first glance appear insurmountable, and in the end feel the profound joy when
a solution, especially an elegant solution, suddenly becomes apparent.
Finally, we would like to thank Danièle and Greg Gibbons for their translation of
this work, even of this very phrase.
Attention, it’s all systems go!
1 Introduction
You, my young friend, are going to learn to program the algorithms of this book,
and then go on to win programming contests, sparkle during your job interviews,
and finally roll up your sleeves, get to work, and greatly improve the gross national
product!
Mistakenly, computer scientists are still often considered the magicians of modern
times. Computers have slowly crept into our businesses, our homes and our machines,
and have become important enablers in the functioning of our world. However, there
are many that use these devices without really mastering them, and hence, they do not
fully enjoy their benefits. Knowing how to program provides the ability to fully exploit
their potential to solve problems in an efficient manner. Algorithms and programming
techniques have become a necessary background for many professions. Their mastery
allows the development of creative and efficient computer-based solutions to problems
encountered every day.
This text presents a variety of algorithmic techniques to solve a number of classic
problems. It describes practical situations where these problems arise, and presents
simple implementations written in the programming language Python. Correctly
implementing an algorithm is not always easy: there are numerous traps to avoid and
techniques to apply to guarantee the announced running times. The examples in the
text are embellished with explanations of important implementation details which
must be respected.
For the last several decades, programming competitions have sprung up at every
level all over the world, in order to promote a broad culture of algorithms. The prob-
lems proposed in these contests are often variants of classic algorithmic problems,
presented as frustrating enigmas that will never let you give up until you solve them!
a web interface, where it is compiled and tested against instances hidden from the
public. For some problems the code is called for each instance, whereas for others the
input begins with an integer indicating the number of instances occurring in the input.
In the latter case, the program must then loop over each instance, solve it and display
the results. A submission is accepted if it gives correct results in a limited time, on the
order of a few seconds.
Figure 1.1 The logo of the ICPC nicely shows the steps in the resolution of a problem.
A helium balloon is presented to the team for each problem solved.
To give here a list of all the programming competitions and training sites is quite
impossible, and such a list would quickly become obsolete. Nevertheless, we will
review some of the most important ones.
ICPC The oldest of these competitions was founded by the Association for
Computing Machinery in 1977 and supported by them up until 2017. This
contest, known as the ICPC, for International Collegiate Programming Contest,
is organised in the form of a tournament. The starting point is one of the regional
competitions, such as the South-West European Regional Contest (SWERC),
where the two best teams qualify for the worldwide final. The particularity of
this contest is that each three-person team has only a single computer at their
disposal. They have only 5 hours to solve a maximum number of problems
among the 10 proposed. The first ranking criterion is the number of submitted
solutions accepted (i.e. tested successfully against a set of unknown instances).
The next criterion is the sum over the submitted problems of the time between
the start of the contest and the moment of the accepted submission. For each
erroneous submission, a penalty of 20 minutes is added.
There are several competing theories on what the ideal composition of a
team is. In general, a good programmer and someone familiar with algorithms
is required, along with a specialist in different domains such as graph theory,
dynamic programming, etc. And, of course, the team members need to get along
together, even in stressful situations!
For the contest, each team can bring 25 pages of reference code printed in an
8-point font. They can also access the online documentation of the Java API and
the C++ standard library.
Google Code Jam In contrast with the ICPC contest, which is limited to students
up to a Master’s level, the Google Code Jam is open to everyone. This more
recent annual competition is for individual contestants. Each problem comes in
1.1 Programming Competitions 3
general with a deck of small instances whose resolution wins a few points, and
a set of enormous instances for which it is truly important to find a solution
with the appropriate algorithmic complexity. The contestants are informed of
the acceptance of their solution for the large instances only at the end of the
contest. However, its true strong point is the possibility to access the solutions
submitted by all of the participants, which is extremely instructive.
The competition Facebook Hacker Cup is of a similar nature.
Prologin The French association Prologin organises each year a competition
targeted at students up to twenty years old. Their capability to solve algorithmic
problems is put to test in three stages: an online selection, then regional
competitions and concluding with a national final. The final is atypically an
endurance test of 36 hours, during which the participants are confronted with a
problem in Artificial Intelligence. Each candidate must program a “champion”
to play a game whose rules are defined by the organisers. At the end of the
day, the champions are thrown in the ring against each other in a tournament to
determine the final winner.
The website https://prologin.org includes complete archives of past
problems, with the ability to submit algorithms online to test the solutions.
France-IOI Each year, the organisation France-IOI prepares junior and senior
high school students for the International Olympiad in Informatics. Since
2011, they have organised the ‘Castor Informatique’ competition, addressed at
students from Grade 4 to Grade 12 (675,000 participants in 2018). Their website
http://france-ioi.org hosts a large number of algorithmic problems (more
than 1,000).
Chinese online judges Several training sites now exist in China. They tend to
have a purer and more refined interface than the traditional judges. Nevertheless,
sporadic failures have been observed.
poj http://poj.org
tju http://acm.tju.edu.cn (Shut down since 2017)
zju http://acm.zju.edu.cn
Modern online judges Sphere Online Judge http://spoj.com and Kattis
http://open.kattis.com have the advantage of accepting the submission
of solutions in a variety of languages, including Python.
spoj http://spoj.com
kattis http://open.kattis.com
zju http://acm.zju.edu.cn
Other sites
codechef http://codechef.com
codility http://codility.com
gcj http://code.google.com/codejam
prologin http://prologin.org
slpc http://cs.stanford.edu/group/acm
Throughout this text, problems are proposed at the end of each section in rela-
tion to the topic presented. They are accompanied with their identifiers to a judge
site; for example [spoj:CMPLS] refers to the problem ‘Complete the Sequence!’ at
the URL www.spoj.com/problems/CMPLS/. The site http://tryalgo.org contains
links to all of these problems. The reader thus has the possibility to put into practice
the algorithms described in this book, testing an implementation against an online
judge.
The languages used for programming competitions are principally C++ and Java.
The SPOJ judge also accepts Python, while the Google Code Jam contest accepts
many of the most common languages. To compensate for the differences in execution
speed due to the choice of language, the online judges generally adapt the time limit
to the language used. However, this adaptation is not always done carefully, and it is
sometimes difficult to have a solution in Python accepted, even if it is correctly written.
We hope that this situation will be improved in the years to come. Also, certain judges
work with an ancient version of Java, in which such useful classes as Scanner are
not available.
Accepted Your program provides the correct output in the allotted time. Congrat-
ulations!
Presentation Error Your program is almost accepted, but the output contains
extraneous or missing blanks or end-of-lines. This message occurs rarely.
Compilation Error The compilation of your program generates errors. Often,
clicking on this message will provide the nature of the error. Be sure to compare
the version of the compiler used by the judge with your own.
Wrong Answer Re-read the problem statement, a detail must have been over-
looked. Are you sure to have tested all the limit cases? Might you have left
debugging statements in your code?
Time Limit Exceeded You have probably not implemented the most efficient
algorithm for this problem, or perhaps have an infinite loop somewhere. Test
your loop invariants to ensure loop termination. Generate a large input instance
and test locally the performance of your code.
Runtime Error In general, this could be a division by zero, an access beyond the
limits of an array, or a pop() on an empty stack. However, other situations can
also generate this message, such as the use of assert in Java, which is often not
accepted.
The taciturn behaviour of the judges nevertheless allows certain information to be
gleaned from the instances. Here is a trick that was used during an ICPC / SWERC
contest. In a problem concerning graphs, the statement indicated that the input con-
sisted of connected graphs. One of the teams doubted this, and wrote a connectivity
test. In the positive case, the program entered into an infinite loop, while in the negative
case, it caused a division by zero. The error code generated by the judge (Time Limit
Exceeded ou Runtime Error) allowed the team to detect that certain graphs in the input
were not connected.
The programming language Python was chosen for this book, for its readability and
ease of use. In September 2017, Python was identified by the website https://
stackoverflow.com as the programming language with the greatest growth in high-
income countries, in terms of the number of questions seen on the website, notably
thanks to the popularity of machine learning.1 Python is also the language retained
for such important projects as the formal calculation system SageMath, whose critical
portions are nonetheless implemented in more efficient languages such as C++ or C.
Here are a few details on this language. This chapter is a short introduction to
Python and does not claim to be exhaustive or very formal. For the neophyte reader
we recommend the site python.org, which contains a high-quality introduction as
well as exceptional documentation. A reader already familiar with Python can profit
1 https://stackoverflow.blog/2017/09/06/incredible-growth-python/
6 Introduction
enormously by studying the programs of David Eppstein, which are very elegant and
highly readable. Search for the keywords Eppstein PADS.
Python is an interpreted language. Variable types do not have to be declared, they
are simply inferred at the time of assignment. There are neither keywords begin/end
nor brackets to group instructions, for example in the blocks of a function or a loop.
The organisation in blocks is simply based on indentation! A typical error, difficult
to identify, is an erroneous indentation due to spaces used in some lines and tabs
in others.
Data Structures
The principal complex data structures are dictionaries, sets, lists and n-tuples. These
structures are called containers, as they contain several objects in a structured manner.
Once again, there are functions dict, set, list and tuple that allow the conversion of
an object into one of these structures. For example, for a string s, the function list(s)
returns a list L composed of the characters of the string. We could then, for example,
replace certain elements of the list L and then recreate a string by concatenating the ele-
ments of L with the expression ‘’.join(L). Here, the empty string could be replaced
by a separator: for example, ‘-’.join([’A’,’B’,’C’]) returns the string “A-B-C”.
Lists The indices of a list start with 0. The last element can also be accessed with
the index −1, the second last with −2 and so on. Here are some examples of
operations to extract elements or sublists of a list. This mechanism is known as
slicing, and is also available for strings.
1.2 Python in a Few Words 7
A loop in Python is written either with the keyword for or with while. The nota-
tion for the loop for is for x in S:, where the variable x successively takes on the
values of the container S, or of the keys of S in the case of a dictionary. In contrast,
while L: will loop as long as the list L is non-empty. Here, an implicit conversion of
a list to a Boolean is made, with the convention that only the empty list converts to
False.
At times, it is necessary to handle at the same time the values of a list along with
their positions (indices) within the list. This can be implemented as follows:
For a dictionary, the following loop iterates simultaneously over the keys and
values:
>>> n = 5
>>> squared_numbers = [x ** 2 for x in range(n + 1)]
>>> squared_numbers
[0, 1, 4, 9, 16, 25]
nb_occurrences = {}
for letter in my_string:
nb_occurrences[letter] = 0
range(k, n) from k to n − 1
range(k, n, 2) from k to n − 1 two by two
range(n - 1, -1, -1) from n − 1 to 0 (−1 excluded) in decreasing order.
def all_pairs(L):
n = len(L)
for i in range(n):
for j in range(i + 1, n):
yield (L[i], L[j])
math This module contains mathematical functions and constants such as log,
sqrt, pi, etc. Python operates on integers with arbitrary precision, thus there
is no limit on their size. As a consequence, there is no integer equivalent to
represent −∞ or +∞. For floating point numbers on the other hand, float(’-
inf’) and float(’inf’) can be used. Beginning with Python 3.5, math.inf (or
from math import inf) is equivalent to float(’inf’).
fractions This module exports the class Fraction, which allows computations
with fractions without the loss of precision of floating point calculations. For
example, if f is an instance of the class Fraction, then str(f) returns a string
similar to the form “3/2”, expressing f as an irreducible fraction.
bisect Provides binary (dichotomous) search functions on a sorted list.
heapq Provides functions to manipulate a list as a heap, thus allowing an element
to be added or the smallest element removed in time logarithmic in the size of
the heap; see Section 1.5.4 on page 22.
string This module provides, for example, the function ascii_lowercase, which
returns its argument converted to lowercase characters. Note that the strings
themselves already provide numerous useful methods, such as strip, which
removes whitespace from the beginning and end of a string and returns the
result, lower, which converts all the characters to lowercase, and especially
split, which detects the substrings separated by spaces (or by another separa-
tor passed as an argument). For example, “12/OCT/2018”.split(“/”) returns
[“12”, “OCT”, “2018”].
Packages
One of the strengths of Python is the existence of a large variety of code packages.
Some are part of the standard installation of the language, while others must be
imported with the shell command pip. They are indexed and documented at the web
site pypi.org. Here is a non-exhaustive list of very useful packages.
tryalgo All the code of the present book is available in a package called tryalgo
and can be imported in the following manner: pip install tryalgo.
collections To simplify life, the class from collections import Counter can
be used. For an object c of this class, the expression c[x] will return 0 if x is not
1.2 Python in a Few Words 11
a key in c. Only modification of the value associated with x will create an entry
in c, such as, for example, when executing the instruction c[x] += 1. This is
thus slightly more practical than a dictionary, as is illustrated below.
>>> c = {} # dictionary
>>> c[’a’] += 1 # the key does not exist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: ’a’
>>> c[’a’] = 1
>>> c[’a’] += 1 # now it does
>>> c
{’a’: 2}
>>> from collections import Counter
>>> c = Counter()
>>> c[’a’] += 1 # the key does not exist, so it is created
Counter({’a’: 1})
>>> c = Counter(’cowboy bebop’)
Counter({’o’: 3, ’b’: 3, ’c’: 1, ’w’: 1, ’y’: 1, ’ ’: 1, ’e’: 1, ’p’: 1})
The collections package also provides the class deque, for double-ended
queue, see Section 1.5.3 on page 21. With this structure, elements can be added
or removed either from the left (head) or from the right (tail) of the queue. This
helps implement Dijkstra’s algorithm in the case where the edges have only
weights 0 or 1, see Section 8.2 on page 126.
This package also provides the class defaultdict, which is a dictionary that
assigns default values to keys that are yet in the dictionary, hence a generalisa-
tion of the class Counter.
See also Section 1.3 on page 13 for an example of reading a graph given as
input.
numpy This package provides general tools for numerical calculations involving
manipulations of large matrices. For example, numpy.linalg.solve solves
a linear system, while numpy.fft.fft calculates a (fast) discrete Fourier
transform.
While writing the code of this book, we have followed the norm PEP8, which
provides precise recommendations on the usage of blanks, the choice of names for
variables, etc. We advise the readers to also follow these indications, using, for exam-
ple, the tool pycodestyle to validate the structure of their code.
12 Introduction
A = [1, 2, 3]
B = A # Beware! Both variables refer to the same object
A = [1, 2, 3]
B = A[:] # B becomes a distinct copy of A
The notation [:] can be used to make a copy of a list. It is also possible to make a
copy of all but the first element, A[1 :], or all but the last element, A[: −1], or even
in reverse order A[:: −1]. For example, the following code creates a matrix M, all of
whose rows are the same, and the modification of M[0][0] modifies the whole of the
first column of M.
A square matrix can be correctly initialised using one of the following expressions:
The module numpy permits easy manipulations of matrices; however, we have cho-
sen not to profit from it in this text, in order to have generic code that is easy to translate
to Java or C++.
Ranges
Another typical error concerns the use of the function range. For example, the follow-
ing code processes the elements of a list A between the indices 0 and 9 inclusive, in
order.
To process the elements in descending order, it is not sufficient to just swap the
arguments. In fact, range(10, 0, -1)—the third argument indicates the step—is the
list of elements with indices 10 (included) to 0 (excluded). Thus the loop must be
written as:
1.3 Input-Output
If you wish to save the output of your program to a file called test.out, type:
A little hint: if you want to display the output at the same time as it is being written
to a file test.out, use the following (the command tee is not present by default in
Windows):
The inputs can be read line by line via the command input(), which returns the
next input line in the form of a string, excluding the end-of-line characters.3 The
module sys contains a similar function stdin.readline(), which does not suppress
the end-of-line characters, but according to our experience has the advantage of being
four times as fast!
If the input line is meant to contain an integer, we can convert the string with the
function int (if it is a floating point number, then we must use float instead). In
the case of a line containing several integers separated by spaces, the string can first be
cut into different substrings using split(); these can then be converted into integers
with the method map. For example, in the case of two integers height and width to be
read on the same line, separated by a space, the following command suffices:
import sys
If your program exhibits performance problems while reading the inputs, our expe-
rience shows that a factor of two can be gained by reading the whole of the inputs with
a single system call. The following code fragment assumes that the inputs are made
up of only integers, eventually on multiple lines. The parameter 0 in the function
os.read means that the read is from standard input, and the constant M must be an
upper bound on the size of the file. For example, if the file contains 107 integers,
each between 0 and 109 , then as each integer is written with at most 10 characters
and there are at most 2 characters separating the integers (\n and \r), we can choose
M = 12 · 107 .
3 According to the operating system, the end-of-line is indicated by the characters \r, \n, or both, but this
is not important when reading with input(). Note that in Python 2 the behaviour of input() is
different, so it is necessary to use the equivalent function raw_input().
1.3 Input-Output 15
import os
3
paris tokyo 9471
paris new-york 5545
new-york singapore 15344
nb_edges = int(input())
g = defaultdict(dict)
for _ in range(nb_edges):
u, v, weight = input().split()
g[u][v] = int(weight)
# g[v][u] = int(weight) # For an undirected graph
def readint():
return int(stdin.readline())
def readarray(typ):
return list(map(typ, stdin.readline().split()))
def readmatrix(n):
M = []
for _ in range(n):
row = readarray(int)
assert len(row) == n
M.append(row)
return M
if __name__ == "__main__":
n = readint()
A = readmatrix(n)
B = readmatrix(n)
C = readmatrix(n)
print(freivalds(A, B, C))
Note the test on the variable __name__. This test is evaluated as True if the file
containing this code is called directly, and as False if the file is included with the
import keyword.
Problem
Enormous Input Test [spoj:INTEST]
To display numbers with fixed precision and length, there are at least two pos-
sibilities in Python. First of all, there is the operator % that works like the func-
tion printf in the language C. The syntax is s % a, where s is a format string, a
character string including typed display indicators beginning with %, and where a
consists of one or more arguments that will replace the display indicators in the format
string.
>>> i_test = 1
>>> answer = 1.2142
>>> print("Case #%d: %.2f gigawatts!!!" % (i_test, answer))
Case #1: 1.21 gigawatts!!!
The letter d after the % indicates that the first argument should be interpreted as an
integer and inserted in place of the %d in the format string. Similarly, the letter f is
used for floats and s for strings. A percentage can be displayed by indicating %% in
the format string. Between the character % and the letter indicating the type, further
numerical indications can be given. For example, %.2f indicates that up to two digits
should be displayed after the decimal point.
Another possibility is to use the method format of a string, which follows the
syntax of the language C#. This method provides more formatting possibilities and
is in general easier to manipulate.
Finally, beginning with Python 3.6, f-strings, or formatted string literals, exist.
In this case, the floating point precision itself can be a variable, and the formatting
is embedded with each argument.
>>> precision = 2
>>> print(f"Case #{testCase}: {answer:.{precision}f} gigawatts!!!")
Case #1: 1.21 gigawatts!!!
1.4 Complexity
Landau Symbols
The complexity of an algorithm is, for example, said to be O(n2 ) if the execution time
can be bounded above by a quadratic function in n, where n represents the size or some
parameter of the input. More precisely, for two functions f ,g we denote f ∈ O(g)
if positive constants n0,c exist, such that for every n ≥ n0 , f (n) ≤ c · g(n). By an
abuse of notation, we also write f = O(g). This notation allows us to ignore the
multiplicative and additive constants in a function f and brings out the magnitude and
form of the dependence on a parameter.
Similarly, if for constants n0,c > 0 we have f (n) ≥ c · g(n) for every n ≥ n0 , then
we write f ∈ (g). If f ∈ O(g) and f ∈ (g), then we write f ∈ (g), indicating
that f and g have the same order of magnitude of complexity. Finally, if f ∈ O(g)
but not g ∈ O(f ), then we write f ∈ o(g)
Complexity Classes
If the complexity of an algorithm is O(nc ) for some constant c, it is said to be polyno-
mial in n. A problem for which a polynomial algorithm exists is said to be polynomial,
and the class of such problems bears the name P. Unhappily, not all problems are
polynomial, and numerous problems exist for which no polynomial algorithm has
been found to this day.
One such problem is k-SAT: Given n Boolean variables and m clauses each
containing k literals (a variable or its negation), is it possible to assign to each variable
a Boolean value in such a manner that each clause contains at least one literal with the
value True (SAT is the version of this problem without a restriction on the number of
variables in a clause)? The particularity of each of these problems is that a potential
solution (assignment to each of the variables) satisfying all the constraints can be
verified in polynomial time by evaluating all the clauses: they are in the class NP
(for Non-deterministic Polynomial). We can easily solve 1-SAT in polynomial time,
hence 1-SAT is in P. 2-SAT is also in P; this is the subject of Section 6.9 on page 110.
However, from 3-SAT onwards, the answer is not known. We only know that solving
3-SAT is at least as difficult as solving SAT.
It turns out that P ⊆ NP—intuitively, if we can construct a solution in polynomial
time, then we can also verify a solution in polynomial time. It is believed that
P = NP, but this conjecture remains unproven to this day. In the meantime,
researchers have linked NP problems among themselves using reductions, which
transform in polynomial time an algorithm for a problem A into an algorithm for a
problem B. Hence, if A is in P, then B is also in P: A is ‘at least as difficult’ as B.
The problems that are at least as difficult as SAT constitute the class of problems
NP-hard, and among these we distinguish the NP-complete problems, which are
defined as those being at the same time NP-hard and in NP. Solve any one of these
in polynomial time and you will have solved them all, and will be gratified by eternal
recognition, accompanied by a million dollars.4 At present, to solve these problems
in an acceptable time, it is necessary to restrict them to instances with properties
4 www.claymath.org/millennium-problems/p-vs-np-problem
1.4 Complexity 19
that can aid the resolution (planarity of a graph, for example), permit the program
to answer correctly with only a constant probability or produce a solution only close
to an optimal solution.
Happily, most of the problems encountered in programming contests are
polynomial.
If these questions of complexity classes interest you, we recommend Christos H.
Papadimitriou’s book on computational complexity (2003).
For programming contests in particular, the programs must give a response within
a few seconds, which gives current processors the time to execute on the order of tens
or hundreds of millions of operations. The following table gives a rough idea of the
acceptable complexities for a response time of a second. These numbers are to be
taken with caution and, of course, depend on the language used,5 the machine that
will execute the code and the type of operation (integer or floating point calculations,
calls to mathematical functions, etc.).
1000000 O(n)
100000 O(n log n)
1000 O(n2 )
The reader is invited to conduct experiments with simple programs to test the time
necessary to execute n integer multiplications for different values of n. We insist here
on the fact that the constants lurking behind the Landau symbols can be very large,
and at times, in practice, an algorithm with greater asymptotic complexity may be
preferred. An example is the multiplication of two n × n matrices. The naive method
costs O(n3 ) operations, whereas a recursive procedure discovered by Strassen (1969)
costs only O(n2.81 ). However, the hidden multiplicative constant is so large that for the
size of matrices that you might need to manipulate, the naive method without doubt
will be more efficient.
In Python, adding an element to a list takes constant time, as does access to an
element with a given index. The creation of a sublist with L[i : j ] requires time
O(max{1,j − i}). Dictionaries are represented by hash tables, and the insertion of
a key-value pair can be done in constant time, see Section 1.5.2 on page 21. However,
this time constant is non-negligible, hence if the keys of the dictionary are the integers
from 0 to n − 1, it is preferable to use a list.
Amortised Complexity
For certain data structures, the notion of amortised time complexity is used. For exam-
ple, a list in Python is represented internally by an array, equipped with a variable
length storing the size. When a new element is added to the array with the method
append, it is stored in the array at the index indicated by the variable length, and then
5 Roughly consider Java twice as slow and Python four times as slow as C++.
20 Introduction
the variable length is incremented. If the capacity of the array is no longer sufficient,
a new array twice as large is allocated, and the contents of the original array are copied
over. Hence, for n successive calls to append on a list initially empty, the time of each
call is usually constant, and it is occasionally linear in the current size of the list.
However, the sum of the time of these calls is O(n), which, once spread out over each
of the calls, gives an amortised time O(1).
We will now tackle a theme that is at the heart of the notion of efficient programming:
the data structures underlying our programs to solve problems.
An abstract type is a description of the possible values that a set of objects can take
on, the operations that can be performed on these objects and the behaviour of these
operations. An abstract type can thus be seen as a specification.
A data structure is a concrete way to organise the data in order to treat them
efficiently, respecting the clauses in the specification. Thus, we can implement an
abstract type by one or more different data structures and determine the complexity in
time and memory of each operation. Thereby, based on the frequency of the operations
that need to be executed, we will prefer one or another of the implementations of an
abstract type to solve a given problem.
To program well, a mastery of the data structures offered by a language and its
associated standard library is essential. In this section, we review the most useful data
structures for programming competitions.
1.5.1 Stacks
A stack (see Figure 1.2) is an object that keeps track of a set of elements and pro-
vides the following operations: test if the stack is empty, add an element to the top
of the stack (push), access the element at the top of the stack and remove an ele-
ment (pop). Python lists can serve as stacks. An element is pushed with the method
append(element) and popped with the method pop().
stack
queue
deque
Figure 1.2 The three principal sequential access data structures provided by Python.
the case for all objects implementing the method __len__; for these, if x: behaves
exactly like if len(x) > 0:. All of these operations execute in constant time.
1.5.2 Dictionaries
A dictionary allows the association of keys to values, in the same manner that
an array associates indices to values. The internal workings are based on a hash
table, which uses a hash function to associate the elements with indices in an array,
and implements a mechanism of collision management in the case where different
elements are sent to the same index. In the best case, the read and write operations
on a dictionary execute in constant time, but in the worst case they execute in linear
time if it is necessary to run through a linear number of keys to handle the collisions.
In practice, this degenerate case arrives only rarely, and in this book, we generally
assume that accesses to dictionary entries take constant time. If the keys are of the
form 0,1, . . . ,n − 1, it is, of course, always preferable for performance reasons to use
a simple array.
Problems
Encryption [spoj:CENCRY]
Phone List [spoj:PHONELST]
A concrete simulation [spoj:ACS]
1.5.3 Queues
A queue is similar to a stack, with the difference that elements are added to the end
of the queue (enqueued) and are removed from the front of the queue (dequeued).
A queue is also known as a FIFO queue (first in, first out, like a waiting line), whereas
a stack is called LIFO (last in, first out, like a pile of plates).
In the Python standard library, there are two classes implementing a queue. The
first, Queue, is a synchronised implementation, meaning that several processes can
access it simultaneously. As the programs of this book do not exploit parallelism,
the use of this class is not recommended, as it entails a slowdown because of the
use of semaphores for the synchronisation. The second class is deque (for double-
ended queue). In addition to the methods append(element) and popleft(), which,
respectively, add to the end of the queue and remove from the head of the queue,
deque offers the methods appendleft(element) and pop(), which add to the head of
the queue and remove from the end of the queue. We can thus speak of a queue with
two ends. This more sophisticated structure will be found useful in Section 8.2 on
page 126, where it is used to find the shortest path in a graph the edges of which have
weights 0 or 1.
We recommend the use of deque—and in general, the use of the data structures
provided by the standard library of the language—but as an example we illustrate here
how to implement a queue using two stacks. One stack corresponds to the head of the
queue for extraction and the other corresponds to the tail for insertion. Once the head
22 Introduction
stack is empty, it is swapped with the tail stack (reversed). The operator __len__ uses
len(q) to recover the number of elements in the queue q, and then if q can be used
to test if q is non-empty, happily in constant time.
class OurQueue:
def __init__(self):
self.in_stack = [] # tail
self.out_stack = [] # head
def __len__(self):
return len(self.in_stack) + len(self.out_stack)
2 3
4 5 6 7
8 9 10 11 12
0 1 2 3 4 5 6 7 8 9 10 11 12
Implementation details
The structure contains an array heap, storing the heap itself, as well as a dictionary
rank, allowing the determination of the index of an element stored in the heap. The
principal operations are push and pop. A new element is inserted with push: it is added
as the last leaf in the heap, and then the heap is reorganised to respect the heap order.
The minimal element is extracted with pop: the root is replaced by the last leaf in the
heap, and then the heap is reorganised to respect the heap order, see Figure 1.4.
The operator __len__ returns the number of elements in the heap. The existence of
this operator permits the inner workings of Python to implicitly convert a heap to a
Boolean and to perform such conditional tests as, for example, while h, which loops
while the heap h is non-empty.
The average complexity of the operations on our heap is O(log n); however, the
worst-case complexity is O(n), due to the use of the dictionary (rank).
5 7
13 9 8 30
20 17 11 12 15
9 7
13 11 8 30
20 17 15 12
Figure 1.4 The operation pop removes and returns the value 2 of the heap and replaces it by the
last leaf 15. Then the operation down performs a series of exchanges to place 15 in a position
respecting the heap order.
1.5 Abstract Types and Essential Data Structures 25
class OurHeap:
def __init__(self, items):
self.heap = [None] # index 0 will be ignored
self.rank = {}
for x in items:
self.push(x)
def __len__(self):
return len(self.heap) - 1
def pop(self):
root = self.heap[1]
del self.rank[root]
x = self.heap.pop() # remove last leaf
if self: # if heap is not empty
self.heap[1] = x # move the last leaf
self.rank[x] = 1 # to the root
self.down(1) # maintain heap order
return root
The reorganisation is done with the operations up(i) and down(i), which are called
whenever an element with index i is too small with respect to its parent (for up)
or too large for its children (for down). Hence, up effects a series of exchanges of
a node with its parents, climbing up the tree until the heap order is respected. The
action of down is similar, for an exchange between a node and its child with the
smallest value.
Finally, the method update permits the value of a heap element to be changed. It
then calls up or down to preserve the heap order. It is this method that requires the
introduction of the dictionary rank.
26 Introduction
1.5.5 Union-Find
Definition
Union-find is a data structure used to store a partition of a universe V and that allows
the following operations, also known as requests in the context of dynamic data
structures:
1.5 Abstract Types and Essential Data Structures 27
• find(v) returns a canonical element of the set containing v. To test if u and v are
in the same set, it suffices to compare find(u) with find(v).
• union(u,v) combines the set containing u with that containing v.
Application
Our principal application of this structure is to determine the connected components
of a graph, see Section 6.5 on page 94. Every addition of an edge will correspond to
a call to union, while find is used to test if two vertices are in the same component.
Union-find is also used in Kruskal’s algorithm to determine a minimal spanning tree
of a weighted graph, see Section 10.4 on page 179.
1. When traversing an element on the way to the root, we take advantage of the
opportunity to compress the path, i.e. we link directly to the root that the elements
encountered.
2. During a union, we hang the tree of smaller rank beneath the root of the tree of
larger rank. The rank of a tree corresponds to the depth it would have if none of
the paths were compressed.
8 12 10
7 2 4 11 9 8 12 2 4 11
3 6 1 7 3 6 1 9 10
5 5
Figure 1.5 On the left: The structure union-find for a graph with two components {7,8,12}
and {2,3,4,5,6,9,10,11}. On the right: after a call to find(10), all the vertices on the path
to~the root now point directly to the root 5. This accelerates future calls to find for these
vertices.
28 Introduction
class UnionFind:
def __init__(self, n):
self.up_bound = list(range(n))
self.rank = [0] * n
Problem
Havannah [gcj:2013round3B]
1.6 Techniques
1.6.1 Comparison
In Python, a comparison between n-tuples is based on lexicographical order. This
allows us, for example, to find, at the same time, the largest value in an array along
with the corresponding index, taking the largest index in the case of equality.
use of a dictionary, where n is the number of words given and k is the maximal
length of a word.
def majority(L):
count = {}
for word in L:
if word in count:
count[word] += 1
else:
count[word] = 1
# Using min() like this gives the first word with
# maximal count "for free"
val_1st_max, arg_1st_max = min((-count[word], word) for word in count)
return arg_1st_max
1.6.2 Sorting
An array of n elements in Python can be sorted in time O(n log n). We distinguish two
kinds of sorts:
• a sort with the method sort() modifies the list in question (it is said to sort ‘in
place’) ;
• a sort with the function sorted() returns a sorted copy of the list in question.
Given a list L of n distinct integers, we would like to determine two integers
in L with minimal difference. This problem can be solved by sorting L, and then
running through L to select the pair with the smallest difference. Note the use of
minimum over a collection of pairs of integers, compared in lexicographical order.
Hence, valmin will contain the smallest distance between two successive elements
of L and argmin will contain the corresponding index.
def closest_values(L):
assert len(L) >= 2
L.sort()
valmin, argmin = min((L[i] - L[i - 1], i) for i in range(1, len(L)))
return L[argmin - 1], L[argmin]
Sorting n elements requires (n log n) comparisons between the elements in the
worst case. To be convinced, consider an input of n distinct integers. An algorithm
must select one among n! possible orders. Each comparison returns one of two values
(greater or smaller) and thus divides the search space in two. Finally, it requires at
most log2 (n! ) comparisons to identify a particular order, giving the lower bound
(log(n! )) = (n log n).
Variants
In certain cases, an array of n integers can be sorted in time O(n), for example when
they are all found between 0 and cn for some constant c. In this case, we can simply
30 Introduction
scan the input and store the number of occurrences of each element in an array count
of size cn. We then scan count by increasing index, and write the values from 0 to cn
to the output array, repeating them as often as necessary. This technique is known as
counting sort; a similar variant is pigeonhole sort.
Problems
Spelling Lists [spoj:MIB]
Yodaness Level [spoj:YODANESS]
Example—Intersection of Intervals
Given n intervals [i ,ri ) for i = 0, . . . ,n − 1, we wish to find a value x included
in a maximum number of intervals. Here is a solution in time O(n log n). We sort
the endpoints, and then sweep them from left to right with an imaginary pointer x.
A counter c keeps track of the number of intervals whose beginning has been seen,
but not yet the end, hence it counts the number of intervals containing x.
Note that the order of processing of the elements of B guarantees that the right
endpoints of the intervals are handled before the left endpoints of the intervals, which
is necessary when dealing with intervals that are half-open to the right.
def max_interval_intersec(S):
B = ([(left, +1) for left, right in S] +
[(right, -1) for left, right in S])
B.sort()
c = 0
best = (c, None)
for x, d in B:
c += d
if best[0] < c:
best = (c, x)
return best
Problem
Back to the future [prologin:demi2012]
local criterion. A formal notion exists that is related to combinatorial structures known
as matroids, and it can be used to prove the optimality or the non-optimality of greedy
algorithms. We do not tackle this here, but refer to Kozen (1992) for a very good
introduction.
For some problems, an optimal solution can be produced step by step, making a
decision that is in a certain sense locally optimal. Such a proof is, in general, based on
an exchange argument, showing that any optimal solution can be transformed into the
solution produced by the algorithm without modifying the cost. The reader is invited
to systematically at least sketch such a proof, as intuition can often be misleading and
the problems that can be solved by a greedy algorithm are in fact quite rare.
An example is making change with coins, see Section 11.2 on page 184. Suppose
you work in a store, and dispose of an infinity of coins with a finite number of distinct
values. You must make change for a client for a specific sum and you wish to do it
with as few coins as possible. In most countries, the values of the coins are of the
form x · 10i with x ∈ {1,2,5} and i ∈ N, and in this case we can in a greedy manner
make change by repeatedly selecting the most valuable coin that is not larger than
the remaining sum to return. However, in general, this approach does not work, for
example with coins with values 1, 4 and 5, and with a total of 8 to return. The greedy
approach generates a solution with 4 coins, i.e. 5 + 1 + 1 + 1, whereas the optimal is
composed of only 2 coins: 4 + 4.
Application
Suppose there are n tasks to be assigned to n workers in a bijective manner, i.e. where
each task must be assigned to a different worker. Each task has a duration in hours and
each worker has a price per hour. The goal is to find the assignment that minimises the
total amount to be paid.
x0 ≤ xk
x0 (yj − yi ) ≤ xk (yj − yi )
32 Introduction
x0 yj − x0 yi ≤ xk yj − xk yi
x0 yj + xk yi ≤ x0 yi + xk yj .
By repeating the argument on the vector x with x0 removed and on y with yj removed,
we find that the product is minimal when i → yπ(i) is decreasing.
Problems
Minimum Scalar Product [gcj:2008round1A]
Minimal Coverage [timus:1303]
F (0) = 0
F (1) = 1
F (i) = F (i − 1) + F (i − 2).
This number gives, for example, the number of possibilities to climb an n-step
stairway by taking one or two steps at a time. A naive implementation of F by a
recursive function is extremely inefficient, since for the same parameter i, F (i) is
computed several times, see Figure 1.6.
def fibo_naive(n):
if n <= 1:
return n
return fibo_naive(n - 1) + fibo_naive(n - 2)
1.6 Techniques 33
F4
F2 F3
F0 F1 F1 F2
F0 F1 F2 F3 F4
F0 F1
Figure 1.6 On the left, the exhaustive exploration tree of the recursive computation of the
Fibonacci number F4 . On the right, the acyclic oriented graph of the value dependencies of
dynamic programming, with many fewer nodes.
Try this function on a not-very-large value, n = 32, and you will see that the code
can already take more than a second, even on a powerful machine; the computation
time increases exponentially with n.
A solution by dynamic programming simply consists of storing in an array of size
n+1 the values of F (0) to F (n), and filling it in increasing order of the indices. Hence,
at the moment we compute F (i), the values F (i − 1) and F (i − 2) will already have
been computed; they are the last two values entered into the array.
def fibo_dp(n):
mem = [0, 1]
for i in range(2, n + 1):
mem.append(mem[-2] + mem[-1])
return mem[-1]
However, the above code uses n + 1 memory locations, whereas 2 are sufficient,
those corresponding to the last two Fibonacci numbers computed.
def fibo_dp_mem(n):
mem = [0, 1]
for i in range(2, n + 1):
mem[i % 2] = mem[0] + mem[1]
return mem[n % 2]
dictionary, to avoid the combinatorial explosion of the calls. In other words, adding
@lru_cache(maxsize=None) transforms any old naive recursive implementation into
a clever example of dynamic programming. Isn’t life beautiful?
@lru_cache(maxsize=None)
def fibo_naive(n):
if n <= 1:
return n
return fibo_naive(n - 1) + fibo_naive(n - 2)
Problem
Fibonacci Sum [spoj:FIBOSUM]
{} 0 empty set
{i} 1 << i this notation represents 2i
{0,1, . . . ,n − 1} (1 << n) − 1 2n − 1 = 20 + 21 + · · · + 2n−1
A∪B A|B the operator | is the binary or
A∩B A&B the operator & is the binary and
(A\B) ∪ (B\A) AˆB the operator ˆ is the exclusive or
A⊆B A & B == A test of inclusion
i∈A (1 << i)& A test of membership
{min A} −A & A this expression equals 0 if A is empty
The justification of this last expression is shown in Figure 1.7. It is useful, for
example, to count in a loop the cardinality of a set. There is no equivalent expression
to obtain the maximum of a set.
To illustrate this encoding technique, we apply it to a classic problem.
7 The limit comes from the fact that integers in Python are, in general, coded in a machine word, which
today is usually 63 bits plus a sign bit, for a total of 64 bits.
1.6 Techniques 35
We wish to obtain the minimum of the set {3,5,6} encoded by an integer. This integer is
23 + 25 + 26 = 104.
64+32+8=104 01101000
complement of 104 10010111
-104 10011000
-104&104 = 8 00001000
The result is 23 encoding the singleton {3}.
def three_partition(x):
f = [0] * (1 << len(x))
for i, _ in enumerate(x):
for S in range(1 << i):
f[S | (1 << i)] = f[S] + x[i]
for A in range(1 << len(x)):
for B in range(1 << len(x)):
if A & B == 0 and f[A] == f[B] and 3 * f[A] == f[-1]:
return (A, B, ((1 << len(x)) - 1) ^ A ^ B)
return None
For another utilisation of this technique, see the resolution for numbers in the TV
contest ‘Des Chiffres et des Lettres’ (1965), presented as ‘Countdown’ (1982) in the
UK, Section 15.6 on page 243.
space is reduced either to [,m] or to [m + 1,h]. Note that because of the rounding
below in the computation of m, the second interval is never empty, nor the first for
that matter. The search terminates after log2 (n) iterations, when the search interval
is reduced to a singleton.
Libraries
Binary search is provided in the standard module bisect, so that in many cases
you will not have to write it yourself. Consider the case of a sorted array tab of n
elements, where we want to find the insertion point of a new element x. The function
bisect_left(tab, x, 0, n) returns the first index i such that tab[i] ≥ x.
Continuous Domain
This technique can equally be applied when the domain of f is continuous and we
seek the smallest value x0 with f (x) = 1 for every x ≥ x0 . The complexity will then
depend on the precision required for x0 .
maximal value. The number of iterations necessary is again logarithmic, on the order
of log3/2 n.
Invert a Function
Let f be a continuous and strictly monotonic function. Thus there exists an inverse
function f −1 , again monotonic. Imagine that f −1 is much easier to compute than f ,
in this case we can use it to compute f (x) for a given value of x. Indeed, it suffices to
find the smallest value y such that f −1 (y) ≥ x.
Example—Filling Tasks
Suppose there are n tanks in the form of rectangular blocks at different heights, inter-
connected by a network of pipes. We pour into this system a volume V of liquid, and
wish to know the resulting height of the liquid in the tanks.
Problems
Fill the cisterns [spoj:CISTFILL]
Egg Drop [gcj:eggdrop]
1.7 Advice
Here is a bit of common sense advice to help you rapidly solve algorithmic problems
and produce a working program. Be organised and systematic. For this, it is important
to not be carried away with the desire to start hacking before all the details are clear.
It is easy to leap into the implementation of a method that can never work for a reason
38 Introduction
that would not have escaped you if you had taken a bit more time to ponder before
starting to pound on the keyboard.
When possible, in your program, separate the input of the instance from the com-
putation of the solution. Be nice to yourself and systematically add to the comments
the name of the problem, if possible with its URL, and specify the complexity of
your algorithm. You will appreciate this effort when you revisit your code at a later
date. Above all, stay coherent in your code and reuse the terms given in the problem
statement to highlight the correspondence. There is little worse than having to debug
a program whose variable names are not meaningful.
iteration is a classic error. Take, for example, a program solving a graph problem
whose input consists of the number of instances, followed by each instance,
beginning with two integers: the number of vertices n and the number of edges
m. These are followed by two arrays of integers A,B of size m, encoding the
endpoints of the edges for each instance. Imagine that the program encodes
the graph in the form of an adjacency list G and for every i = 0, . . . ,m − 1,
adds B[i] to G[A[i]] and A[i] to G[B[i]]. If the lists are not emptied before
the beginning of each input of an instance, the edges accumulate to form a
superposition of all the graphs.
Debug
Make all your mistakes now to have the proper reflexes later.
Generate test sets for the limit cases (Wrong Answer) and for large instances
(Time Limit Exceeded or Runtime Error).
Explain the algorithm to a team-mate and add appropriate comments to the pro-
gram. You must be capable of explaining each and every line.
Simplify your implementation. Regroup all similar bits of code. Never go wild
with copy-and-paste (note from the translators—one of the most observed
sources of buggy programs from novice programmers!).
Take a step back by passing to another problem, and come back later for a fresh
look.
Compare the environment of your local machine with that of the server where
your code will be tested.
See [icpcarchive:8154].
Iskander the Baker is decorating a huge cake by covering the rectangular sur-
face of the cake with frosting. For this purpose, he mixes frosting sugar with lemon
juice and beetle juice, in order to produce three kinds of frosting: yellow, pink and
white. These colours are identified by the numbers 0 for yellow, 1 for pink and 2
for white.
To obtain a nice pattern, he partitions the cake surface into vertical stripes of width
A1,A2, . . . ,An centimeters, and horizontal stripes of height B1,B2, . . . ,Bn centime-
ters, for some positive integer n. These stripes split the cake surface into n × n
rectangles. The intersection of vertical stripe i and horizontal stripe j has colour
number (i + j ) mod 3 for all 1 ≤ i,j ≤ n, see Figure 1.8. To prepare the frosting,
Iskander wants to know the total surface in square centimeters to be coloured for each
of the three colours, and asks for your help.
Input
The input consists of the following integers:
Exploring the Variety of Random
Documents with Different Content
The Project Gutenberg eBook of Suonion
kootut runoelmat ja kertoelmat
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: Finnish
SUONION KOOTUT
RUNOELMAT JA KERTOELMAT
Kirj.
J. Krohn
Tekijän esipuhe
Varpunen
I. Emma
Lemmen aamu
Sydämelle
Armaalleni
Nyt on aika armastella
Tottelemattomat jäsenet
Kova rangaistus
Lempeni ja viisas ystäväni
Armasta odottaessa
Illalle
Miks sua rakastan ma?
Haudan partaalla
Kahden kesken
Tyhjyys
Uusi sulhas-aika
Helmi ja isänsä
Kaikkein vaikein
Unhoitus
Ihmis-seuroissa
Hiljaa!
Puolen vuoden päästä
Ma olin rikas
Mut miltä tuntui katsees?
Vapaa
II. Lempi
Neidon rukous
Ainoa hetki
Ne ovat vait
Yhteen kasvaneet koivut
Neidon lohdutus
Nimetön sormi
Sydämen taisteluita
Oi kiitos!
Keväällä 1876
Suvilaulu
Onneton
Juomalaulu
Soittoa kuullessa
Sotamies-laulu
Pikku Julius vainaa
Järven rannalla
Pää pystyyn
Sun tahtosi tapahtukoon
IV. Luonto ja elämä
Suksimiesten laulu
Lumisateella
Rantakalliolla keväällä
Clarens'in hautausmaalla
Rauta
Tähden tuikkiminen
Purjehdusretki
Viinitarhan edustalla
Naurava käki
Varoitus
Runoniekan sydän
Kaste ja Kyynel
Elämän meno
Turvaton
V. Leikillisiä
Neuvo
Laiskuuden ylistys
Varoitus tytöille
L'Isle de la paix
Lempi ja Lempo
Komea hautakivi
Suurisuiselle ystävälle
Italian herääminen
Pohjolan valkeneminen
Suomalaisille
Koivu Etelässä
Provessori Lönnrotille
Vieras lippu
Hyljätty äiti
Karkuri
Suomalainen maamme Ruotsalaiselle
Tuhma, raak' on Suomalainen
Suurelle herralle
Feniläiset
VII. Tilapäisiä
VIII. Virsiä
IX. Suomennoksia
X. Kuun tarinoita
XI. Novelleja.
Viimeinen Rekryytin-otto
Hollannin saaristossa
Viimeinen Kosija
Viimeinen kohtaukseni Neapelin rosvoin kanssa
TEKIJÄN ESIPUHE
Paremmille laulajoille,
Runsahammille runoille.
Paremmat laulu-äänet
Keväällä ehtinee,
Niin kuullellessaan noita
Jo varpu vaikenee!
I. EMMA.
Lemmen aamu.
Sydämelle.
Sydän, sydän saastahinen,
Kuinka tohditkaan sa kurja
Pyhää neittä ihaellen
Toivoin tykyttää?
Armaalleni.
Tottelemattomat jäsenet.
Kova rangaistus.
Neito:
Poika:
Armasta odottaessa.
Istun ikävissäni:
Kauan kulta viipyvi,
Verkkaan aika vierevi —
Riennä, aika, riennä!
Tulipa jo kultani,
Lepää kainalossani,
Mailma kaikk' unohtuvi —
Viivy, aika, viivy!
Illalle.
Lampi läikkyväinen
Mielenikin on,
Päivän hälinässä
Raukka rauhaton.
Haudan partaalla.
Lapioi, lapioi!
Hautuumiesi, lapioi!
Jota niinkuin terää silmän
Varjoin tuulosistakin;
Sen nyt poveen mustan, kylmän
Maan ma itse upotin.
Lapioi, lapioi,
Kultan' maahan lapioi!
Lapioi, lapioi,
Hautuumiesi lapioi!
Käydess' ennen käsityksin
Helpoittaa ma koitin tien;
Nyt mä tänne jätän yksin,
Tupaan kolkkoon, outoon vien.
Lapioi, lapioi,
Armaan' maahan lapioi!
Lapioi, lapioi,
Hautuumiesi, lapioi!
»Miksi: elo?» kysyin ennen;
»Ilohan ois oikeempi!»
Ah nyt ilon' katos tännen,
Elostani erosi.
Lapioi, lapioi,
Onnen' maahan lapioi!
Lapioi, lapioi! —
Herra — voi! — Mut mi soi?
Virsi, jonka hältä kuulin,
Kun hän jätti hyvästi,
Jonka kylmenevin huulin
Riemuin vielä veisasi!
Virsi soi, virsi soi,
Pyhä virsi, soi, ah soi!
Tyhjyys.
Uusi sulhas-aika.
Helmi ja isänsä.
Kaikkein vaikein.
Unhoitus.
Ihmis-seuroissa.
——————————
Hiljaa!
Ma olin rikas.
Vapaa.
Sä olet vapaa taas — niin mulle sanotaan —
Saat vapaast' ihaella suloisuutta;
Sun lupa ompi onnea taas uutta.
Jos mistä mieli tekee, mennä hakemaan! —
ebookbell.com