Competitive Programming in Python: 128 Algorithms to Develop your Coding Skills 1st Edition Christoph Dürr all chapter instant download
Competitive Programming in Python: 128 Algorithms to Develop your Coding Skills 1st Edition Christoph Dürr all chapter instant download
com
https://textbookfull.com/product/competitive-programming-in-
python-128-algorithms-to-develop-your-coding-skills-1st-
edition-christoph-durr/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/algorithmic-thinking-learn-
algorithms-your-coding-skills-2ed-2024-zingaro-d/
textboxfull.com
https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-michael-stueben/
textboxfull.com
https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-1st-edition-
michael-stueben/
textboxfull.com
https://textbookfull.com/product/algorithms-for-competitive-
programming-1st-edition-david-esparza-alba/
textboxfull.com
Basic Exercises for Competitive Programming Python 1st
Edition Jan Pol
https://textbookfull.com/product/basic-exercises-for-competitive-
programming-python-1st-edition-jan-pol/
textboxfull.com
https://textbookfull.com/product/coding-games-in-python-1st-edition-
carol-vorderman/
textboxfull.com
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
Another Random Scribd Document
with Unrelated Content
France, under the leadership of Poincaré, scoffed from the
beginning at the League of Nations, although supporting it over the
Corfu incident, and although one representative, M. Léon Bourgeois,
was a loyal friend of the League idea. After the refusal of the United
States to ratify the pact of security for France against another war of
German aggression, followed by the withdrawal of Great Britain, the
France of Poincaré saw no safety except in the power of her Army in
alliance with other forces which she could link in a military chain
around her defeated enemies. No one ought to blame France for
that philosophy, in view of her agony and her future peril. But it
resulted inevitably in actions which checked the recovery of Europe,
aroused all the old hatreds, filled the defeated peoples with a sense
of profound injustice, and raised the old devils of national pride,
vengeance, and belief in force which for a time had been banished
to the houses of the German Junkers and had lain low in German
hearts. It was the cause of increasing friction, spasms of passionate
ill-will, between France and England, and a long campaign of
scurrilous abuse in the French Press which poisoned the old Entente
Cordiale, wiped out the memories of war comradeship, and was a
tragic and painful chapter in recent history.
France under Poincaré demanded her pound of flesh from
Germany, including the lifeblood of the German people in the
arteries of its economic health. Germany could not recover nor,
before recovering, pay. Afterwards, when the Ruhr was invaded,
their chief source of wealth and of payment was strangled. The
French objects of “security” and “reparations” were in hopeless
antagonism, and defeated each other. There could be no
reparations, on a large scale, if French security demanded the
expulsion of those who directed and worked the Ruhr and its
railways. There could be no “security” for France in the long run if,
instead of German reparations, she goaded the German people into
nationalism and a war of vengeance by every means, fair or foul.
While the policy of Poincaré was dominant, Europe sank deep into
despair, and the nations most stricken by war saw no hope of
revival.
The first three years after the world war provided terrible proofs of
the disaster which had happened to humanity in that deadly
struggle. Those who wish to convince the future generations of the
devastating effect of modern warfare upon highly organised nations,
as a frightful warning, must summon up the picture of Europe in
1919, 1920 and 1921. I saw it from end to end, and it haunted me.
On the Eastern side of Europe Russia was cut off from the family
of nations and lay prostrate. Civilisation itself had gone down there
in anarchy and misery, and its new government of Bolsheviks were
ruling over a hundred million people, hungry, diseased, stricken,
crushed in spirit, weak in body, overcome by melancholy and inertia.
They had broken first under the strain of war. Four million of their
men had died in the fields of slaughter and their labour had been
taken from the fields. Corruption beyond words, treachery in high
places, inefficiency amounting to murder, had aroused a spirit of
revolt amongst soldiers sent forward without arms to fight against
men with whom, individually, they had no lasting cause of quarrel;
peasants like themselves, gun-fodder like themselves, for ambitions
and hatreds which they did not share. They turned to rend their own
leaders and made a pact at any price with the enemy outside. All the
explosive forces of passion which had been stored up in centuries of
tyranny by a brutal Tsardom and its Governors burst out against its
present representatives, although the last Tsar was a gentle man
who loved his people. Old dreams of liberty, new philosophies of
democracy, united for a time to overthrow the Government and all
its powers. Revolution, bloody and cruel, raged in Russia, and the
beast leapt up in peasant minds. Kerensky tried to control this
anarchy but was swept on one side like a straw by stronger forces.
Lenin and his crowd took command, and their new philosophy of
Communism, fair-sounding, theoretically righteous, based upon the
principles of equality and brotherhood and peace, put a spell upon
the simple minds of the Russian folk. All opponents, critics, doubters,
were destroyed relentlessly. Lenin and his friends, having taken
command of the new machinery of Government by Soviet
committees, were in supreme power over a people unarmed, half-
starving, and submissive to those who had broken their old chains.
It was some time before the Russian folk were aware of the fetters
which enslaved them, and of a tyranny over their minds and bodies
more ruthless than that of Tsardom. They were denied freedom of
speech, freedom of knowledge, freedom of movement. The
newspapers published the news of the world according to Lenin. The
schools taught economic history according to Karl Marx and world
history according to Soviet philosophy. Trotsky fashioned a Red Army
in which discipline was more severe than under the Grand Duke
Nicholas. The prisons were filled with people of all classes who came
under the notice of the secret police. Execution became a habit.
There was a Reign of Terror undoubtedly as bad as that of the
French Revolution of 1793.
For a time the people as a whole were keyed up to a new
enthusiasm for what they believed to be a democratic system of
Government by attacks from the “White Armies” of the old Royalists,
financed, armed and organised by foreign powers, and especially by
France and Great Britain. As Republican France had risen against the
armies of the emigrés, so Soviet Russia rallied against the armies of
Koltchak, Denikin, Wrangel and others, and defeated them
overwhelmingly. After that the Reign of Terror abated somewhat,
internal revolt died down, and the gospel of Communism was seen
at work in conditions of peace.
It failed to work. It was all very well for the Communists to hand
out tickets for bread, clothes, boots, education and operas to all
those who were registered for service to the State, but those who
presented the tickets found that there was not enough bread to go
round, that no clothes or boots were forthcoming, that education is
a poor thing on empty stomachs in schools where the teachers died
of starvation, and that the opera, beautiful as it continued to be, was
not nourishing after a day of hunger. The workers fled from the
factories because they could get no food. In the fields the peasants
resisted the soldiers who tried to requisition their grain for the cities.
Transport broke down. Grass grew on the railways. Horses and cattle
died for lack of fodder. Typhus was rampant for lack of soap,
medicines, decent conditions of life. Then famine struck the Volga
region after two summers of drought. Twenty-five million people
were threatened with death by actual starvation, and all over Russia
there was hunger, fear, and despair.
From the famine districts the roads were black with fugitives
moving to districts where they hoped to find food, while, from those
very districts, people were trekking away from barren fields. Parents
abandoned their children. When I went down the Volga the people
were eating dried leaves, chopped straw and clay. The children were
dying. The old people awaited death. And far away in Petrograd and
in Moscow the factories were deserted, the hospitals were stone cold
for lack of fuel, and there was not a single man or woman who had
any comfort of body or soul.
Communism had failed. Its failure was proclaimed by Lenin
himself. Russia was in extremis after a war which had broken the
machinery of its life and a revolution which had failed to fulfil any of
its promises, except equality—in misery.
That downfall of Russia was the worst thing in Europe, and was
the cause of some of its general poverty. Trade was cut off from a
hundred million people. Their purchasing power had been
extinguished, so that neighbouring countries could not sell to them.
Their own sources of wealth had perished, so that neither wheat nor
oil nor flax could be exchanged for manufactured goods. The wealth
of the world was so much less.
At that time the new Baltic States were unable to support
themselves on any decent standard of life. Their children also were
underfed. No trade came into the port of Riga, which once had been
busy with the world’s merchandise.
In Poland there was the spiritual warmth of national
independence, but not much else. Misery was widespread. Food for
the army was taken from the people. Commerce was stagnant,
industry at a standstill. Germany was not buying from Poland. Poland
could not buy from Germany or Russia. Underneath its new military
ardour there was desperate need in the homes of the workers.
In Germany it was not so bad—but bad. For the last year of the
war the people had been reduced to the bare limits of food supply.
After the war, when the blockade was maintained until the signature
of peace, the children went without milk and fats and there was
general shortness of provisions, not amounting to actual starvation,
but weakening the working men and women. Factory workmen told
me that they never ate meat, and existed on bread and potatoes. It
was enough for life, they said, but not enough for physical strength.
They felt tired. Women fainted in the tramcars. There was stinting
and scraping in every home, except those of the “profiteers,” who by
some genius of finance were making a good thing out of the fall of
the mark.
Coming across Europe like that, and seeing the spreading track of
financial and commercial ruin, the lowering of the standard of life in
many countries where it had been high and splendid, the loss of
purchasing power for anything but the barest necessities, and all the
new frontiers and customs lines between new States and old States,
checking the free interchange of goods, slowing down world trade,
an observer like myself was staggered by the gravity of this state of
things. It seemed to me that we were all heading for disaster. I was
convinced that all those fair promises of quick prosperity, German
reparations, revival of British trade, stabilising of international
exchanges, would be utterly falsified unless there was a new co-
operation among the countries of Europe on lines of economic
commonsense, and a truce to the policy of demanding from the
defeated countries immense sums of money beyond their ability to
pay. It seemed to me very clear that if Germany went down into real
economic disaster the whole of Europe would go down too, and that
what was wanted most was not payment of fantastic reparations but
a return to the normal exchange of goods and energy. I was afraid
for England.
Then, quicker than in France, all this illusion was smashed in the
face by reality. The British nation became aware of its dwindling
trade, the stagnation of its industry. Unemployment began to creep
up in a steady tide, until two million men were out of work and
existing only on Government “doles.” Factories were closing down or
working half time. The Mersey, the Clyde and the Thames were
crowded with ships without cargoes, and all the ports were filled
with seamen without berths. After demobilisation ex-officers as well
as men could not find jobs to do. They tramped the streets in search
of work, wearing out their boots and their hearts. They played
piano-organs, moved in dismal processions with banners flying the
words “We want work,” shook street collecting boxes in the faces of
the passers-by. The Trade Unions were hard and selfish. They
refused to admit untrained labour to their ranks. Without Trade
Union tickets men who had saved the country were turned away at
the factory gates. Labour put up a fierce fight to maintain the
standard of wages and of life which had been established in time of
war—no longer possible in time of peace with failing markets and a
world in ruin. One cannot blame them. None of us likes to reduce his
standard of life and go back to miserable conditions of stint and
scrape. Strikes and lockouts beat them down, but did not relieve the
strain or increase the nation’s wealth. Things looked very serious
below the surface of English life. There was a bitterness in the minds
of men who had been promised great rewards for heroic service,
and now found themselves destitute, in overcrowded slums—where
were the “homes for heroes”?—maintained on a miserable “dole”
that just saved them from starvation but was not enough for decent
life. There was for a year or so a danger of revolt, a spreading of
revolutionary ideas, among men like that. Russian Communism put a
spell upon many minds who knew nothing of the agony in Russia but
were stirred by the Bolshevik doctrine of equality and the
“dictatorship of the proletariat.”
When Germany failed to pay the immense reparations which had
been demanded from her the British Government was faced with the
necessity of balancing its yearly Budget without those payments,
and, unlike France, which still banked upon them, or like Germany,
which created false money by inflation, determined to sustain the
national credit by taxation and sound finance. It put the most
tremendous burden upon the nation that has ever been sustained by
any people in modern history. It was accepted with a resignation and
courage which will stand for ever to the credit of the British folk, and
especially to the credit of those who paid at the cost of all that was
dearest to them in life apart from national honour and family blood.
Income Tax, Super Tax, and Death Duties fell upon the people who
lived on inherited wealth with a terrifying ferocity. There are only
two and a half million people in Great Britain who pay any Income
Tax at all, and only eighty-five thousand who are subject to Super
Tax, but it was from that small minority that the Government
demanded the revenue necessary for the upkeep of its services. It
caused, and is causing, a social revolution which is changing the
whole aspect of English life. The old aristocracy are abandoning their
houses, selling their estates, becoming shabby genteel, losing their
old splendour, prerogatives and power. To pay their Income Tax and
Death Duties they are eating into their old capital, selling the old
pictures on their walls, abandoning old mansions haunted by the
ghosts of history in which their pride and spirit dwelt. They have
done this not without anguish, not without a sense of tragedy, not
without bitterness, but with an acknowledgment of inevitable
necessity. Bloodlessly the revolution in England is being
accomplished, though the hard road has not yet been travelled to
the end.
More crippling in its effects upon the nation as a whole was the
taxation of capital in trade and industry. At a time when it was most
necessary to limit the costs of production and to stimulate the
adventure of trade, the business world was crushed under a burden
of taxation which limited its reserves, put heavy charges upon the
cost of manufacture, and reduced the capital available for new
enterprise. The price of war, and of victory, lay with an almost
intolerable weight upon the spirit of the British people, even before
they had to shoulder the burden—rejected by every other nation—
the payment of War Debt to the United States of America,
amounting to £35,000,000 sterling every year. With an export trade
less than 75 per cent. of what it reached before the War, with a
population which had increased by nearly two millions in spite of all
the slaughter, with new and ruinous expenses, and with a higher
standard of life demanded by the labouring class, the people of
Great Britain breathed hard, became very anxious, faced up to
realities, and saw, with almost blinding clarity of vision, that their
own national life depended upon the peace and recovery of Europe,
including that of Germany and the defeated peoples. This realisation
changed their whole attitude of mind towards the problem of peace.
It made them draw farther and farther away from the French policy
of Poincaré, which was based upon the prevention of German
recovery and “security” by military force. But above all these
financial considerations England believed in fair play even to a
defeated foe, in generosity rather than vengeance, and in future
peace by conciliation rather than by a military combination which
one day would be challenged in another “inevitable” war, more
ghastly than the last. All that sounded like weakness and treachery
to the mind of France. The Entente Cordiale was strained and
broken....
The “A.R.A.”
I went into Russia with some of the first officials of the A.R.A. and
travelled with them to the Volga region, where twenty-five million
people were threatened with starvation and starving. It was
Governor “Jim” of Indiana—Governor Goodrich—whose wise,
temperate and humane report was a document which helped to save
those millions. I read it as he had written it in a slow-going train
from Kazan to Moscow on the way back from dreadful scenes, and I
gave the homage of my heart to that serene-eyed man who, with
one lame leg, travelled through Russia on a diet of apples, went
fearlessly into typhus-stricken places, and saw all things with a great
pity, sound commonsense, practical judgment, large humanity.
He was only an observer. Colonel Haskell and his little band of
officers were the organisation and the administration in the field of
action, of a great campaign of rescue which flowed out from
America. They had to contend with the inertia of Russian character,
with the suspicion of Soviet officials who feared a political purpose
behind the work of charity, with a broken-down railway system, with
no material for printing or packing, with immense distances and lack
of transport, with the Russian language and bad interpreters, with
Russian labour weakened by being under-nourished, and with
millions of starving and disease-stricken people who had hardly the
strength or will to help themselves or co-operate with others for
their own rescue. It was a formidable adventure in which the young
officers of the A.R.A.—like those of our British relief societies—risked
their lives by disease and were strained to the utmost of nervous
energy. And they brought the food to Russia and distributed it to the
starving folk. Millions died—Dr. Nansen reckons four millions—but
eleven million people were fed every day by the A.R.A. for nearly a
year. In addition to that mass relief, millions of food packages
addressed to individuals in Russia by relations and friends in the
United States reached the starving and distressed people outside the
area of actual famine, and gave new hope of life to those who had
been reduced to misery and despair in Petrograd, Moscow, and other
cities. When we think of the organisation and labour required in time
of war to feed our armies in the field, it is almost miraculous that
eleven million Russian peasants could be supplied at a distance of
6,000 miles, after the breakdown of the very machinery of their life.
History will record it as the greatest campaign of relief and
international charity ever attempted or achieved.
It is only right to say that, after the first suspicions had been
overcome, the Soviet Government and its officials played fair and did
all they could to facilitate this work. The food did reach the starving
children and their parents. The railways and engines were repaired.
Trucks were built. A new hope dawned in Russia, which learnt
something from American methods of efficiency. The Reign of Terror
had worn itself out, the actual practice of Communism was
abandoned, the rights of private property and private trading were,
to some extent, restored, a great shadow passed from the spirit of
the people, and in many ways life became endurable after the years
of agony. The utter failure of the Communist experiment was
acknowledged by Lenin within Russia itself, though its propaganda
and revolutionary doctrines were still used to stir up trouble in the
outside world. Slowly the life of the Russian people staggered up
from misery, and although there is still great distress in many
districts and a new threat of famine, the ninety million peasants,
controlled by a small body of Communists whose economic
philosophy has no appeal for them, are getting a bare life out of the
soil, with now and then a surplus of grain for export in return for
manufactured goods. Even Russia is on the road to recovery.
Other countries revived, at least to the extent of providing their
own means of subsistence, in peasant states like those of the new
Baltic nations. Even international trade recovered some of its old
activity in countries, like Czecho-Slovakia, newly carved out of the
old Austrian Empire and successors to its sources of industrial
energy. But it was impossible to hope for any general and complete
recovery of trade conditions in Europe so long as there was no
stability in the value of monetary exchange and no political peace.
The printing presses in many countries were issuing paper money
which had no reality behind it, and the time came when it proved
worthless either for internal commerce or for foreign business.
Russian roubles had long ceased to have any purchasing power. A
million roubles brought from Moscow would not buy a glass of
schnapps in Riga.
The Relief of Austria
What further excited the bitter hatred of the Germans was the
effort of French generals and political agents to detach the loyalty of
the Rhineland from the German Empire by encouraging bodies of
“Separatists,” who proclaimed a Rhineland Republic. Led by a very
doubtful but plausible gentleman named Dr. Dorten, whom I met in
the early days of the British occupation, these “Separatists” were
mostly youths of the disorderly class and men of criminal type
supported by a few sincere fanatics. Many of them were in the pay
of the French. Their movement was regarded as black treachery by
patriotic Germans, and when the French troops stood by the
Separatists while they seized public buildings and murdered German
police, previously disarmed by French orders, fury was unrestrained
among the German people. French policy, in this matter at least, was
a blunder, because from the first the Separatist movement had no
basis of reality nor any chance of success. It was an illusion of
French politicians who let their wish be father to their thoughts.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com