PDF Competitive Programming in Python: 128 Algorithms to Develop your Coding Skills 1st Edition Christoph Dürr download
PDF Competitive Programming in Python: 128 Algorithms to Develop your Coding Skills 1st Edition Christoph Dürr download
com
https://textbookfull.com/product/competitive-
programming-in-python-128-algorithms-to-develop-
your-coding-skills-1st-edition-christoph-durr/
https://textbookfull.com/product/algorithmic-thinking-learn-
algorithms-your-coding-skills-2ed-2024-zingaro-d/
textbookfull.com
https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-michael-stueben/
textbookfull.com
https://textbookfull.com/product/good-habits-for-great-coding-
improving-programming-skills-with-examples-in-python-1st-edition-
michael-stueben/
textbookfull.com
https://textbookfull.com/product/healing-your-eyes-with-chinese-
medicine-acupuncture-acupressure-chinese-herbs-andy-rosenfarb/
textbookfull.com
CFD Techniques and Energy Applications 1st Edition Zied
Driss
https://textbookfull.com/product/cfd-techniques-and-energy-
applications-1st-edition-zied-driss/
textbookfull.com
https://textbookfull.com/product/the-performance-of-nationalism-india-
pakistan-and-the-memory-of-partition-1st-edition-jisha-menon/
textbookfull.com
https://textbookfull.com/product/discourses-on-sustainability-climate-
change-clean-energy-and-justice-elena-v-shabliy/
textbookfull.com
The Alternative Augustan Age 1st Edition Josiah Osgood
https://textbookfull.com/product/the-alternative-augustan-age-1st-
edition-josiah-osgood/
textbookfull.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().
Random documents with unrelated
content Scribd suggests to you:
karkeat hatutki, joita talonpoikaiset kantoivat; mutta nyt ruvettiin
kaikkea senlaista kotimaassa askaroimaan. Pohjanmaalla ja
Viipurissaki rakennettiin laivoja, ja ulkoa hankittiin taitavia
tekomestareita talonpoikia tämmöiseen työhön opettamaan. Muuten
oli tämä aika rikas lakein laatimisestaki. Meri-, Sota-, Hovi- ja
Kirkkosäännöt, niinkuin myöski Käytösorteleita virkamiehille,
annettiin järjestyksen edesauttamiseksi.
Iso viha oli, niinkuin kova ja hävittävä rajuilma, käynyt yli Suomen
maan. Surkialta näytti sen perästä meidän tila. Ihmiset olivat tuiki
vähässä, suuria maanääriä oli autiana, kaupungit hävitetyt, kaikki
kauppa väsäytynyt, hevoiset ja juhdat sangen kalliit ja harvassa
tavattavat, ja pellot eivät olleet muokassa eivätkä kylvetyt. Tämä tuli
vielä pahemmaksi, kun v. 1722 ja 1723 tapahtuivat katovuodet.
Ruotsista lähetettiin jyviä ja koettiin kaikella tavalla ylösauttaa
meidän maata. Veroja helpotettiin, ja vapaavuosia annettiin niille,
jotka tahtoivat uudestaan ylösottaa autiamaita. Itäisen rajan
puoltamiseksi vahvisti Kuningas Fredrikki I:mäinen linnoituksilla sen
entisen Vehkalahden kaupungin, joka nyt sai Haminan nimen (ruots.
Fredrikshamn).
Gustavi III:nen kautta, joka heti isänsä perästä otti kruunun, tulee
se aika päätymään, kun on vuotten 1720 ja 1772 välillä, kutsuttu
Vapausajaksi ja merkitty Kuningasten aivan vähän vallan ynnä siitä
seuraavan sisämäisen hämmennyksen kautta. Viimmeiseksi
mainittuna vuonna vaikutti Gustavi sen muutoksen, joka pelasti
Ruotsin valtakunnan monivallan riidoista, antoi jällensä Kuninkaalle
oikean mahtinsa ja tuotti laillisen hallitusmuodon. Tämän Kuninkaan
ensimmäiset vuodet olivat Suomelle, niinkuin Ruotsillenki, siunatut
hyvällä sovulla ja menestyksellä. Gustavi kävi v. 1775 ensimäisen
kerran meidän maassa ja teki monta laitosta, joista paljon hyvää on
seurannut. Ennen oli hän jo jakanut Suomen 6:teen lääniin ja
määrännyt Maanherrain asuntopaikat lääneinsä keskeen. Nyt alettiin
suurella innolla toimittaa maantilusten jakamista ison jaon kautta.
Vaasaan laitettiin Hovi-Oikeus, joka 28 p. Kesäkuuta v. 1776 tuli
Tukhulmissa vihityksi. Kihlakuntain rajat tulivat tarkemmin käydyiksi,
Tuomarein alustoita jaettiin pienemmiksi, teitä tehtiin uudesta, ja
koskenperkkaukset saivat alkunsa. Uusia kaupunkeja perustettiin:
Kuopio v. 1779, Tamperi 1779, ynnä Kasköö 1785; ja Hämeenlinna
tuli v. 1788 soveliaammalle ja raittiimmalle paikalle muutetuksi.
Kauppa alkoi kukoistaa, ja sota Englannin ja Pohjas-Amerikassa
olevain uutisasuntojensa välillä, oli Suomen laivankulkua
erinomaisesti kartuttava isojen vuokratavarain kulettamisella ja
korkealla tervan ynnä kaikenlaisten laivantarpeitten hinnalla. —
Tämä oli parempi ja rauhaisempi puoli Gustavi III:nen hallituksesta.
Mutta sen loppupuolella nousi maakunnassa suuri epätytyväisyys
moneen Kuninkaan toimeen, ja oliki tähän usein hänen itsensä
syytä, ehkä ne laittomaan vapauteen harjautuneet ylimykset myös
toiselta puolen hakivat syitä vihaansa ja uppiniskaisuuteensa häntä
vasten. Tämä viha puheksi kapinaan siinä sodassa, jonka Gustavi v.
1788 nosti Venäjätä vasten. Mainittu valta, — jossa, Keisarinnan
Eliisabethin v. 1762 kuoltua ja Pietari III:nen muutamia kuukausi
hallittua, uusi Keisarinna Kathariina II:nen oli saanut kruunun, —
sattui silloin olemaan sodassa Turkin kanssa ja kaikki hänen
sotalaumat siellä etelässä. Sentähden toivoiki Gustavi nyt saada
tämän naapurinsa kukistetuksi ja ne maat, kun se oli ennen Ruotsilta
voittanut, jällenotetuksi. Hänen sotajoukko kävi rajan yli, ja
pienempiä tappeloita tapahtui. Meritappelosta Huoglannin tykönä, 17
p. Heinäkuuta, ei seurannut mitään. Itäpuolella Haminata nousivat
Ruotsalaiset maalle, ja sen kaupungin piti kaikilta puolin tulla
piiritetyksi, kun joukko upseerejä ja sotamiehiä äkäysi, eivätkä
tahtoneet totella Kuningasta. He sanoivat sotaa vasten riikin lakeja
alotetuksi. Tällä kovakorvaisuudella oli siinä perustuksensa, että ne
ylimykset, kun 1772-vuoden hallitusmuodon muutoksen kautta olivat
menettäneet valtansa, nyt olivat vahvistuneet ja vannouneet
kapinaliittoon, joka Anjalan liittouksen nimellä on tuttu. Kun
Kuningas oli tästä tiedon saanut, käski hän armeiansa marssia
takasin ja lopetti sen vuoden sotimiset; mutta mainitun liittouksen
päämiehet tulivat kovan rangaistuksen kärsimään. Seuraavana
vuonna tapahtui vähempiä metelejä, vaihettelevaisella onnella.
Ruotsalaiset saivat voiton Parkkumäen tykönä; vaan heidän
luotolaivasto tuli Ruotsinsalmen luona lyödyksi. Mutta vuoden 1790
sotaan varustausi Gustavi III:mas kaikista voimistansa. Varain
keväistä alkoivat nyt metelit, vaan ei tullut mitään päättävätä
toimeen kummankaan puolen, vaikka suurella vihastuksella sodittiin.
Ruotsalaiset saivat voiton Valkialan tykönä; vaan Savitaipaleen ja
Anjalan luona ajoi vihollinen heidät peräytymään. Sillä aikaa oli
Kuningas itse suurella laivastollansa tullut Viipurin lahteen ja
vihollinen salvannut hänen sinne niin pahasti, että hän ainoastaan
suuren tapon kanssa pääsi lyömään itsensä sieltä läpi ja pois. Sitä
vastoin sai hän heti perästä suuren ja painavan voiton
meritappelussa Ruotsinsalmen tykönä. Se voitto vaikutti, että rauha,
14 p. Elokuuta, lyötettiin Värrölän ( Niin kutsutaan tätä paikkaa kylän
keskuudessa. Kirjoissa tule se Verelän nimellä esiin.) kylässä, jossa
kaikki päätettiin samalla asemella pysymään, kun ennen sotaaki. Ei
ollut Suomella ollut pahasti rasitusta tästä sodasta, vaan sen siaan
suuria rahasummia tullut liikkeelle maassa, ja kaikki saaneet kalunsa
korkeaan hintaan menemään. Ainoastaan muutamat sotaa seuraavat
taudit olivat tappaneet ihmisiä, ja väestötä maasta vähentäneet. —
Tämän sodan aikana oli Kuningas Gustavi 1789:vuoden
Riikinkokouksessa kaikenlaisilla keinoilla pakoittanut kansaa
suostumaan siihen niin kutsuttuun Yhdistys ja Vakuutuskirjaan, joka
tuotti Kuninkaalle yhä suuremman vallan. Riikin Neuvot tulivat myös
herkeämään, ja Kuninkaan Korkein Tuomioistuin siaan. Mutta viha
Kuningasta vasten kiihtyi tämän kautta aina enemmin, ja vaikutti,
että hän tuli v. 1792 ammutuksi eräältä Ankarströmiltä. Hän oli
aikanansa rakastanut paljon kirjallisia taitoja sekä kehoittamalla niitä
sytyttänyt.
Joko nyt taas silmäämme, kutka tällä ajalla olivat Suomen Kirkkoa
hallinneet. Jaakko Gadoliini oli ensistä pispana Turussa vuoteen
1802, jolloin hän kuoli ja Jaakko Tengströmi hänen perästä tuli siihen
virkaan. Tämä erinomaisilla luonnon ja tiedon lahjoilla koristettu
mies oli syntynyt Kokkolassa Pohjanmaalla. Ennenkun tuli pispaksi,
oli hän ollut Jumaluusopin Professorina Turussa. Tällä ajalla kukoisti
tiedon tutkinto Suomen Korkiopistossa. Gadoliini ja Tengströmi olivat
siltä kohdalta kehuttavat, jälkimmäinen historiallisten ja muittenki
kirjoitustensa vuoksi. Mutta paitsi näitä löytyi monta muutaki
korkeassa arvossa pidettävätä miestä. Niistä nimitämmä ainoastaan
Professorit Porthaanin ja Kaloniuksen, joitten kuuluisat nimet ovat
ulkomaallaki kaikkuneet. Porvon hiippakunnassa, (josta Viipurin puoli
Ison Vihan perästä oli tullut jäämään Venäjän alle,) oli Johani
Getselius Pojanpoika kuollut v. 1733 ja hänen perästä Danieli
Juslenius, joka on kirjoittanut Suomalaisen Sanakirjan, tullut
pispaksi. Hän pakeni sodanaikana v. 1742 Ruotsiin ja jäi sinne. Sittä
seurasivat Johani Nylanderi (k. 1761), Gabrieli Fortelius (k. 1788),
Paavali Krogius (k. 1792) ynnä Sakharias Cygnääus Vanhempi, joka
kuoli 1809 ja sai Maunus Jaakko Alopääuksen
jälkeenseuraajaksensa. Mainitut miehet vaikuttivat, kukin taitojaan
myöten, hiippakuntansa hyväksi.
V.
Neljäs Aikakausi.