This commit is contained in:
Benjamin Qi 2020-06-22 21:00:35 -04:00
parent a8ab28fc9b
commit 84cc6bcebd
41 changed files with 551 additions and 468 deletions

View file

@ -5,6 +5,13 @@ author: Darren Yao
description: Learn about the basic data types needed for competitive programming.
---
## Additional Reading
- CPH 1.1 - 1.3
- [PAPC 2.3](http://www.csc.kth.se/~jsannemo/slask/main.pdf)
## Data Types
There are several main **data types** that are used in contests: 64-bit integers, floating point numbers, booleans, characters, and strings. Assuming that you are familiar with the language you are using, this should be mostly review.
It's a good idea to use 64-bit integers (`long long` in C++) instead of 32-bit integers (`int`). 64-bit integers are less likely to have overflow issues, since they can store any number between $-9\,223\,372\,036\,854\,775\,808$ and $9\,223\,372\,036\,854\,775\,807$ which is roughly equal to $\pm 9 \times 10^{18}$. Contest problems are usually set such that the 64-bit integer is sufficient. Of course, you shouldn't do this when time and/or memory limits are tight, which may be the case in higher divisions of USACO.
@ -16,8 +23,3 @@ It's a good idea to use 64-bit integers (`long long` in C++) instead of 32-bit i
**Character** variables represent a single Unicode character. They are returned when you access the character at a certain index within a string. Characters are represented using the ASCII standard, which assigns each character to a corresponding integer. This allows us to do arithmetic with them; for example, both `cout << ('f' - 'a');` in C++ and `System.out.print('f' - 'a');` in Java will print `5`.
**Strings** are stored as an array of characters. You can easily access the character at a certain index and take substrings of the string. String problems on USACO Bronze or Silver generally don't involve any special data structures.
## Additional Reading
- CPH 1.1 - 1.3
- [PAPC Ch 2](http://www.csc.kth.se/~jsannemo/slask/main.pdf)

View file

@ -5,6 +5,11 @@ author: Darren Yao
description: Demonstrates how to read input and print output for USACO contests.
---
## Additional Reading
- CSES 1.2
- [PAPC 2.4](http://www.csc.kth.se/~jsannemo/slask/main.pdf)
## Standard I/O
In most websites (such as CodeForces and CSES), input and output are **standard**.

View file

@ -5,7 +5,9 @@ author: Nathan Wang, Benjamin Qi, Anthony Wang
description: Options for running C++ both online and locally.
---
# Running C++ Online
Of course, please let us know if these installation instructions do not work for you.
# Using C++ Online
- [OnlineGDB](https://www.onlinegdb.com/)
- online compiler with an embedded GDB debugger
@ -21,81 +23,45 @@ description: Options for running C++ both online and locally.
You can share code with [pastebin](https://pastebin.com/) or [hastebin](https://hastebin.com/).
# Running C++ Locally
# Using an IDE
[PAPC Ch 2.1](http://www.csc.kth.se/~jsannemo/slask/main.pdf) is one option.
These often have C++ support already built-in.
## On Windows
- [Visual Studio Code](https://code.visualstudio.com/)
- lightweight, fast IDE, but requires some configuration
- see [PAPC Ch 2.1](http://www.csc.kth.se/~jsannemo/slask/main.pdf) for setup instructions
- [Visual Studio](https://visualstudio.microsoft.com/vs/)
- heavier cousin of VS Code, VS Code is better for competitive programming
- [Geany](https://www.geany.org/)
- Ben: I used at IOI
- [Codeblocks](http://www.codeblocks.org/)
- bad on Mac
- [XCode](https://developer.apple.com/xcode/)
- Mac only
- [CLion](https://www.jetbrains.com/clion/)
- requires a license, but [free for students](https://www.jetbrains.com/community/education/#students)
Like Windows in general, you have a lot of options for running C++.
# Using Command Line
The easiest option is to use an IDE such as [Codeblocks](http://www.codeblocks.org/) or [Visual Studio](https://visualstudio.microsoft.com/vs/) because they often have C++ support already built-in. See the IDEs section below for more information.
Alternatively, run C++ from the command line and use a text editor of your choice.
However, you can also use [MinGW](http://mingw.org/) if you prefer compiling and running C++ using the command line. Another good option is Windows Subsystem for Linux (WSL) which is what I personally use, although it may be more difficult to properly set up.
## Text Editors
### Installing MinGW
First, download and run the [MinGW installer](https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/). Once it's installed, open the MinGW Installation Manager, click on Basic Setup on the left, and select `mingw32-gcc-g++-bin` for installation.
[Adding MinGW to PATH](https://www.rose-hulman.edu/class/csse/resources/MinGW/installation.htm)
### Installing WSL
[VSCode Docs](https://code.visualstudio.com/docs/cpp/config-wsl) (difficult for beginners)
## On Mac
[Clang](https://en.wikipedia.org/wiki/Clang) is the default compiler for Mac OS X, but you should use [GCC](https://en.wikipedia.org/wiki/GNU_Compiler_Collection)'s g++ since that's what [USACO](http://www.usaco.org/index.php?page=instructions) uses to compile your code.
### Installation
First, open **Terminal** and familiarize yourself with some basic commands.
- [Intro to OS X Command Line](https://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line).
- [Mac Terminal Cheat Sheet](https://www.makeuseof.com/tag/mac-terminal-commands-cheat-sheet/)
You will also need to install [Homebrew](https://brew.sh/).
Run
```
brew install gcc
```
According to [this](https://stackoverflow.com/questions/30998890/installing-opencv-with-brew-never-finishes) if `brew` doesn't seem to finish for a long time then
```
brew install gcc --force-bottle
```
probably suffices.
#### Confirmation
You should be able to compile with `g++` or maybe `g++-#`, where # is the version number (currently 9). Running the following command:
```
g++-9 --version
```
should display something like this:
```
g++-9 (Homebrew GCC 9.2.0_2) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
```
#### Troubleshooting
Make sure you have installed XCode command line tools.
```
xcode-select --install # make sure x-code command line tools are installed
softwareupdate --list
softwareupdate -i -a # installs everything
```
- [Sublime Text 3](https://www.sublimetext.com/)
- fast, lightweight text editor for Windows, Mac, and Linux
- [Editing Build Settings](https://stackoverflow.com/questions/23789410/how-to-edit-sublime-text-build-settings)
- no need to do this if you just use command line to compile & run
- [FastOlympicCoding Addon](https://github.com/Jatana/FastOlympicCoding)
- see "Debugging" for another way to stress test
- [Sublime Snippets](https://www.granneman.com/webdev/editors/sublime-text/top-features-of-sublime-text/quickly-insert-text-and-code-with-sublime-text-snippets)
- Ben - I use to insert templates
- [Symlink](https://www.sublimetext.com/docs/3/osx_command_line.html)
- Ben - Using `/usr/local/bin/subl` instead of `~/bin/subl` worked for me on OS X Mojave.
- [Atom](https://atom.io/)
- another text editor for Windows, Mac, and Linux from the makers of Github
- [Vim](https://www.vim.org/)
- classic text editor, usually preinstalled on Mac and Linux, and also available for Windows
- probably easiest way to print syntax-highlighted code on Mac, see the response to [this post](https://stackoverflow.com/questions/1656914/printing-code-with-syntax-highlighting)
## On Linux
@ -107,6 +73,77 @@ whereis g++
If it is not preinstalled, you can probably install it using your distro's package manager.
## On Windows
### MinGW
One option is [MinGW](http://mingw.org/).
First, download and run the [MinGW installer](https://osdn.net/projects/mingw/downloads/68260/mingw-get-setup.exe/). Once it's installed, open the MinGW Installation Manager, click on Basic Setup on the left, and select `mingw32-gcc-g++-bin` for installation.
[Adding MinGW to PATH](https://www.rose-hulman.edu/class/csse/resources/MinGW/installation.htm)
### WSL
Another good option is Windows Subsystem for Linux (WSL) which is what I (Anthony) personally use, although it may be more difficult to properly set up.
[VSCode Docs](https://code.visualstudio.com/docs/cpp/config-wsl) (difficult for beginners)
## On Mac
[Clang](https://en.wikipedia.org/wiki/Clang) is the default compiler for Mac OS X, but you should use [GCC](https://en.wikipedia.org/wiki/GNU_Compiler_Collection)'s g++ since that's what [USACO](http://www.usaco.org/index.php?page=instructions) uses to compile your code.
### Installation
1. Open the **Terminal** application and familiarize yourself with some basic commands.
- [Intro to OS X Command Line](https://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line).
- [Mac Terminal Cheat Sheet](https://www.makeuseof.com/tag/mac-terminal-commands-cheat-sheet/)
2. Install XCode command line tools.
```
xcode-select --install
```
If you previously installed these you may need to update them:
```
softwareupdate --list # list updates
softwareupdate -i -a # installs all updates
```
3. Install [Homebrew](https://brew.sh/).
4. Install gcc with Homebrew.
```
brew install gcc
```
According to [this](https://stackoverflow.com/questions/30998890/installing-opencv-with-brew-never-finishes) if `brew` doesn't seem to finish for a long time then
```
brew install gcc --force-bottle
```
probably suffices.
5. You should be able to compile with `g++` or maybe `g++-#`, where # is the version number (ex. 9). Running the following command
```
g++-9 --version
```
should display something like this:
```
g++-9 (Homebrew GCC 9.2.0_2) 9.2.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
```
## Running With the Command Line
Consider a simple program such as the following, which we'll save in `name.cpp`.
@ -158,8 +195,8 @@ Use [compiler flags](https://developers.redhat.com/blog/2018/03/21/compiler-and-
Explanation:
- `-O2` tells `g++` to compile your code to run more quickly (see [here](https://www.rapidtables.com/code/linux/gcc/gcc-o.html))
- `-std=c++17` allows you to use features that were added to C++ in 2017. USACO uses `-std=c++11`.
- `-Wall -Wextra -Wshadow` checks your program for common errors. See "General - Debugging" for more information about these.
- `-std=c++17` allows you to use features that were added to C++ in 2017. USACO currently uses `-std=c++11`.
- `-Wall -Wextra -Wshadow` checks your program for common errors. See "General - Debugging" for more information.
- [Summary of Options](https://gcc.gnu.org/onlinedocs/gcc/Option-Summary.html)
You should always compile with these flags.
@ -187,40 +224,3 @@ run() { co $1 && ./$1 & fg; }
```
Now you can easily compile and run `name.cpp` from the command line with `co name && ./name` or `run name`. Note that all occurrences of `$1` in the function are replaced with `name`.
# Tools
## IDEs
- [Geany](https://www.geany.org/)
- [Visual Studio Code](https://code.visualstudio.com/)
- lightweight, fast IDE, but requires some configuration
- [Visual Studio](https://visualstudio.microsoft.com/vs/)
- heavier cousin of Visual Studio Code, VS Code is better for competitive programming
- [XCode](https://developer.apple.com/xcode/)
- Mac only
- [Codeblocks](http://www.codeblocks.org/)
- bad on Mac
- [CLion](https://www.jetbrains.com/clion/)
- requires a license, but [free for students](https://www.jetbrains.com/community/education/#students)
## Text Editors
Run with the command line.
- [Sublime Text 3](https://www.sublimetext.com/)
- fast, lightweight text editor for Windows, Mac, and Linux
- [Editing Build Settings](https://stackoverflow.com/questions/23789410/how-to-edit-sublime-text-build-settings)
- no need to do this if you just use command line to compile & run
- [FastOlympicCoding Addon](https://github.com/Jatana/FastOlympicCoding)
- see "Debugging" for another way to stress test
- [Sublime Snippets](https://www.granneman.com/webdev/editors/sublime-text/top-features-of-sublime-text/quickly-insert-text-and-code-with-sublime-text-snippets)
- Ben - I use to insert templates
- [Symlink](https://www.sublimetext.com/docs/3/osx_command_line.html)
- Ben - Using `/usr/local/bin/subl` instead of `~/bin/subl` worked for me on OS X Mojave.
- [Atom](https://atom.io/)
- another text editor for Windows, Mac, and Linux from the makers of Github
- [Vim](https://www.vim.org/)
- classic text editor, usually preinstalled on Mac and Linux, and also available for Windows
- probably easiest way to print syntax-highlighted code on Mac, see the response to [this post](https://stackoverflow.com/questions/1656914/printing-code-with-syntax-highlighting)
- Others?

View file

@ -5,59 +5,66 @@ author: Benjamin Qi
description: A bunch of helpful links.
---
Some resources (such as **CPH** and **Intro to USACO**) will be mentioned extensively in later modules.
## Lists
* [USACO Resources Page](http://www.usaco.org/index.php?page=resources)
* [Awesome List (Inishan)](http://codeforces.com/blog/entry/23054)
- [Awesome List (Inishan)](http://codeforces.com/blog/entry/23054)
- [USACO Resources Page](http://www.usaco.org/index.php?page=resources)
- some links (ex. in "Other Contests") are outdated
## Books
* [Competitive Programmer's Handbook (CPH)](https://cses.fi/book/book.pdf)
* The [CSES problemset](https://cses.fi/problemset/) (now at 200 problems) is quite good!
* [Guide to Competitive Programming](https://www.amazon.com/Guide-Competitive-Programming-Algorithms-Undergraduate/dp/3319725467) is a paid book based off CPH
* Can currently download PDF for [free](https://link.springer.com/book/10.1007/978-3-319-72547-5)!
* Intro to USACO (Darren Yao)
* Bronze, Silver
* [Java](http://darrenyao.com/usacobook/java.pdf)
* [C++](http://darrenyao.com/usacobook/cpp.pdf)
* Competitive Programming Book (Steven, Felix)
* [Competitive Programming Book 1](http://www.comp.nus.edu.sg/~stevenha/myteaching/competitive_programming/cp1.pdf) is freely available but old
* [Competitive Programming 4](https://cpbook.net/) is the latest edition of the book (with significant additions) but costs money.
* Release date is July 19th, 2020.
* [Principles of Algorithmic Problem Solving (PAPS)](http://www.csc.kth.se/~jsannemo/slask/main.pdf)
* [Samuel Hsiang - CS Guide](https://github.com/alwayswimmin/cs_guide)
* [TJSCT](https://activities.tjhsst.edu/sct/)
* [TJIOI](https://github.com/tjsct/tjioi-study-guide)
* [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/)
* good book specifically for programming interviews
- [Competitive Programmer's Handbook](https://cses.fi/book/book.pdf) (CPH) - Antti Laaksonen
- The [CSES problemset](https://cses.fi/problemset/) (now at 200 problems) is quite good!
- *Will be mentioned extensively in later modules.*
- [Guide to Competitive Programming](https://www.amazon.com/Guide-Competitive-Programming-Algorithms-Undergraduate/dp/3319725467) is a paid book based off CPH
- Can currently download PDF for [free](https://link.springer.com/book/10.1007/978-3-319-72547-5)!
- Intro to USACO - Darren Yao
- Bronze, Silver
- [Java](http://darrenyao.com/usacobook/java.pdf)
- [C++](http://darrenyao.com/usacobook/cpp.pdf)
- *Some modules are from this book.*
- Competitive Programming Book - Steven Halim, Felix Halim
- [Competitive Programming Book 1](http://www.comp.nus.edu.sg/~stevenha/myteaching/competitive_programming/cp1.pdf) is freely available but old
- [Competitive Programming 4](https://cpbook.net/) is the latest edition of the book (with significant additions) but costs money.
- Release date is July 19th, 2020.
- [CS Guide](https://github.com/alwayswimmin/cs_guide) - Samuel Hsiang, Alexander Wei, Yang Liu
- Also see the following from TJHSST:
- [TJ Senior Computer Team](https://activities.tjhsst.edu/sct/)
- [TJIOI](https://github.com/tjsct/tjioi-study-guide)
- some basics
- [Principles of Algorithmic Problem Solving](http://www.csc.kth.se/~jsannemo/slask/main.pdf) - Johan Sannemo
- practice problems from Kattis
- [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/)
- good book specifically for programming interviews
## Courses
* [Competitive Programming Course (SuprDewd)](https://github.com/SuprDewd/T-414-AFLV)
* [Cousera Algorithms Pt 1 (and Pt 2)](https://www.coursera.org/learn/algorithms-part1)
* [Carnegie-Mellon ICPC Course](https://contest.cs.cmu.edu/295/f17/)
* topic-specific contests in CF group
## Algorithm Collections
* [CSAcademy](https://csacademy.com/lessons/)
* [cp-algorithms](https://cp-algorithms.com/)
* [KTH ICPC Team Reference (KACTL)](https://github.com/kth-competitive-programming/kactl)
* [Topcoder Data Science Tutorials](http://www.topcoder.com/community/data-science/data-science-tutorials/)
* [List of CF Tutorials](http://codeforces.com/blog/entry/57282)
## By USACO Finalists
- [VPlanet](https://www.vplanetcoding.com/courses)
- Riya Arora
- [Competitive Programming Course](https://github.com/SuprDewd/T-414-AFLV) - Bjarki Ágúst Guðmundsson
- practice problems from Kattis
- [Carnegie-Mellon ICPC Course](https://contest.cs.cmu.edu/295/f17/) - Danny Sleator
- topic-specific contests in CF group
- [VPlanet](https://www.vplanetcoding.com/courses) - Riya Arora
- courses for various levels
- [ekzlib](http://ekzlib.herokuapp.com)
- Eric Zhang
- (advanced) implementations
- [bqi343 USACO Github](https://github.com/bqi343/USACO)
- Benjamin Qi
- implementations
- [Cousera Algorithms Pt 1 (and Pt 2)](https://www.coursera.org/learn/algorithms-part1) - Kevin Wayne, Robert Sedgewick
- Java
## Tutorials
- [cp-algorithms](https://cp-algorithms.com/) (E-Maxx Eng)
- many
- [Topcoder Data Science Tutorials](http://www.topcoder.com/community/data-science/data-science-tutorials/)
- many, format is not always great
- [CSAcademy](https://csacademy.com/lessons/)
- few (but nice) lessons
- [List of CF Tutorials](http://codeforces.com/blog/entry/57282)
- many
## Implementations
- [KTH ICPC Team Reference (KACTL)](https://github.com/kth-competitive-programming/kactl)
- ICPC book
- past USACO solutions
- [USACO Github](https://github.com/bqi343/USACO) - Benjamin Qi
- ICPC book
- past USACO solutions
- [ekzlib](http://ekzlib.herokuapp.com) - Eric Zhang
- (advanced) implementations

View file

@ -5,6 +5,12 @@ author: Darren Yao
description: In many problems (especially in Bronze) it suffices to check all possible cases in the solution space.
---
## Additional Reading
- CPH 5.1 - 5.3 (Complete Search)
# Complete Search
In many problems (especially in Bronze) it suffices to check all possible cases in the solution space, whether it be all elements, all pairs of elements, or all subsets, or all permutations. Unsurprisingly, this is called **complete search** (or **brute force**), because it completely searches the entire solution space.
## Example 1

View file

@ -5,6 +5,13 @@ author: Darren Yao
description: Introduces C++ containers that are frequently used in competitive programming.
---
## Additional Resources
- CPH 4 (Data Structures)
- [PAPS 3.1, 3.5, 6.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
# Data Structures
A **data structure** determines how data is stored (is it sorted? indexed? what operations does it support?). Each data structure supports some operations efficiently, while other operations are either inefficient or not supported at all.
The C++ [standard library data structures](http://www.cplusplus.com/reference/stl/) are designed to store any type of data. We put the desired data type within the `<>` brackets when declaring the data structure, as follows:
@ -98,41 +105,116 @@ for(auto element : v) {
}
```
## Stacks and the Various Types of Queues
## Sets and Maps
### [Stacks](http://www.cplusplus.com/reference/stack/stack/)
A set is a collection of objects that contains no duplicates. There are two types of sets: unordered sets (`unordered_set` in C++), and ordered set (`set` in C++).
A stack is a **Last In First Out** (LIFO) data structure that supports three operations, all in $O(1)$ time:
### Unordered Sets
- `push`: adds an element to the top of the stack
- `pop`: removes an element from the top of the stack
- `top`: retrieves the element at the top without removing it
Think of it like a real-world stack of papers (or cards).
The unordered set works by hashing, which is assigning a unique code to every variable/object which allows insertions, deletions, and searches in $O(1)$ time, albeit with a high constant factor, as hashing requires a large constant number of operations. However, as the name implies, elements are not ordered in any meaningful way, so traversals of an unordered set will return elements in some arbitrary order. The operations on an unordered set are `insert`, which adds an element to the set if not already present, `erase`, which deletes an element if it exists, and `count`, which returns 1 if the set contains the element and 0 if it doesn't.
```cpp
stack<int> s;
s.push(1); // [1]
s.push(13); // [1, 13]
s.push(7); // [1, 13, 7]
cout << s.top() << endl; // 7
s.pop(); // [1, 13]
cout << s.size() << endl; // 2
unordered_set<int> s;
s.insert(1); // [1]
s.insert(4); // [1, 4] in arbitrary order
s.insert(2); // [1, 4, 2] in arbitrary order
s.insert(1); // [1, 4, 2] in arbitrary order
// the add method did nothing because 1 was already in the set
cout << s.count(1) << endl; // 1
set.erase(1); // [2, 4] in arbitrary order
cout << s.count(5) << endl; // 0
s.erase(0); // [2, 4] in arbitrary order
// if the element to be removed does not exist, nothing happens
for(int element : s){
cout << element << " ";
}
cout << endl;
// You can iterate through an unordered set, but it will do so in arbitrary order
```
### [Queues](http://www.cplusplus.com/reference/queue/queue/ )
### [Ordered Sets](http://www.cplusplus.com/reference/set/set/)
A queue is a First In First Out (FIFO) data structure that supports three operations, all in $O(1)$ time.
- `push`: insertion at the back of the queue
- `pop`, deletion from the front of the queue
- `front`: which retrieves the element at the front without removing it.
The second type of set data structure is the ordered or sorted set. Insertions, deletions, and searches on the ordered set require $O(\log n)$ time, based on the number of elements in the set. As well as those supported by the unordered set, the ordered set also allows four additional operations: `begin()`, which returns an iterator to the lowest element in the set, `end()`, which returns an iterator to the highest element in the set, `lower_bound`, which returns an iterator to the least element greater than or equal to some element `k`, and `upper_bound`, which returns an iterator to the least element strictly greater than some element `k`.
```cpp
queue<int> q;
q.push(1); // [1]
q.push(3); // [3, 1]
q.push(4); // [4, 3, 1]
q.pop(); // [4, 3]
cout << q.front() << endl; // 3
set<int> s;
s.insert(1); // [1]
s.insert(14); // [1, 14]
s.insert(9); // [1, 9, 14]
s.insert(2); // [1, 2, 9, 14]
cout << *s.upper_bound(7) << '\n'; // 9
cout << *s.upper_bound(9) << '\n'; // 14
cout << *s.lower_bound(5) << '\n'; // 9
cout << *s.lower_bound(9) << '\n'; // 9
cout << *s.begin() << '\n'; // 1
auto it = s.end();
cout << *(--it) << '\n'; // 14
s.erase(s.upper_bound(6)); // [1, 2, 14]
```
The primary limitation of the ordered set is that we can't efficiently access the $k^{th}$ largest element in the set, or find the number of elements in the set greater than some arbitrary $x$. These operations can be handled using a data structure called an order statistic tree (see Gold - Binary Indexed Trees).
### [Maps](http://www.cplusplus.com/reference/map/map/)
A map is a set of ordered pairs, each containing a key and a value. In a map, all keys are required to be unique, but values can be repeated. Maps have three primary methods: one to add a specified key-value pairing, one to retrieve the value for a given key, and one to remove a key-value pairing from the map. Like sets, maps can be unordered (`unordered_map` in C++) or ordered (`map` in C++). In an unordered map, hashing is used to support $O(1)$ operations. In an ordered map, the entries are sorted in order of key. Operations are $O(\log n)$, but accessing or removing the next key higher or lower than some input `k` is also supported.
### Unordered Maps
In an unordered map `m`, the `m[key] = value` operator assigns a value to a key and places the key and value pair into the map. The operator `m[key]` returns the value associated with the key. If the key is not present in the map, then `m[key]` is set to 0. The `count(key)` method returns the number of times the key is in the map (which is either one or zero), and therefore checks whether a key exists in the map. Lastly, `erase(key)` and `erase(it)` removes the map entry associated with the specified key or iterator. All of these operations are $O(1)$, but again, due to the hashing, this has a high constant factor.
```cpp
unordered_map<int, int> m;
m[1] = 5; // [(1, 5)]
m[3] = 14; // [(1, 5); (3, 14)]
m[2] = 7; // [(1, 5); (3, 14); (2, 7)]
m.erase(2); // [(1, 5); (3, 14)]
cout << m[1] << '\n'; // 5
cout << m.count(7) << '\n' ; // 0
cout << m.count(1) << '\n' ; // 1
```
### Ordered Maps
The ordered map supports all of the operations that an unordered map supports, and additionally supports `lower_bound` and `upper_bound`, returning the iterator pointing to the lowest entry not less than the specified key, and the iterator pointing to the lowest entry strictly greater than the specified key respectively.
```cpp
map<int, int> m;
m[3] = 5; // [(3, 5)]
m[11] = 4; // [(3, 5); (11, 4)]
m[10] = 491; // [(3, 5); (10, 491); (11, 4)]
cout << m.lower_bound(10)->first << " " << m.lower_bound(10)->second << '\n'; // 10 491
cout << m.upper_bound(10)->first << " " << m.upper_bound(10)->second << '\n'; // 11 4
m.erase(11); // [(3, 5); (10, 491)]
if (m.upper_bound(10) == m.end())
{
cout << "end" << endl; // Prints end
}
```
A note on unordered sets and maps: In USACO contests, they're generally fine, but in CodeForces contests, you should always use sorted sets and maps. This is because the built-in hashing algorithm is vulnerable to pathological data sets causing abnormally slow runtimes, in turn causing failures on some test cases (see [neal's blog](https://codeforces.com/blog/entry/62393)). Alternatively, use a different hashing algorithm.
### [Multisets](http://www.cplusplus.com/reference/set/multiset/)
Lastly, there is the multiset, which is essentially a sorted set that allows multiple copies of the same element. In addition to all of the regular set operations, the multiset `count()` method returns the number of times an element is present in the multiset. (Actually, you shouldn't use `count()` because this takes time **linear** in the number of matches.)
The `begin()`, `end()`, `lower_bound()`, and `upper_bound()` operations work the same way they do in the normal sorted set.
**Warning:** If you want to remove a value *once*, make sure to use `multiset.erase(multiset.find(val))` rather than `multiset.erase(val)`. The latter will remove *all* instances of `val`.
```cpp
multiset<int> ms;
ms.insert(1); // [1]
ms.insert(14); // [1, 14]
ms.insert(9); // [1, 9, 14]
ms.insert(2); // [1, 2, 9, 14]
ms.insert(9); // [1, 2, 9, 9, 14]
ms.insert(9); // [1, 2, 9, 9, 9, 14]
cout << ms.count(4) << '\n'; // 0
cout << ms.count(9) << '\n'; // 3
cout << ms.count(14) << '\n'; // 1
ms.erase(ms.find(9));
cout << ms.count(9) << '\n'; // 2
ms.erase(9);
cout << ms.count(9) << '\n'; // 0
```

View file

@ -15,8 +15,9 @@ Both of these will be covered in Silver. For now, it suffices to learn how graph
## Tutorial
- Recommended
- CPH 11
- CPH 11 (Basics of graphs)
- Intro to USACO 10.1 - 10.3
- [PAPS 6.4](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [CSAcademy Graph Intro](https://csacademy.com/lesson/introduction_to_graphs)
- [CSAcademy Graph Representations](https://csacademy.com/lesson/graph_representation)
- Usually, adjacency lists are used.

View file

@ -73,65 +73,6 @@ In order to sort a static or dynamic array, use `Arrays.sort(arr)` or `Collectio
In array-based contest problems, we'll use one-, two-, and three-dimensional static arrays most of the time. However, we can also have static arrays of dynamic arrays, dynamic arrays of static arrays, and so on. Usually, the choice between a static array and a dynamic array is just personal preference.
## Stacks and the Various Types of Queues
### Stacks
A stack is a **Last In First Out** (LIFO) data structure that supports three operations: `push`, which adds an element to the top of the stack, `pop`, which removes an element from the top of the stack, and `peek`, which retrieves the element at the top without removing it, all in $O(1)$ time. Think of it like a real-world stack of papers (or cards).
```java
Stack<Integer> s = new Stack<Integer>();
s.push(1); // [1]
s.push(13); // [1, 13]
s.push(7); // [1, 13, 7]
System.out.println(s.peek()); // 7
s.pop(); // [1, 13]
System.out.println(s.size()); // 2
```
### Queues
A queue is a First In First Out (FIFO) data structure that supports three operations of `add`, insertion at the back of the queue, `poll`, deletion from the front of the queue, and `peek`, which retrieves the element at the front without removing it, all in $O(1)$ time. Java doesn't actually have a `Queue` class; it's only an interface. The most commonly used implementation is the `LinkedList`, declared as follows:
```java
Queue<Integer> q = new LinkedList<Integer>();
q.add(1); // [1]
q.add(3); // [3, 1]
q.add(4); // [4, 3, 1]
q.poll(); // [4, 3]
System.out.println(q.peek()); // 3
```
### Deques
A deque (usually pronounced “deck”) stands for double ended queue and is a combination of a stack and a queue, in that it supports $O(1)$ insertions and deletions from both the front and the back of the deque. In Java, the deque class is called `ArrayDeque`. The four methods for adding and removing are `addFirst` , `removeFirst`, `addLast`, and `removeLast`.
```java
ArrayDeque<Integer> deque = new ArrayDeque<Integer>();
deque.addFirst(3); // [3]
deque.addFirst(4); // [4, 3]
deque.addLast(7); // [4, 3, 7]
deque.removeFirst(); // [3, 7]
deque.addFirst(1); // [1, 3, 7]
deque.removeLast(); // [1, 3]
```
### Priority Queues
A priority queue supports the following operations: insertion of elements, deletion of the element considered lowest priority, and retrieval of the lowest priority element, all in $O(\log n)$ time according to the number of elements in the priority queue. Priority is based on a comparator function, but by default the lowest element is at the front of the priority queue. The priority queue is one of the most important data structures in competitive programming, so make sure you understand how and when to use it.
```java
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(7); // [7]
pq.add(2); // [7, 2]
pq.add(1); // [7, 2, 1]
pq.add(5); // [7, 5, 2, 1]
System.out.println(pq.peek()); // 1
pq.poll(); // [7, 5, 2]
pq.poll(); // [7, 5]
pq.add(6); // [7, 6, 5]
```
## Sets & Maps
A set is a collection of objects that contains no duplicates. There are two types of sets: unordered sets (`HashSet` in Java), and ordered set (`TreeSet` in Java).

View file

@ -5,6 +5,13 @@ author: Darren Yao, Benjamin Qi
description: Measuring how long your algorithm takes to run in terms of the input size.
---
## Additional Resources
- CPH 2 (Time Complexity)
- [PAPS 5](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
# Time Complexity
In programming contests, your program needs to finish running within a certain timeframe in order to receive credit. For USACO, this limit is $4$ seconds for Java submissions. A conservative estimate for the number of operations the grading server can handle per second is $10^8$ (but could be closer to $5 \cdot 10^8$ given good constant factors).
(define time complexity?)
@ -137,9 +144,4 @@ Here are conservative upper bounds on the value of $n$ for each time complexity.
| $n \le 5 \cdot 10^6$ | $O(n)$ |
| $n \le 10^{18}$ | $O(\log^2 n)$, $O(\log n)$, $O(1)$ |
## Other Resources
- CPH 2

View file

@ -7,13 +7,14 @@ prerequisites:
description: Traversing a graph in a way such that vertices closer to the starting vertex are processed first.
---
Note that this is **not** required for silver.
Note that this is **not** required for silver, but it's good to learn along with DFS.
- [CSES Message Route](https://cses.fi/problemset/task/1667)
### Tutorial
- CSES 12.2
- CPH 12.2
- [PAPS 12.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [CSAcademy BFS](https://csacademy.com/lesson/breadth_first_search)
- [cp-algo BFS](https://cp-algorithms.com/graph/breadth-first-search.html)
- [cp-algo 0/1 BFS](https://cp-algorithms.com/graph/01_bfs.html)
@ -21,7 +22,7 @@ Note that this is **not** required for silver.
### Problems
- USACO
- USACO Gold
- [Monsters](https://cses.fi/problemset/task/1194)
- [Cow Navigation](http://www.usaco.org/index.php?page=viewproblem2&cpid=695)
- [Dream](http://www.usaco.org/index.php?page=viewproblem2&cpid=575)

View file

@ -1,150 +0,0 @@
---
id: containers-silver
title: Built-In C++ Containers (Silver)
author: Darren Yao
---
### [Deques](http://www.cplusplus.com/reference/deque/deque/)
A deque (usually pronounced "deck") stands for double ended queue and is a combination of a stack and a queue, in that it supports $O(1)$ insertions and deletions from both the front and the back of the deque. The four methods for adding and removing are `push_back`, `pop_back`, `push_front`, and `pop_front`. Not very common in Bronze / Silver.
```cpp
deque<int> d;
d.push_front(3); // [3]
d.push_front(4); // [4, 3]
d.push_back(7); // [4, 3, 7]
d.pop_front(); // [3, 7]
d.push_front(1); // [1, 3, 7]
d.pop_back(); // [1, 3]
```
### [Priority Queues](http://www.cplusplus.com/reference/queue/priority_queue/)
A priority queue supports the following operations: insertion of elements, deletion of the element considered highest priority, and retrieval of the highest priority element, all in $O(\log n)$ time according to the number of elements in the priority queue. Priority is based on a comparator function, but by default the highest element is at the top of the priority queue. The priority queue is one of the most important data structures in competitive programming, so make sure you understand how and when to use it.
```cpp
priority_queue<int> pq;
pq.push(7); // [7]
pq.push(2); // [2, 7]
pq.push(1); // [1, 2, 7]
pq.push(5); // [1, 2, 5, 7]
cout << pq.top() << endl; // 7
pq.pop(); // [1, 2, 5]
pq.pop(); // [1, 2]
pq.push(6); // [1, 2, 6]
```
## Sets and Maps
A set is a collection of objects that contains no duplicates. There are two types of sets: unordered sets (`unordered_set` in C++), and ordered set (`set` in C++).
### Unordered Sets
The unordered set works by hashing, which is assigning a unique code to every variable/object which allows insertions, deletions, and searches in $O(1)$ time, albeit with a high constant factor, as hashing requires a large constant number of operations. However, as the name implies, elements are not ordered in any meaningful way, so traversals of an unordered set will return elements in some arbitrary order. The operations on an unordered set are `insert`, which adds an element to the set if not already present, `erase`, which deletes an element if it exists, and `count`, which returns 1 if the set contains the element and 0 if it doesn't.
```cpp
unordered_set<int> s;
s.insert(1); // [1]
s.insert(4); // [1, 4] in arbitrary order
s.insert(2); // [1, 4, 2] in arbitrary order
s.insert(1); // [1, 4, 2] in arbitrary order
// the add method did nothing because 1 was already in the set
cout << s.count(1) << endl; // 1
set.erase(1); // [2, 4] in arbitrary order
cout << s.count(5) << endl; // 0
s.erase(0); // [2, 4] in arbitrary order
// if the element to be removed does not exist, nothing happens
for(int element : s){
cout << element << " ";
}
cout << endl;
// You can iterate through an unordered set, but it will do so in arbitrary order
```
### [Ordered Sets](http://www.cplusplus.com/reference/set/set/)
The second type of set data structure is the ordered or sorted set. Insertions, deletions, and searches on the ordered set require $O(\log n)$ time, based on the number of elements in the set. As well as those supported by the unordered set, the ordered set also allows four additional operations: `begin()`, which returns an iterator to the lowest element in the set, `end()`, which returns an iterator to the highest element in the set, `lower_bound`, which returns an iterator to the least element greater than or equal to some element `k`, and `upper_bound`, which returns an iterator to the least element strictly greater than some element `k`.
```cpp
set<int> s;
s.insert(1); // [1]
s.insert(14); // [1, 14]
s.insert(9); // [1, 9, 14]
s.insert(2); // [1, 2, 9, 14]
cout << *s.upper_bound(7) << '\n'; // 9
cout << *s.upper_bound(9) << '\n'; // 14
cout << *s.lower_bound(5) << '\n'; // 9
cout << *s.lower_bound(9) << '\n'; // 9
cout << *s.begin() << '\n'; // 1
auto it = s.end();
cout << *(--it) << '\n'; // 14
s.erase(s.upper_bound(6)); // [1, 2, 14]
```
The primary limitation of the ordered set is that we can't efficiently access the $k^{th}$ largest element in the set, or find the number of elements in the set greater than some arbitrary $x$. These operations can be handled using a data structure called an order statistic tree (see Gold - Binary Indexed Trees).
### [Maps](http://www.cplusplus.com/reference/map/map/)
A map is a set of ordered pairs, each containing a key and a value. In a map, all keys are required to be unique, but values can be repeated. Maps have three primary methods: one to add a specified key-value pairing, one to retrieve the value for a given key, and one to remove a key-value pairing from the map. Like sets, maps can be unordered (`unordered_map` in C++) or ordered (`map` in C++). In an unordered map, hashing is used to support $O(1)$ operations. In an ordered map, the entries are sorted in order of key. Operations are $O(\log n)$, but accessing or removing the next key higher or lower than some input `k` is also supported.
### Unordered Maps
In an unordered map `m`, the `m[key] = value` operator assigns a value to a key and places the key and value pair into the map. The operator `m[key]` returns the value associated with the key. If the key is not present in the map, then `m[key]` is set to 0. The `count(key)` method returns the number of times the key is in the map (which is either one or zero), and therefore checks whether a key exists in the map. Lastly, `erase(key)` and `erase(it)` removes the map entry associated with the specified key or iterator. All of these operations are $O(1)$, but again, due to the hashing, this has a high constant factor.
```cpp
unordered_map<int, int> m;
m[1] = 5; // [(1, 5)]
m[3] = 14; // [(1, 5); (3, 14)]
m[2] = 7; // [(1, 5); (3, 14); (2, 7)]
m.erase(2); // [(1, 5); (3, 14)]
cout << m[1] << '\n'; // 5
cout << m.count(7) << '\n' ; // 0
cout << m.count(1) << '\n' ; // 1
```
### Ordered Maps
The ordered map supports all of the operations that an unordered map supports, and additionally supports `lower_bound` and `upper_bound`, returning the iterator pointing to the lowest entry not less than the specified key, and the iterator pointing to the lowest entry strictly greater than the specified key respectively.
```cpp
map<int, int> m;
m[3] = 5; // [(3, 5)]
m[11] = 4; // [(3, 5); (11, 4)]
m[10] = 491; // [(3, 5); (10, 491); (11, 4)]
cout << m.lower_bound(10)->first << " " << m.lower_bound(10)->second << '\n'; // 10 491
cout << m.upper_bound(10)->first << " " << m.upper_bound(10)->second << '\n'; // 11 4
m.erase(11); // [(3, 5); (10, 491)]
if (m.upper_bound(10) == m.end())
{
cout << "end" << endl; // Prints end
}
```
A note on unordered sets and maps: In USACO contests, they're generally fine, but in CodeForces contests, you should always use sorted sets and maps. This is because the built-in hashing algorithm is vulnerable to pathological data sets causing abnormally slow runtimes, in turn causing failures on some test cases (see [neal's blog](https://codeforces.com/blog/entry/62393)). Alternatively, use a different hashing algorithm.
### [Multisets](http://www.cplusplus.com/reference/set/multiset/)
Lastly, there is the multiset, which is essentially a sorted set that allows multiple copies of the same element. In addition to all of the regular set operations, the multiset `count()` method returns the number of times an element is present in the multiset. (Actually, you shouldn't use `count()` because this takes time **linear** in the number of matches.)
The `begin()`, `end()`, `lower_bound()`, and `upper_bound()` operations work the same way they do in the normal sorted set.
**Warning:** If you want to remove a value *once*, make sure to use `multiset.erase(multiset.find(val))` rather than `multiset.erase(val)`. The latter will remove *all* instances of `val`.
```cpp
multiset<int> ms;
ms.insert(1); // [1]
ms.insert(14); // [1, 14]
ms.insert(9); // [1, 9, 14]
ms.insert(2); // [1, 2, 9, 14]
ms.insert(9); // [1, 2, 9, 9, 14]
ms.insert(9); // [1, 2, 9, 9, 9, 14]
cout << ms.count(4) << '\n'; // 0
cout << ms.count(9) << '\n'; // 3
cout << ms.count(14) << '\n'; // 1
ms.erase(ms.find(9));
cout << ms.count(9) << '\n'; // 2
ms.erase(9);
cout << ms.count(9) << '\n'; // 0
```

View file

@ -14,7 +14,8 @@ description: A way to traverse a graph using recursion.
### Tutorial
- Recommended:
- CPH 12.1
- CPH 12.1 (DFS), 14 (Tree algorithms)
- [PAPS 12.2](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [CSAcademy DFS](https://csacademy.com/lesson/depth_first_search/)
- Additional:
- [CPC.7](https://github.com/SuprDewd/T-414-AFLV/tree/master/07_graphs_1)
@ -26,6 +27,8 @@ description: A way to traverse a graph using recursion.
- CSES Trees
- [Subordinates](https://cses.fi/problemset/task/1674)
- Tree Traversal
- [Tree Diameter](https://cses.fi/problemset/task/1131)
- [Tree Distances I](https://cses.fi/problemset/task/1132)
- [Tree Distances II](https://cses.fi/problemset/task/1133)
- CF
@ -49,7 +52,8 @@ description: A way to traverse a graph using recursion.
- [POI Hotels](https://szkopul.edu.pl/problemset/problem/gDw3iFkeVm7ZA3j_16-XR7jI/site/?key=statement) [](61)
- [Kattis Birthday Party (Easy)](https://open.kattis.com/problems/birthday)
- DFS with each edge removed
- [CSA Tree Construction](https://csacademy.com/contest/archive/task/tree-construct)
- several cases
## Graph Two-Coloring
@ -60,6 +64,8 @@ The most common example of a two-colored graph is a *bipartite graph*, in which
### Tutorial
- CPH 12.3
The idea is that we can arbitrarily label a node and then run DFS. Every time we visit a new (unvisited) node, we set its color based on the edge rule. When we visit a previously visited node, check to see whether its color matches the edge rule. For example, an implementation of coloring a bipartite graph is shown below.
```cpp

View file

@ -7,15 +7,18 @@ prerequisites:
description: Greedy algorithms select the optimal choice at each step instead of looking at the solution space as a whole. This reduces the problem to a smaller problem at each step.
---
## Additional Reading
- CPH 6
- [PAPS 8](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [CPC.5](https://github.com/SuprDewd/T-414-AFLV/tree/master/05_greedy_algorithms)
# Greedy
Greedy does not refer to a single algorithm, but rather a way of thinking that is applied to problems. There's no one way to do greedy algorithms. Hence, we use a selection of well-known examples to help you understand the greedy paradigm.
Usually, when using a greedy algorithm, there is a heuristic or value function that determines which choice is considered most optimal. Usually (but not always) some sorting step is involved.
## Additional Resources
- CPH 6
- [CPC.5](https://github.com/SuprDewd/T-414-AFLV/tree/master/05_greedy_algorithms)
## Example: Studying Algorithms
### Statement

View file

@ -9,7 +9,8 @@ description: Introduces sorting and binary searching on a sorted array.
## Additional Resources
- CPH 3 (once again, very good)
- CPH 3 (Sorting)
- once again, very good
## Sorting Algorithms

View file

@ -1,16 +1,17 @@
---
id: data-structures
title: "Data Structures"
id: maps-sets
title: "More With Maps & Sets"
author: Unknown
prerequisites:
- Bronze - Data Structures
description: More practice with data structures introduced in bronze, and some new ones.
description: "More with iterators?"
---
(set iterators?)
## USACO Problems
- [CSES Bit Inversions](https://cses.fi/problemset/task/1188/)
- Silver
- [Cities & States](http://usaco.org/index.php?page=viewproblem2&cpid=667)
- [Milk Measurement](http://usaco.org/index.php?page=viewproblem2&cpid=763)
@ -19,4 +20,3 @@ description: More practice with data structures introduced in bronze, and some n
- [Snow Boots](http://www.usaco.org/index.php?page=viewproblem2&cpid=813)
- [Springboards](http://www.usaco.org/index.php?page=viewproblem2&cpid=995)
- hard?
- [CSES Bit Inversions](https://cses.fi/problemset/task/1188/)

View file

@ -15,6 +15,7 @@ Let's say we have a one-indexed integer array $\texttt{arr}$ of size $N$ and we
## Additional Resources
- CPH 9.1
- [PAPS 11.2.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
## Tutorial

View file

@ -0,0 +1,155 @@
---
id: stacks-queues
title: Stacks & Queues
author: Darren Yao
description:
prerequisites:
- Bronze - Data Structures
---
## Additional Reading
- CPH 4.5
- [PAPS 3.2 3.3, 3.4, 6.2, 6.3, 6.5](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
## [Stacks](http://www.cplusplus.com/reference/stack/stack/)
A stack is a **Last In First Out** (LIFO) data structure that supports three operations, all in $O(1)$ time. Think of it like a real-world stack of papers (or cards).
### C++
- `push`: adds an element to the top of the stack
- `pop`: removes an element from the top of the stack
- `top`: retrieves the element at the top without removing it
```cpp
stack<int> s;
s.push(1); // [1]
s.push(13); // [1, 13]
s.push(7); // [1, 13, 7]
cout << s.top() << endl; // 7
s.pop(); // [1, 13]
cout << s.size() << endl; // 2
```
### Java
- `push`: adds an element to the top of the stack
- `pop`: removes an element from the top of the stack
- `peek`: retrieves the element at the top without removing it
```java
Stack<Integer> s = new Stack<Integer>();
s.push(1); // [1]
s.push(13); // [1, 13]
s.push(7); // [1, 13, 7]
System.out.println(s.peek()); // 7
s.pop(); // [1, 13]
System.out.println(s.size()); // 2
```
## [Queues](http://www.cplusplus.com/reference/queue/queue/)
A queue is a First In First Out (FIFO) data structure that supports three operations, all in $O(1)$ time.
### C++
- `push`: insertion at the back of the queue
- `pop`, deletion from the front of the queue
- `front`: which retrieves the element at the front without removing it.
```cpp
queue<int> q;
q.push(1); // [1]
q.push(3); // [3, 1]
q.push(4); // [4, 3, 1]
q.pop(); // [4, 3]
cout << q.front() << endl; // 3
```
### Java
- `add`: insertion at the back of the queue
- `poll`: deletion from the front of the queue
- `peek`, which retrieves the element at the front without removing it
Java doesn't actually have a `Queue` class; it's only an interface. The most commonly used implementation is the `LinkedList`, declared as follows:
```java
Queue<Integer> q = new LinkedList<Integer>();
q.add(1); // [1]
q.add(3); // [3, 1]
q.add(4); // [4, 3, 1]
q.poll(); // [4, 3]
System.out.println(q.peek()); // 3
```
## [Deques](http://www.cplusplus.com/reference/deque/deque/)
A deque (usually pronounced "deck") stands for double ended queue and is a combination of a stack and a queue, in that it supports $O(1)$ insertions and deletions from both the front and the back of the deque. Not very common in Bronze / Silver.
### C++
The four methods for adding and removing are `push_back`, `pop_back`, `push_front`, and `pop_front`.
```cpp
deque<int> d;
d.push_front(3); // [3]
d.push_front(4); // [4, 3]
d.push_back(7); // [4, 3, 7]
d.pop_front(); // [3, 7]
d.push_front(1); // [1, 3, 7]
d.pop_back(); // [1, 3]
```
### Java
In Java, the deque class is called `ArrayDeque`. The four methods for adding and removing are `addFirst` , `removeFirst`, `addLast`, and `removeLast`.
```java
ArrayDeque<Integer> deque = new ArrayDeque<Integer>();
deque.addFirst(3); // [3]
deque.addFirst(4); // [4, 3]
deque.addLast(7); // [4, 3, 7]
deque.removeFirst(); // [3, 7]
deque.addFirst(1); // [1, 3, 7]
deque.removeLast(); // [1, 3]
```
## [Priority Queues](http://www.cplusplus.com/reference/queue/priority_queue/)
A priority queue supports the following operations: insertion of elements, deletion of the element considered highest priority, and retrieval of the highest priority element, all in $O(\log n)$ time according to the number of elements in the priority queue. Priority is based on a comparator function. The priority queue is one of the most important data structures in competitive programming, so make sure you understand how and when to use it.
### C++
```cpp
priority_queue<int> pq;
pq.push(7); // [7]
pq.push(2); // [2, 7]
pq.push(1); // [1, 2, 7]
pq.push(5); // [1, 2, 5, 7]
cout << pq.top() << endl; // 7
pq.pop(); // [1, 2, 5]
pq.pop(); // [1, 2]
pq.push(6); // [1, 2, 6]
```
### Java
In Java, we delete and retrieve the element of **lowest** priority.
```java
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(7); // [7]
pq.add(2); // [7, 2]
pq.add(1); // [7, 2, 1]
pq.add(5); // [7, 5, 2, 1]
System.out.println(pq.peek()); // 1
pq.poll(); // [7, 5, 2]
pq.poll(); // [7, 5]
pq.add(6); // [7, 6, 5]
```
## Problems
??

View file

@ -17,7 +17,7 @@ description: Introduces the problems of finding level ancestors in a tree and co
### Tutorial
- CPH 18
- CPH 18.1, 18.3
- [cp-algorithms: Lowest Common Ancestor](https://cp-algorithms.com/)
- [Binary Jumping w/ O(N) Memory](https://codeforces.com/blog/entry/74847)
- you shouldn't actually need this, but maybe interesting
@ -33,6 +33,9 @@ description: Introduces the problems of finding level ancestors in a tree and co
- [USACO Gold Cow Land](http://www.usaco.org/index.php?page=viewproblem2&cpid=921)
- LCA + BIT
- Plat
- [USACO Plat Newbarns](http://www.usaco.org/index.php?page=viewproblem2&cpid=817)
- online tree diameter
- Copy of [CF Brain Network "Hard"](https://codeforces.com/contest/690/problem/C3)
- [Max Flow](http://www.usaco.org/index.php?page=viewproblem2&cpid=576)
- [Promote](http://www.usaco.org/index.php?page=viewproblem2&cpid=696)
- Subtree + BIT

View file

@ -7,6 +7,10 @@ prerequisites:
description: Monotonic stack and sliding window.
---
## Additional Reading
- CPH 8 (Amortized Analysis)
# Monotonic Stack
Consider the following problem:
@ -22,7 +26,6 @@ The stack we used is called a "monotonic stack" because we keep popping off the
## Further Reading
- "Nearest Smallest Element" from CPH 8
- [CP Algorithms (Min Stack)](https://cp-algorithms.com/data_structures/stack_queue_modification.html)
- [Medium](https://medium.com/@vishnuvardhan623/monotonic-stack-e9dcc4fa8c3e)
@ -43,16 +46,21 @@ To compute the sum in the range, instead of using a set, we can store a variable
## Further Reading
- "Sliding Window" from CPH 8
- Read [this article]([https://cp-algorithms.com/data_structures/stack_queue_modification.html](https://cp-algorithms.com/data_structures/stack_queue_modification.html)) to learn about the "min queue" that CPH describes.
- [Medium]([https://levelup.gitconnected.com/an-introduction-to-sliding-window-algorithms-5533c4fe1cc7](https://levelup.gitconnected.com/an-introduction-to-sliding-window-algorithms-5533c4fe1cc7))
- [cp-algorithms: Min Stack + Queue](https://cp-algorithms.com/data_structures/stack_queue_modification.html)
- learn about the "min queue" that CPH describes.
- [Medium](https://levelup.gitconnected.com/an-introduction-to-sliding-window-algorithms-5533c4fe1cc7)
- [G4G](https://www.geeksforgeeks.org/window-sliding-technique/)
## Problems
- [Haybale Feast (Gold)](http://usaco.org/index.php?page=viewproblem2&cpid=767)
- [Gold - Haybale Feast](http://usaco.org/index.php?page=viewproblem2&cpid=767)
- Direct application of sliding window.
- [Train Tracking 2 (Plat)]([http://www.usaco.org/current/data/sol_train_platinum_open18.html](http://www.usaco.org/current/data/sol_train_platinum_open18.html))
- **Extremely difficult.**
<optional-content title="Better Memory with Two Passes">
- [Plat - Train Tracking](http://www.usaco.org/current/data/sol_train_platinum_open18.html)
- Quite difficult.
</optional-content>
(add more once codeforces comes up)

View file

@ -9,6 +9,8 @@ description: The Disjoint Set Union (DSU) data structure allows you to add edges
## Tutorial
- CPH 15.2
- [PAPS 11.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- Chapter 10.6 of "An Introduction to the US Computing Olympiad"
- [CSAcademy Disjoint-Set](https://csacademy.com/lesson/disjoint_data_sets)
- [Topcoder Union Find](https://www.topcoder.com/community/data-science/data-science-tutorials/disjoint-set-data-structures/)

View file

@ -5,15 +5,17 @@ author: Benjamin Qi
description: Quickly test equality of substrings with a small probability of failure.
---
- Tutorial
- CPH 26.3
- [cp-algorithms String Hashing](https://cp-algorithms.com/string/string-hashing.html)
- [Anti-Hash Tests](https://codeforces.com/blog/entry/60442)
## Tutorial
- [PAPS 14.3](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- CPH 26.3
- [cp-algorithms String Hashing](https://cp-algorithms.com/string/string-hashing.html)
- [Anti-Hash Tests](https://codeforces.com/blog/entry/60442)
- On CodeForces educational rounds in particular, make sure to use random bases.
My implementation can be found [here](https://github.com/bqi343/USACO/blob/master/Implementations/content/strings%20(14)/Light/HashRange%20(14.2).h). It uses two bases rather than just one to decrease the probability that two random strings hash to the same value. As mentioned in the articles above, there is no need to calculate modular inverses.
### Problems
## Problems
- USACO
- [Gold Cownomics](http://www.usaco.org/index.php?page=viewproblem2&cpid=741)

View file

@ -4,12 +4,13 @@ title: "Introductory Number Theory"
author: Darren Yao, Michael Cao
prerequisites:
- Gold - Introduction to Dynamic Programming
description: Prime Factorization, GCD & LCM, Modular Arithmetic
description: Divisibility and Modular Arithmetic
---
## Additional Resources
- CSES 21.1, 21.2
- [PAPS 16](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- CPH 21.1 (Primes and factors), 21.2 (Modular arithmetic)
- [CF CodeNCode](https://codeforces.com/blog/entry/77137)
## Prime Factorization

View file

@ -16,6 +16,7 @@ description: A subset of the edges of a connected, undirected, edge-weighted gra
## Tutorial
- CPH 15 (Spanning Trees)
- [PAPS 12.4](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- Prim's Algorithm
- [cp-algo](https://cp-algorithms.com/graph/mst_prim.html)
- Similar to Dijkstra

View file

@ -7,6 +7,10 @@ prerequisites:
description: ?
---
## Additional Reading
- CPH 18.4 - Merging Data Structures
# Merging Sets
Let's consider a tree, rooted at node $1$, where each node has a color (see [CSES Distinct Colors](https://cses.fi/problemset/task/1139)).
@ -20,6 +24,7 @@ if(a.size() < b.size()){ //for two sets a and b
}
```
In other words, by merging the smaller set into the larger one, the runtime complexity becomes $O(N\log N).$
<details>
<summary> Proof </summary>
@ -36,10 +41,6 @@ Prove that if you instead merge sets that have size equal to the depths of the s
</info-block>
## Further Reading
- "Merging Data Structures" from CPH 18
## Problems
- [Favorite Colors (USACO Gold)](http://www.usaco.org/index.php?page=viewproblem2&cpid=1042)

View file

@ -11,7 +11,8 @@ A **segment tree** allows you to do point update and range query in $O(\log N)$
### Tutorials
- CPH 9.3, 28.1 (Segment Trees Revisited)
- CPH 9.3 (Segment Trees)
- [PAPS 11.2.3](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [Codeforces Tutorial](http://codeforces.com/blog/entry/18051)
- [CSAcademy Tutorial](https://csacademy.com/lesson/segment_trees/)
- [cp-algorithms](https://cp-algorithms.com/data_structures/segment_tree.html)

View file

@ -24,8 +24,10 @@ Aka *Fenwick Tree*.
### Tutorials
* CPH 9.2 (very good)
* [CSAcademy BIT](https://csacademy.com/lesson/fenwick_trees) (also very good)
* CPH 9.2, 9.4
* very good
* [CSAcademy BIT](https://csacademy.com/lesson/fenwick_trees)
* also very good
* [cp-algorithms Fenwick Tree](https://cp-algorithms.com/data_structures/fenwick.html)
* extends to range increment and range query, although this is not necessary for gold
* [Topcoder BIT](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-indexed-trees/)

View file

@ -19,6 +19,7 @@ Use *Dijkstra's Algorithm*.
### Tutorial
- CSES 13.2
- [PAPS 12.3.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [cp-algo Dijkstra (Dense Graphs)](https://cp-algorithms.com/graph/dijkstra_sparse.html)
- [cp-algo Dijkstra (Sparse Graphs)](https://cp-algorithms.com/graph/dijkstra_sparse.html)
- Usually, it's this one that's applicable.
@ -51,6 +52,7 @@ Use the *Floyd-Warshall* algorithm.
### Tutorial
- CPH 13.3
- [PAPS 12.3.3](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [cp-algo Floyd-Warshall](https://cp-algorithms.com/graph/all-pair-shortest-path-floyd-warshall.html)
### Problems

View file

@ -18,6 +18,7 @@ First we'll consider the special case when $\ominus$ denotes `min`.
### Tutorial
- CPH 9.1
- [PAPS 11.2.2](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [cp-algorithms RMQ](https://cp-algorithms.com/sequences/rmq.html)
<optional-content title="Preprocessing in O(N) Time">

View file

@ -24,6 +24,8 @@ Consider [Khan's Algorithm](https://en.wikipedia.org/wiki/Topological_sorting#Ka
## Dynamic Programming
- [PAPS 9.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
One useful property of directed acyclic graphs is, as the name suggests, that there exists no cycles. If we consider each node in the graph as a state, we can perform dynamic programming on the graph if we process the states in an order that guarantees for every edge, $u\to v$ that $u$ is processed before $v$. Fortunately, this is the exact definition of a topological sort!
Let's consider a classical problem (see Longest Flight Route) where we must find the longest path in a Directed Acyclic Graph. Let `dp[curr] = longest path ending at the node curr`. Then, if we process states in topological order, the transition is relatively straightforward: `dp[curr] = max of all dp[prev] where prev represents a node with an edge going into the current node` (word better?). To reiterate, since the states a processed in topological order, we can guarantee that all possible `dp[prev]` are computed before we compute `dp[curr]`.

View file

@ -1,19 +0,0 @@
---
id: tree-dia
title: "Tree Diameter"
author: Benjamin Qi
prerequisites:
- Silver - Depth First Search
description: Finding a pair of vertices of a tree that are farthest apart.
---
### Tutorial
- CPH 14.2
### Problems
- [CSES Tree Diameter](https://cses.fi/problemset/task/1131)
- [USACO Plat Newbarns](http://www.usaco.org/index.php?page=viewproblem2&cpid=817)
- Copy of [CF Brain Network "Hard"](https://codeforces.com/contest/690/problem/C3)
- [Tree Construction](https://csacademy.com/contest/archive/task/tree-construct)

View file

@ -8,6 +8,8 @@ prerequisites:
description: Subtree updates and queries and another way to compute lowest common ancestors.
---
- CPH 18.2
RMQ LCA?
https://cses.fi/problemset/task/1138: path queries

View file

@ -60,7 +60,7 @@ Note: no lazy propagation in 2D.
### Short Description
- CSES 28.2, 28.4
- CSES 28.2 (Sparse Segment Tree), 28.4
- Segment Tree (or BIT) nested inside segment tree
- use 2D offline BIT instead whenever possible (faster, lower memory)

View file

@ -12,7 +12,8 @@ Has not been the solution to any platinum problem, but appeared in old gold and
## Tutorial
- CPH Chapter 10
- [PAPS 9.4](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- CPH 10 (Bit manipulation), 19.2 (Hamiltonian Paths)
- [Dynamic Programming Over Subsets (Codeforces)](https://codeforces.com/blog/entry/337)
- [Dynamic Programming and Bit Masking (HackerEarth)](https://www.hackerearth.com/practice/algorithms/dynamic-programming/bit-masking/tutorial/)

View file

@ -16,7 +16,7 @@ You should know basic operations like cross product and dot product. For platinu
- convex hulls
- polygon area
- point in polygon
- CPH 29
- CPH 29 (Geometry), 30.1, 30.2 (Sweep line algorithms)
- [TopCoder - Basic Geometry Concepts](https://www.topcoder.com/community/competitive-programming/tutorials/geometry-concepts-basic-concepts/)
- [CF - Point Class](https://codeforces.com/blog/entry/48122)
- [C++ - std::complex](https://codeforces.com/blog/entry/22175)

View file

@ -3,6 +3,8 @@ id: hull
title: "Convex Hull"
author: Benjamin Qi
description: Smallest convex polygon containing a set of points on a grid.
prerequisites:
- Platinum - Geometry Primitives
---
## [Convex Hull](https://en.wikipedia.org/wiki/Convex_hull_algorithms)

View file

@ -7,6 +7,8 @@ prerequisites:
description: Lazy updates on segment trees and two binary indexed trees in conjunction.
---
CPH 28.1 (Segment Trees Revisited)
## Lazy Segment Tree
- [USACO Old Gold The Lazy Cow](http://www.usaco.org/index.php?page=viewproblem2&cpid=418) (check ...)

View file

@ -12,6 +12,7 @@ description: Applications of Bellman-Ford.
### Tutorial
- CPH 13.1
- [cp-algo Bellman Ford](https://cp-algorithms.com/graph/bellman_ford.html)
- [Topcoder Graphs Pt 3](https://www.topcoder.com/community/data-science/data-science-tutorials/introduction-to-graphs-and-their-data-structures-section-3/)

View file

@ -3,8 +3,7 @@ id: slope
title: "Slope Trick"
author: Benjamin Qi
prerequisites:
-
- Platinum - Convex Hull
- Platinum - Convex Hull
description: Ways to manipulate piecewise linear convex functions.
---

View file

@ -11,11 +11,12 @@ description: Knuth-Morris-Pratt and Z Algorithms (and a few more related topics)
- [CPC.11](https://github.com/SuprDewd/T-414-AFLV/tree/master/11_strings)
- [CP-Algorithms String Processing: Fundamentals](https://cp-algorithms.com/)
- CPH (26, String Algorithms)
## Z, KMP
- Tutorial
- CPH 26.4 (Z-algorithm)
- [PAPS 14.2](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
- [paladin8](http://codeforces.com/blog/entry/3107)
- [GeeksForGeeks](http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/)
- [TopCoder](https://www.topcoder.com/community/data-science/data-science-tutorials/introduction-to-string-searching-algorithms/)

View file

@ -5,4 +5,5 @@ author: Benjamin Qi
description: ?
---
- CPH 26.2
- [Algorithm Gym](http://codeforces.com/blog/entry/15729)

View file

@ -48,10 +48,15 @@ const ModuleOrdering = {
"sorting-cpp",
]
},
{
name: "Data Structures",
items: {
"stacks-queues",
"maps-sets",
}
},
"binary-search",
"2P",
"containers-silver",
"data-structures",
"greedy",
{
name: "Graphs",
@ -59,6 +64,7 @@ const ModuleOrdering = {
"dfs",
"ff",
"func-graphs",
"bfs",
]
},
],
@ -69,7 +75,6 @@ const ModuleOrdering = {
{
name: "Graphs",
items: [
"bfs",
"toposort",
"cyc",
"dsu",
@ -88,7 +93,6 @@ const ModuleOrdering = {
{
name: "Trees",
items: [
"tree-dia",
"dp-trees",
"merging",
"bin-jump",