Merge branch 'master' of https://github.com/thecodingwizard/usaco-guide
This commit is contained in:
commit
d170301e50
33 changed files with 340 additions and 215 deletions
BIN
content/1_Intro/Error.png
Normal file
BIN
content/1_Intro/Error.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 74 KiB |
|
@ -12,6 +12,9 @@ import { Problem } from "../models";
|
|||
|
||||
export const metadata = {
|
||||
problems: {
|
||||
fence: [
|
||||
new Problem("Bronze", "Fence Painting", "567", "Intro"),
|
||||
],
|
||||
general: [
|
||||
new Problem("Bronze", "Promotion Counting", "591", "Intro"),
|
||||
new Problem("Bronze", "Word Processor", "987", "Intro"),
|
||||
|
@ -21,15 +24,21 @@ export const metadata = {
|
|||
}
|
||||
};
|
||||
|
||||
[Technical Specifications for USACO Contests](http://www.usaco.org/index.php?page=instructions)
|
||||
<resources>
|
||||
<resource source="USACO" title="Technical Specifications for Contests" url="http://www.usaco.org/index.php?page=instructions" starred>Make sure to read this.</resource>
|
||||
</resources>
|
||||
|
||||
## Example: [Fence Painting](http://usaco.org/index.php?page=viewproblem2&cpid=567)
|
||||
## Example: Fence Painting
|
||||
|
||||
USACO will automatically add a newline to the end of your file if it does not end with one. Make sure not to output trailing spaces!
|
||||
<problems-list problems={metadata.problems.fence} />
|
||||
|
||||
Importantly, USACO will automatically add a newline to the end of your file if it does not end with one. **Make sure not to output trailing spaces!**
|
||||
|
||||
![bad](Error.png)
|
||||
|
||||
### C++
|
||||
|
||||
[Here](https://www.geeksforgeeks.org/bitsstdc-h-c/) is some info about `<bits/stdc++.h\>` if you are not familiar with it.
|
||||
[Here](https://www.geeksforgeeks.org/bitsstdc-h-c/) is some info about `<bits/stdc++.h>` if you are not familiar with it.
|
||||
|
||||
#### Method 1
|
||||
|
||||
|
@ -56,17 +65,6 @@ int main() {
|
|||
}
|
||||
```
|
||||
|
||||
<optional-content title="Faster Input & Output">
|
||||
(using scanf, printf instead?)
|
||||
|
||||
(not using endl?)
|
||||
|
||||
Including `ios_base::sync_with_stdio(0); cin.tie(0);` in the main function can speed up input & output significantly on some tasks. See [here](https://codeforces.com/blog/entry/5217) and [StackOverflow](https://stackoverflow.com/questions/31162367/significance-of-ios-basesync-with-stdiofalse-cin-tienull) for more information.
|
||||
|
||||
- Actually, the former link says that it is supposedly prohibited to use `freopen` to redirect `cin` and `cout` if `ios_base::sync_with_stdio(0); cin.tie(0);` is included, but it works properly as far as I know.
|
||||
|
||||
</optional-content>
|
||||
|
||||
#### Method 2
|
||||
|
||||
Use [ifstream & ofstream](http://www.cplusplus.com/doc/tutorial/files/).
|
||||
|
@ -116,7 +114,7 @@ public class paintSol { // must be declared in paintSol.java
|
|||
|
||||
Alternatively, we can use the InputReader given in the previous module.
|
||||
|
||||
<spoiler title="InputReader">
|
||||
<spoiler title="Solution with InputReader">
|
||||
|
||||
```java
|
||||
import java.util.*;
|
||||
|
@ -202,5 +200,4 @@ The following require relatively little programming experience and no algorithmi
|
|||
|
||||
<problems-list problems={metadata.problems.general} />
|
||||
|
||||
|
||||
Also check the [CSES Introductory Problems](https://cses.fi/problemset/list/) up to and including "Palindrome Reorder."
|
|
@ -5,15 +5,12 @@ author: Darren Yao
|
|||
description: Demonstrates how to read input and print output for USACO contests.
|
||||
---
|
||||
|
||||
## Additional Reading
|
||||
## Brief Descriptions
|
||||
|
||||
- CSES 1.2
|
||||
|
||||
cin, getline, files
|
||||
|
||||
- [PAPC 2.4](http://www.csc.kth.se/~jsannemo/slask/main.pdf)
|
||||
|
||||
cin, getline
|
||||
<resources>
|
||||
<resource source="CPH" title="1.2" starred>cin, getline, files</resource>
|
||||
<resource source="PAPS" title="2.4">cin, getline</resource>
|
||||
</resources>
|
||||
|
||||
## Standard I/O
|
||||
|
|
@ -20,23 +20,21 @@ For those of you with experience in software development, note that competitive
|
|||
- [William Lin - What is Competitive Programming?](https://www.youtube.com/watch?time_continue=1&v=ueNT-w7Oluw)
|
||||
- [Kamil Debowski - Interview with a Competitive Programmer](https://www.youtube.com/watch?v=F4rykKLcduI)
|
||||
- [Task](https://open.kattis.com/contests/mcpc19open/problems/basketballoneonone) that was mentioned in video.
|
||||
- Reading
|
||||
- [PAPC Ch 1](http://www.csc.kth.se/~jsannemo/slask/main.pdf)
|
||||
|
||||
<resources embedded title="Additional Reading">
|
||||
<resource source="CPH" title="1 - Introduction" starred>algorithms & programming contests</resource>
|
||||
<resource source="PAPS" title="1 - Algorithms & Problems">examples of algorithms</resource>
|
||||
</resources>
|
||||
|
||||
</optional-content>
|
||||
|
||||
|
||||
## USACO Contest Format
|
||||
|
||||
The [USA Computing Olympiad](http://www.usaco.org/index.php?page=contests) is a national programming competition that occurs four times a year, with December, January, February, and US Open (March) contests. The regular contests are four hours long, and the US Open is five hours long. Each contest contains three problems. Solutions are evaluated and scored against a set of predetermined test cases that are not visible to the student. Scoring is out of 1000 points, with each problem being weighted equally (\~333 points). There are four divisions of contests: Bronze, Silver, Gold, and Platinum. After each contest, students who meet the contest-dependent cutoff for promotion will compete in the next division for future contests.
|
||||
|
||||
## About This Guide
|
||||
|
||||
### Languages
|
||||
|
||||
- For Bronze and Silver, we will provide code snippets in C++, Java, and Python.
|
||||
- For Gold, we will provide code snippets in C++ and Java and (sometimes) Python.
|
||||
- For Platinum, code snippets may only be provided in one language (typically either C++ or Java).
|
||||
|
||||
### Guidelines
|
||||
|
||||
- For Bronze, Silver, and Gold contestants, we aim to be a "**one stop shop**," meaning that this is the only site you have to use to be exposed to most (if not all) of the topics required for Bronze - Gold.
|
||||
|
@ -62,21 +60,29 @@ Hopefully these are helpful.
|
|||
|
||||
#### Lesson
|
||||
|
||||
- Consists of text, videos, and simple problems.
|
||||
- Goal is to introduce you to the concept.
|
||||
- Everything should be completed in order.
|
||||
- Any problems here will generally be pure implementation.
|
||||
- Everything is meant to be completed in order.
|
||||
- Usually begins with at least one standard problem.
|
||||
- External resources (text, possibly videos) will generally be placed in tables like the one above. Generally, we'll star those that are most useful for a beginner.
|
||||
|
||||
<optional-content title="Optional Content">
|
||||
|
||||
It's okay to skip over these. Some material might not be useful for competitive programming.
|
||||
It's okay to skip over these. Some material in these boxes might not be useful for competitive programming.
|
||||
|
||||
</optional-content>
|
||||
|
||||
#### Example Code
|
||||
|
||||
With examples of usage if not already provided in one of the resources above.
|
||||
|
||||
- For Bronze and Silver, we will provide code snippets in C++, Java, and Python.
|
||||
- For Gold, we will provide code snippets in C++ and Java and (sometimes) Python.
|
||||
- For Platinum, code snippets may only be provided in one language (typically either C++ or Java).
|
||||
|
||||
#### Practice
|
||||
|
||||
- Link the relevant past USACO problems (and other recommended problems).
|
||||
- Problems should be sorted in order of how they are recommended be completed.
|
||||
- Add comments regarding solution sketches.
|
||||
- Possibly include additional problems.
|
||||
- Difficulty is relative to division. (?)
|
||||
- Difficulty is **not** comparable across different modules.
|
|
@ -7,12 +7,12 @@ description: What languages you can use for programming contests and what you're
|
|||
|
||||
## Choosing a Language
|
||||
|
||||
The most popular languages that USACO supports are [C++11](https://en.wikipedia.org/wiki/C%2B%2B), [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), and [Python 3](https://en.wikipedia.org/wiki/Python_(programming_language)). In general, we recommend the following:
|
||||
The most popular languages that USACO supports are [C++11](https://en.wikipedia.org/wiki/C%2B%2B), [Java](https://en.wikipedia.org/wiki/Java_(programming_language)), and [Python 3](https://en.wikipedia.org/wiki/Python_(programming_language)). Pascal used to be popular in the past, but its use is rare now, and many programming contests have removed or are planning to remove support for it in the near future (in short: don't use it now). In general, we recommend the following:
|
||||
|
||||
- If you already know one of these languages, just use it.
|
||||
- If you know multiple languages, we recommend you pick C++ over Java, and Java over Python.
|
||||
- For Bronze, any language will do.
|
||||
- For Silver, Gold, and Platinum, Python is not recommended.
|
||||
- For Silver, Gold, and Platinum, Python is not recommended, because it is a slow language. See "Why C++?" for more information about this.
|
||||
|
||||
Keep in mind that it's easy to switch languages down the road. Don't get caught up on which language to choose. Just pick the one you feel most comfortable with!
|
||||
|
||||
|
@ -48,37 +48,35 @@ In particular, contestants using Java should be familiar with roughly the first
|
|||
|
||||
## Resources for Learning How to Code
|
||||
|
||||
Let us know what works (or doesn't) for you.
|
||||
|
||||
### General
|
||||
|
||||
<resources title="Learning to Code">
|
||||
<resource title="Sololearn" url="https://www.sololearn.com/" starred>courses for C++, Java, Python</resource>
|
||||
<resource title="VPlanet - Learn to Code" url="https://www.vplanetcoding.com/course1">basic problems, mostly loops</resource>
|
||||
</resources>
|
||||
|
||||
|
||||
### C++
|
||||
|
||||
Use one of these resources (or find your own) to learn C++.
|
||||
Use one of the resources above or below (or find your own) to learn C++. If you use Sololearn, you don't have to complete the full course; we recommend you finish everything up to (but not including) "More on Classes."
|
||||
|
||||
<resources>
|
||||
<resource source="Sololearn" title="C++" url="https://www.sololearn.com/Play/CPlusPlus" starred>also courses for Java, Python</resource>
|
||||
<resource source="PAPS" title="2 - Programming in C++" starred></resource>
|
||||
<resources title="C++">
|
||||
<resource source="PAPS" title="2 - Programming in C++" starred>lots of examples, Kattis exercises</resource>
|
||||
</resources>
|
||||
|
||||
If you use Sololearn, we recommend you finish everything up to (but not including) "More on Classes." You don't have to complete the full course.
|
||||
|
||||
<info-block title="Pro Tip">
|
||||
|
||||
You do not need to learn pointers (for now). Knowledge of structs and classes is useful but not required.
|
||||
|
||||
</info-block>
|
||||
|
||||
|
||||
## Resources for Getting Started
|
||||
|
||||
<optional-content>
|
||||
|
||||
Let us know what works (or doesn't) for you.
|
||||
|
||||
<resources embedded title="Getting Started">
|
||||
<resource source="CodeSignal" title="CodeSignal" url="https://codesignal.com/">can practice basics with "Arcade," "Interview Practice"</resource>
|
||||
<resource source="Philippines OI" title="Prepare" url="https://noi.ph/prepare/">lots of links!</resource>
|
||||
<resource source="IOI" title="Getting Started" url="https://ioinformatics.org/page/getting-started/14">not so up to date</resource>
|
||||
<resource source="Quora" title="Joshua Pan - Schedule for Beginners" url="https://www.quora.com/What-is-a-good-schedule-to-follow-for-becoming-better-at-competitive-programming-for-beginners">generally good, although CSES (see resources) is definitely a better place to start than USACO Training or Codechef</resource>
|
||||
<resources title="Getting Started">
|
||||
<resource source="CodeSignal" title="CodeSignal" url="https://codesignal.com/" starred>can practice basics with "Arcade," "Interview Practice"</resource>
|
||||
<resource source="Philippines OI" title="Prepare" url="https://noi.ph/prepare/" starred>lots of links!</resource>
|
||||
<resource source="IOI" title="Getting Started" url="https://ioinformatics.org/page/getting-started/14">not up to date</resource>
|
||||
<resource source="Quora" title="Joshua Pan - Schedule for Beginners" url="https://www.quora.com/What-is-a-good-schedule-to-follow-for-becoming-better-at-competitive-programming-for-beginners">generally good, although CSES problemset (see "Resources") is definitely a better place to start than USACO Training or Codechef</resource>
|
||||
</resources>
|
||||
|
||||
|
||||
</optional-content>
|
|
@ -9,16 +9,18 @@ See [clist.by](https://clist.by/coder/bqi343/) for an extensive list of contests
|
|||
|
||||
Make sure to [upsolve](https://en.wiktionary.org/wiki/upsolve) after the contest ends!
|
||||
|
||||
## Contests that I regularly participate in
|
||||
|
||||
- [AtCoder](https://beta.atcoder.jp/contests/archive)
|
||||
- probably the highest quality, although difficulty isn't always reasonable
|
||||
- Contests
|
||||
- Beginner / Regular: 4 problems, 100 min
|
||||
- Beginner / Regular: 4 or 6 problems, ~100 min
|
||||
- Grand: 6 problems, ~110 min
|
||||
- [Visualizer](https://kenkoooo.com/atcoder/#/table/Benq)
|
||||
- I've done nearly all of the AGC problems.
|
||||
- [Codeforces](http://codeforces.com/problemset)
|
||||
- Contests
|
||||
- Div 2, Div 1: 5 problems, 2 hrs
|
||||
- Div 1/2/3/(4?): 5-6 problems (with some variations), 2 to 2.5 hrs
|
||||
- Archive
|
||||
- problem quality, difficulty ratings are ok but not always great
|
||||
- [Topcoder](https://www.topcoder.com/my-dashboard/)
|
||||
|
@ -27,6 +29,9 @@ Make sure to [upsolve](https://en.wiktionary.org/wiki/upsolve) after the contest
|
|||
- Solutions only tested after contest!
|
||||
- [Don Mills OJ](http://dmoj.ca/)
|
||||
- at least one contest every month during school year
|
||||
|
||||
## Other Websites
|
||||
|
||||
- [Google Kickstart](https://codingcompetitions.withgoogle.com/kickstart)
|
||||
- Feb - Nov
|
||||
- [Kattis](https://open.kattis.com/)
|
||||
|
@ -46,42 +51,32 @@ The following websites do not hold regular contests anymore, but they're still w
|
|||
- Open: 7 problems, 2 hrs
|
||||
- no more? D:
|
||||
- Archive
|
||||
- short statements, editorials
|
||||
- short statements, good editorials
|
||||
- solve statistics
|
||||
- ability to view best solutions
|
||||
- I've done nearly all of the problems. :D
|
||||
- I've done nearly all of the problems.
|
||||
- [HackerRank](https://www.hackerrank.com/dashboard)
|
||||
- hack the interview!!
|
||||
|
||||
## Annual Contests
|
||||
|
||||
- [Google Code Jam](https://code.google.com/codejam/): Apr
|
||||
- 25 from R3
|
||||
- [Facebook Hacker Cup](https://www.facebook.com/hackercup/): Jun-Jul -> Oct??
|
||||
- 25 from R3
|
||||
- [Topcoder Open](https://tco19.topcoder.com/): Apr-Aug -> Nov
|
||||
- 4 from SRMs
|
||||
- 10 from R4
|
||||
- 2 from Wildcard
|
||||
- [AtCoder World Tour Finals](https://codeforces.com/blog/entry/56623)
|
||||
- 8 from AGC
|
||||
- [Bubble Cup](http://bubblecup.org/): Apr
|
||||
<resources>
|
||||
<resource source="Google" title="Code Jam" url="https://codingcompetitions.withgoogle.com/codejam/">25 from R3</resource>
|
||||
<resource source="Facebook" title="Hacker Cup" url="https://www.facebook.com/hackercup/">25 from R3</resource>
|
||||
<resource source="TopCoder" title="Open" url="https://tco20.topcoder.com/competition-overview/algorithm/algorithm-ways">4 from SRMs, 10 from R4, 2 from wildcard</resource>
|
||||
<resource source="AtCoder" title="World Tour Finals" url="https://codeforces.com/blog/entry/56623">8 from AGC</resource>
|
||||
</resources>
|
||||
|
||||
## US High School
|
||||
|
||||
- [VT HSPC](https://icpc.cs.vt.edu/#/hscontest2017)
|
||||
- Online
|
||||
- 5 hours
|
||||
- [Kattis](https://open.kattis.com/problem-sources/2016%20Virginia%20Tech%20High%20School%20Programming%20Contest)
|
||||
- December
|
||||
- [UCF HSPT](https://hspt.ucfprogrammingteam.org/index.php/hspt-online-edition)
|
||||
- Online
|
||||
- 4 hours
|
||||
- December
|
||||
- [Cornell HSPC](https://www.cs.cornell.edu/events/cornell-high-school-programming-contest)
|
||||
- [2019](https://cornell-hspc19.kattis.com/problems)
|
||||
- [PClassic (Philadelphia)](https://pclassic.org/)
|
||||
- Java only :((
|
||||
- [mBIT (Montgomery Blair HS)](https://mbit.mbhs.edu/)
|
||||
Only considering contests which allow C++ since the others aren't legit. (add more?)
|
||||
|
||||
<resources>
|
||||
<resource source="Virginia Tech" title="HSPC" url="https://icpc.cs.vt.edu/#/hscontest2017">December, online, teams of 3, 5 hours, past problems on <a href="https://icpc.cs.vt.edu/#/hscontest2017">Kattis</a></resource>
|
||||
<resource source="University of Central Florida" title="HSPT" url="https://hspt.ucfprogrammingteam.org/index.php/hspt-online-edition">Decmeber, online, individual, 4 hours</resource>
|
||||
<resource source="Cornell" title="HSPC" url="https://www.cs.cornell.edu/events/cornell-high-school-programming-contest">April, teams of 3, 3 hours, <a href="https://cornell-hspc19.kattis.com/problems">2019 problems</a></resource>
|
||||
<resource source="Montgomery Blair HS" title="mBIT" url="https://mbit.mbhs.edu/">online, teams of 4, 4 hours</resource>
|
||||
</resources>
|
||||
|
||||
## Codeforces Tools
|
||||
|
18
content/2_General/IO_Speed.mdx
Normal file
18
content/2_General/IO_Speed.mdx
Normal file
|
@ -0,0 +1,18 @@
|
|||
---
|
||||
id: io-speed
|
||||
title: Input / Output Speed
|
||||
author: ?
|
||||
description: ""
|
||||
---
|
||||
|
||||
(actually figure out what makes a dif on USACO lol)
|
||||
|
||||
## C++
|
||||
|
||||
(using scanf, printf instead?)
|
||||
|
||||
(not using endl?)
|
||||
|
||||
Including `ios_base::sync_with_stdio(0); cin.tie(0);` in the main function can speed up input & output significantly on some tasks. See [here](https://codeforces.com/blog/entry/5217) and [StackOverflow](https://stackoverflow.com/questions/31162367/significance-of-ios-basesync-with-stdiofalse-cin-tienull) for more information.
|
||||
|
||||
- Actually, the former link says that it is supposedly prohibited to use `freopen` to redirect `cin` and `cout` if `ios_base::sync_with_stdio(0); cin.tie(0);` is included, but it works properly as far as I know.
|
|
@ -21,7 +21,7 @@ In general, I think it’s fine to read the solution relatively early on, as lon
|
|||
|
||||
Problems that you practice with should be of the appropriate difficulty. You don't necessarily need to complete all the exercises at the end of each module, just do what you think is right for you. A problem at the right level of difficulty should be one of two types: either you struggle with the problem for a while before coming up with a working solution, or you miss it slightly and need to consult the solution for some small part. If you instantly come up with the solution, a problem is likely too easy, and if you're missing multiple steps, it might be too hard.
|
||||
|
||||
[This](https://web.evanchen.cc/FAQs/raqs.html) and [this](https://usamo.wordpress.com/2019/01/31/math-contest-platitudes-v3/) are two blog posts by Evan Chen that I find quite insightful. They discuss such things as time management, the problem-solving process, and other tips that you may find useful.
|
||||
[This](https://web.evanchen.cc/FAQs/raqs.html) and [this](https://usamo.wordpress.com/2019/01/31/math-contest-platitudes-v3/) are two blog posts by Evan Chen that I find quite insightful. They discuss such things as time management, the problem-solving process, and other tips that you may find useful. See [my website](https://darrenyao.com/beginner) for more information.
|
||||
|
||||
## Nathan Wang
|
||||
|
|
@ -10,30 +10,32 @@ import { Problem } from "../models";
|
|||
|
||||
export const metadata = {
|
||||
problems: {
|
||||
cses: [
|
||||
new Problem("CSES", "Creating Strings I", "1622", "Intro", false, []),
|
||||
new Problem("CSES", "Apple Division", "1623", "Intro", false, []),
|
||||
new Problem("CSES", "Chessboard and Queens", "1624", "Easy", false, []),
|
||||
easier: [
|
||||
new Problem("CSES", "Creating Strings I", "1622", "Intro", false, [], "all perms of string"),
|
||||
new Problem("CSES", "Apple Division", "1623", "Intro", false, [], "all $2^n$ subsets"),
|
||||
new Problem("Bronze", "Diamond Collector", "639", "Easy", false, [], "fix the min"), // 99.9
|
||||
new Problem("Bronze", "Milk Pails", "615", "Easy", false, [], "Hint: Fix the number of first-type operations you perform."), // 99.71
|
||||
new Problem("Bronze", "Bovine Genomics", "736", "Easy", false, [], ""), // 99.73
|
||||
new Problem("Bronze", "Cow Gymnastics", "963", "Easy", false, [], "Hint: Brute force over all possible pairs."), // 99.93
|
||||
new Problem("Bronze", "Where Am I?", "964", "Easy", false, [], "Hint: Brute force over all possible substrings."), // 99.48
|
||||
new Problem("Bronze", "Triangles", "1011", "Easy", false, [], "loop over the possible right angles"), // 98.02
|
||||
],
|
||||
bronze: [
|
||||
new Problem("Bronze", "Milk Pails", "615", "Intro", false, [], "Hint: Fix the number of first-type operations you perform."),
|
||||
new Problem("Bronze", "Triangles", "1011", "Easy", false, [], ""),
|
||||
new Problem("Bronze", "Cow Gymnastics", "963", "Easy", false, [], "Hint: Brute force over all possible pairs."),
|
||||
new Problem("Bronze", "Lifeguards", "784", "Easy", false, [], "Hint: Try removing each lifeguard one at a time."),
|
||||
new Problem("Bronze", "Where Am I?", "964", "Easy", false, [], "Hint: Brute force over all possible substrings."),
|
||||
new Problem("Bronze", "Photoshoot", "988", "Normal", false, [], "Hint: Figure out what exactly you're complete searching."),
|
||||
new Problem("Bronze", "Field Reduction", "641", "Normal", false, [], "Hint: For this problem, you can't do a full complete search; you have to do a reduced search."),
|
||||
new Problem("Bronze", "Back & Forth", "857", "Hard", false, [], ""),
|
||||
new Problem("Bronze", "Livestock Lineup", "965", "Hard", false, ["permutations"], ""),
|
||||
harder: [
|
||||
new Problem("CSES", "Chessboard and Queens", "1624", "Normal", false, [], "backtracking"),
|
||||
new Problem("Bronze", "Lifeguards", "784", "Normal", false, [], "Hint: Try removing each lifeguard one at a time."), // 98.76
|
||||
new Problem("Bronze", "Photoshoot", "988", "Normal", false, [], "Hint: Figure out what exactly you're complete searching."), // 98.45
|
||||
new Problem("Bronze", "Back & Forth", "857", "Hard", false, [], "exponential time going through all possibilities"), // 99.63
|
||||
new Problem("Bronze", "Livestock Lineup", "965", "Hard", false, ["permutations"], ""), // 91.95
|
||||
new Problem("Bronze", "Field Reduction", "641", "Hard", false, [], "Hint: For this problem, you can't do a full complete search; you have to do a reduced search."), // 91.75
|
||||
new Problem("Bronze", "Circle Cross", "712", "Hard", false, [], ""), // 89.6
|
||||
new Problem("Silver", "Bovine Genomics", "739", "Hard", false, [], ""),
|
||||
new Problem("Bronze", "Load Balancing", "617", "Very Hard", false, [], ""), // 82.79
|
||||
new Problem("Bronze", "Bull in a China Shop", "640", "Very Hard", false, [], "lots of WA on this one"), // 47.38
|
||||
new Problem("Silver", "Field Reduction", "642", "Very Hard", false, [], ""),
|
||||
],
|
||||
silver: [
|
||||
new Problem("Silver", "Bovine Genomics", "739", "Normal", false, [], ""),
|
||||
new Problem("Silver", "Field Reduction", "642", "Normal", false, [], ""),
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
## Additional Reading
|
||||
|
||||
- CPH 5.1 - 5.3 (Complete Search)
|
||||
|
@ -109,7 +111,7 @@ A **permutation** is a reordering of a list of elements. Some problems will ask
|
|||
|
||||
In Java, we'll have to implement this ourselves, which is called [Heap's Algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm) (no relation to the heap data structure). What's going to be in the check function depends on the problem, but it should verify whether the current permutation satisfies the constraints given in the problem.
|
||||
|
||||
As an example, here are the permutations generated by Heap's Algorithm for \([1, 2, 3]\):
|
||||
As an example, here are the permutations generated by Heap's Algorithm for $[1, 2, 3]$:
|
||||
|
||||
$$
|
||||
[1, 2, 3], [2, 1, 3], [3, 1, 2], [1, 3, 2], [2, 3, 1], [3, 2, 1]
|
||||
|
@ -132,6 +134,7 @@ static void generate(int[] arr, int k){
|
|||
swap(arr, 0, k-1);
|
||||
// swap indices 0 and k-1 of arr
|
||||
}
|
||||
generate(arr, k-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -145,16 +148,10 @@ do {
|
|||
|
||||
Note that this generates the permutations in **lexicographical order** (explanation)
|
||||
|
||||
## Problems
|
||||
## Easier Problems
|
||||
|
||||
<problems-list problems={metadata.problems.cses} />
|
||||
<problems-list problems={metadata.problems.easier} />
|
||||
|
||||
<problems-list problems={metadata.problems.bronze} />
|
||||
## Harder Problems
|
||||
|
||||
Load Balancing: 617
|
||||
Bull in a China Shop: 640
|
||||
Bovine Genomics: 736
|
||||
Diamond Collector: 639
|
||||
Circle Cross: 712
|
||||
|
||||
<problems-list problems={metadata.problems.silver} />
|
||||
<problems-list problems={metadata.problems.harder} />
|
||||
|
|
|
@ -8,9 +8,11 @@ frequency: 4
|
|||
|
||||
## Additional Resources
|
||||
|
||||
- CPH 4 (Data Structures)
|
||||
- [PAPS 3.1, 3.5, 6.1](https://www.csc.kth.se/~jsannemo/slask/main.pdf)
|
||||
- [CPC.2](https://github.com/SuprDewd/T-414-AFLV/tree/master/02_data_structures)
|
||||
<resources>
|
||||
<resource source="CPH" title="4 - Data Structures" starred>structures mentioned in 4.5 are covered later</resource>
|
||||
<resource source="PAPS" title="3.1, 3.5, 6.1">vectors, sets, maps</resource>
|
||||
<resource source="CPC" title="2 - Data Structures" url="02_data_structures">assumes prior experience</resource>
|
||||
</resources>
|
||||
|
||||
# Data Structures
|
||||
|
||||
|
|
|
@ -26,7 +26,7 @@ export const metadata = {
|
|||
**Sorting** is exactly what it sounds like: arranging items in some particular order.
|
||||
|
||||
<info-block title="Pro Tip">
|
||||
No bronze problem requires sorting, but it can be an alternate solution that is sometimes much easier to implement.
|
||||
No bronze problem should require sorting, but it can be an alternate solution that is sometimes much easier to implement.
|
||||
</info-block>
|
||||
|
||||
## Additional Resources
|
||||
|
@ -78,11 +78,13 @@ Other variations are similar, such as the following:
|
|||
|
||||
### Tutorial
|
||||
|
||||
- CSES 3.3
|
||||
- [CSAcademy Binary Search](https://csacademy.com/lesson/binary_search)
|
||||
- [Topcoder Binary Search](https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/)
|
||||
- [KhanAcademy Binary Search](https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/a/binary-search)
|
||||
- [GeeksForGeeks](https://www.geeksforgeeks.org/binary-search/)
|
||||
<resources>
|
||||
<resource source="KA" title="Binary Search" url="https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/a/binary-search" starred>animations!</resource>
|
||||
<resource source="CSA" title="Binary Search" url="binary_search" starred>animation!</resource>
|
||||
<resource source="CPH" title="3.3 - Binary Search" starred></resource>
|
||||
<resource source="TC" title="Binary Search" url="binary-search"></resource>
|
||||
<resource source="GFG" title="Binary Search" url="binary-search"></resource>
|
||||
</resources>
|
||||
|
||||
### Library Functions to do Binary Search
|
||||
|
||||
|
|
|
@ -9,6 +9,9 @@ import { Problem } from "../models";
|
|||
|
||||
export const metadata = {
|
||||
problems: {
|
||||
blocked: [
|
||||
new Problem("Bronze", "Blocked Billboard", "759", "Easy", false, ["rect"]),
|
||||
],
|
||||
general: [
|
||||
new Problem("Bronze", "Square Pasture", "663", "Intro", false, ["rect"]),
|
||||
new Problem("Bronze", "Blocked Billboard II", "783", "Easy", false, ["rect"]),
|
||||
|
@ -17,10 +20,11 @@ export const metadata = {
|
|||
}
|
||||
};
|
||||
|
||||
|
||||
Most only include two or three squares or rectangles, in which case you can simply draw out cases on paper. This should logically lead to a solution.
|
||||
|
||||
## Example: [Blocked Billboard](http://usaco.org/index.php?page=viewproblem2&cpid=759)
|
||||
## Example: Bronze - Blocked Billboard
|
||||
|
||||
<problems-list problems={metadata.problems.blocked} />
|
||||
|
||||
### Naive Solution
|
||||
|
||||
|
|
|
@ -10,19 +10,21 @@ import { Problem } from "../models"
|
|||
|
||||
export const metadata = {
|
||||
problems: {
|
||||
bronze: [
|
||||
new Problem("Bronze", "Mixing Milk", "855", "Intro"),
|
||||
new Problem("Bronze", "Speeding", "568", "Intro"),
|
||||
new Problem("Bronze", "Angry Cows", "592", "Intro"),
|
||||
new Problem("Bronze", "Milk Measurement", "761", "Intro"),
|
||||
new Problem("Bronze", "Block Game", "664", "Intro"),
|
||||
new Problem("Bronze", "Shell Game", "891", "Intro"),
|
||||
new Problem("Bronze", "Team Tic Tac Toe", "831", "Intro"),
|
||||
new Problem("Bronze", "The Lost Cow", "735", "Intro", false, [], ""),
|
||||
new Problem("Bronze", "Why Did the Cow Cross the Road III", "713", "Intro", false, []),
|
||||
new Problem("Bronze", "Mowing the Field", "593", "Intro", false, []),
|
||||
new Problem("Bronze", "The Bovine Shuffle", "760", "Normal", false, []),
|
||||
new Problem("Bronze", "Circular Barn", "616", "Normal", false, []),
|
||||
easier: [
|
||||
new Problem("Bronze", "Shell Game", "891", "Easy"), // 99.93
|
||||
new Problem("Bronze", "Mixing Milk", "855", "Easy", false, [], "just pour 100 times"), // 99.87
|
||||
new Problem("Bronze", "Speeding", "568", "Easy", false, [], "store speed for each mile"), // 99.05
|
||||
new Problem("Bronze", "The Lost Cow", "735", "Easy", false, [], ""), // 99.46
|
||||
new Problem("Bronze", "The Bovine Shuffle", "760", "Easy", false, []), // 100
|
||||
],
|
||||
harder: [
|
||||
new Problem("Bronze", "Circular Barn", "616", "Normal", false, []), // 99.25
|
||||
new Problem("Bronze", "Block Game", "664", "Normal"), // 97.41
|
||||
new Problem("Bronze", "Team Tic Tac Toe", "831", "Normal"), // 97.41
|
||||
new Problem("Bronze", "Cow Queue", "713", "Normal", false, []), // 97.59
|
||||
new Problem("Bronze", "Mowing the Field", "593", "Normal", false, []), // 97.16
|
||||
new Problem("Bronze", "Milk Measurement", "761", "Hard"), // 95.97
|
||||
new Problem("Bronze", "Angry Cows", "592", "Hard", false, [], ""), // 94.15
|
||||
]
|
||||
}
|
||||
};
|
||||
|
@ -47,11 +49,11 @@ Please output a single integer containing the number of seconds after the start
|
|||
|
||||
### Solution
|
||||
|
||||
We can simulate the process. After inputting the values of $R$, $S$, $M$, $N$, $P$, and $Q$, we can keep track of Alice's and Bob's $x$- and $y$-coordinates. To start, we initialize variables for their respective positions. Alice's coordinates are initially \((0, 0)\), and Bob's coordinates are $(R, S)$ respectively. Every second, we increase Alice's $x$-coordinate by $M$ and her $y$-coordinate by $N$, and decrease Bob's $x$-coordinate by $P$ and his $y$-coordinate by $Q$.
|
||||
We can simulate the process. After inputting the values of $R$, $S$, $M$, $N$, $P$, and $Q$, we can keep track of Alice's and Bob's $x$- and $y$-coordinates. To start, we initialize variables for their respective positions. Alice's coordinates are initially $(0, 0)$, and Bob's coordinates are $(R, S)$ respectively. Every second, we increase Alice's $x$-coordinate by $M$ and her $y$-coordinate by $N$, and decrease Bob's $x$-coordinate by $P$ and his $y$-coordinate by $Q$.
|
||||
|
||||
Now, when do we stop? First, if Alice and Bob ever have the same coordinates, then we are done. Also, since Alice strictly moves up and to the right and Bob strictly moves down and to the left, if Alice's $x$- or $y$-coordinates are ever greater than Bob's, then it is impossible for them to meet.
|
||||
|
||||
Example Java code is displayed below. Here, as in other examples, input processing will be omitted).
|
||||
Example Java code is displayed below. Here, as in other examples, input processing will be omitted.
|
||||
|
||||
```java
|
||||
int ax = 0; int ay = 0; // alice's x and y coordinates
|
||||
|
@ -71,14 +73,14 @@ if(ax == bx && ay == by){ // if they are in the same location
|
|||
out.close(); // flush the output
|
||||
```
|
||||
|
||||
For C++, replaces lines such as `out.println(t)` with `cout << t << endl`.
|
||||
For C++, replace lines such as `out.println(t)` with `cout << t << endl`.
|
||||
|
||||
|
||||
## Example 2
|
||||
|
||||
### Statement
|
||||
|
||||
There are $N$ buckets ($5 \leq N \leq 10^5$), each with a certain capacity $C_i$ ($1 \leq C_i \leq 100$). One day, after a rainstorm, each bucket is filled with $A_i$ units of water ($1\leq A_i \leq C_i$). Charlie then performs the following process: he pours bucket 1 into bucket 2, then bucket 2 into bucket 3, and so on, up until pouring bucket $N-1$ into bucket $N$. When Charlie pours bucket $B$ into bucket $B+1$, he pours as much as possible until bucket $B$ is empty or bucket $B+1$ is full. Find out how much water is in each bucket once Charlie is done pouring.
|
||||
There are $N$ buckets ($5 \leq N \leq 10^5$), each with a certain capacity $C_i$ ($1 \leq C_i \leq 100$). One day, after a rainstorm, each bucket is filled with $A_i$ units of water ($1\leq A_i \leq C_i$). Charlie then performs the following process: he pours bucket $1$ into bucket $2$, then bucket $2$ into bucket $3$, and so on, up until pouring bucket $N-1$ into bucket $N$. When Charlie pours bucket $B$ into bucket $B+1$, he pours as much as possible until bucket $B$ is empty or bucket $B+1$ is full. Find out how much water is in each bucket once Charlie is done pouring.
|
||||
|
||||
#### Input Format
|
||||
|
||||
|
@ -94,7 +96,7 @@ Please print one line of output, containing $N$ space-separated integers: the fi
|
|||
|
||||
### Solution
|
||||
|
||||
Once again, we can simulate the process of pouring one bucket into the next. The amount of milk poured from bucket $B$ to bucket $B+1$ is the smaller of the amount of water in bucket $B$ (after all previous operations have been completed) and the remaining space in bucket $B+1$, which is $C_{B+1} - A_{B+1}$. We can just handle all of these operations in order, using an array C to store the maximum capacities of each bucket, and an array A to store the current water level in each bucket, which we update during the process. Example code is below (note that arrays are zero-indexed, so the indices of our buckets go from $0$ to $N-1$ rather than from $1$ to $N$).
|
||||
Once again, we can simulate the process of pouring one bucket into the next. The amount of milk poured from bucket $B$ to bucket $B+1$ is the smaller of the amount of water in bucket $B$ (after all previous operations have been completed) and the remaining space in bucket $B+1$, which is $C_{B+1} - A_{B+1}$. We can just handle all of these operations in order, using an array $C$ to store the maximum capacities of each bucket, and an array $A$ to store the current water level in each bucket, which we update during the process. Example code is below (note that arrays are zero-indexed, so the indices of our buckets go from $0$ to $N-1$ rather than from $1$ to $N$).
|
||||
|
||||
Java:
|
||||
|
||||
|
@ -135,4 +137,10 @@ for(int i = 0; i < n; i++){
|
|||
cout << endl;
|
||||
```
|
||||
|
||||
<problems-list problems={metadata.problems.bronze} />
|
||||
## Easier Problems
|
||||
|
||||
<problems-list problems={metadata.problems.easier} />
|
||||
|
||||
## Harder Problems
|
||||
|
||||
<problems-list problems={metadata.problems.harder} />
|
|
@ -36,9 +36,9 @@ No silver problem should require BFS rather than DFS, but it's still good to kno
|
|||
## Resources
|
||||
|
||||
<resources>
|
||||
<resource source="CPH" title="12.2"></resource>
|
||||
<resource source="PAPS" title="12.1"></resource>
|
||||
<resource source="CSA" title="Breadth First Search" url="breadth_first_search"></resource>
|
||||
<resource source="CSA" title="Breadth First Search" url="breadth_first_search" starred>interactive</resource>
|
||||
<resource source="CPH" title="12.2 - Breadth-First Search" starred></resource>
|
||||
<resource source="PAPS" title="12.1 - Breadth-First Search"></resource>
|
||||
<resource source="KA" title="Breadth First Search and Its Uses" url="https://www.khanacademy.org/computing/computer-science/algorithms/breadth-first-search/a/breadth-first-search-and-its-uses"></resource>
|
||||
<resource source="cp-algo" title="Breadth First Search" url="graph/breadth-first-search.html"></resource>
|
||||
<resource source="cp-algo" title="0/1 BFS" url="graph/01_bfs.html"></resource>
|
||||
|
|
|
@ -57,13 +57,15 @@ The binary search function for this is very similar. Find the maximum value of $
|
|||
|
||||
## Example: [CF 577 Div. 2 C](https://codeforces.com/contest/1201/problem/C)
|
||||
|
||||
Given an array `arr` of $n$ integers, where $n$ is odd, we can perform the following operation on it $k$ times: take any element of the array and increase it by $1$. We want to make the median of the array as large as possible, after $k$ operations.
|
||||
Given an array $\texttt{arr}$ of $n$ integers, where $n$ is odd, we can perform the following operation on it $k$ times: take any element of the array and increase it by $1$. We want to make the median of the array as large as possible after $k$ operations.
|
||||
|
||||
Constraints: $1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^9$ and $n$ is odd.
|
||||
**Constraints:** $1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^9$ and $n$ is odd.
|
||||
|
||||
The solution is as follows: we first sort the array in ascending order. Then, we binary search for the maximum possible median. We know that the number of operations required to raise the median to $x$ increases monotonically as $x$ increases, so we can use binary search. For a given median value $x$, the number of operations required to raise the median to $x$ is
|
||||
|
||||
$$\sum_{i=(n+1)/2}^{n} \max(0, x - \text{arr[i]})$$
|
||||
$$
|
||||
\sum_{i=(n+1)/2}^{n} \max(0, x - \texttt{arr}[i])
|
||||
$$
|
||||
|
||||
If this value is less than or equal to $k$, then $x$ can be the median, so our check function returns true. Otherwise, $x$ cannot be the median, so our check function returns false.
|
||||
|
||||
|
|
|
@ -56,12 +56,12 @@ export const metadata = {
|
|||
|
||||
<resources>
|
||||
<resource source="CPH" title="12.1 - DFS, 14 - Tree algorithms" starred></resource>
|
||||
<resource source="CSA" title="Depth First Search" url="depth_first_search" starred></resource>
|
||||
<resource source="PAPS" title="12.2"></resource>
|
||||
<resource source="CPC" title="7 - Graphs 1" url="07_graphs_1"></resource>
|
||||
<resource source="CSA" title="Depth First Search" url="depth_first_search" starred>interactive</resource>
|
||||
<resource source="IUSACO" title="10.4 - Graph Traversal Algorithms"></resource>
|
||||
<resource source="PAPS" title="12.2 - Depth-First Search">with an example problem</resource>
|
||||
<resource source="CPC" title="7 - Graphs 1" url="07_graphs_1">fast-paced</resource>
|
||||
<resource source="cp-algo" title="Depth First Search" url="graph/depth-first-search.html">hard to parse for a beginner</resource>
|
||||
<resource source="TC" title="Graphs Section 2" url="introduction-to-graphs-and-their-data-structures-section-2"></resource>
|
||||
<resource source="IUSACO" title="10.4 - Graph Traversal Algorithms"></resource>
|
||||
</resources>
|
||||
|
||||
### Problems
|
||||
|
@ -76,7 +76,7 @@ export const metadata = {
|
|||
|
||||
## Graph Two-Coloring
|
||||
|
||||
*Graph two-coloring* refers to assigning a boolean value to each node of the graph, dictated by the edge configuration
|
||||
*Graph two-coloring* refers to assigning a boolean value to each node of the graph, dictated by the edge configuration.
|
||||
The most common example of a two-colored graph is a *bipartite graph*, in which each edge connects two nodes of opposite colors.
|
||||
|
||||
<problems-list problems={metadata.problems.bipsample} />
|
||||
|
@ -84,8 +84,8 @@ The most common example of a two-colored graph is a *bipartite graph*, in which
|
|||
### Tutorial
|
||||
|
||||
<resources>
|
||||
<resource source="IUSACO" title="10.7 - Bipartite Graphs"></resource>
|
||||
<resource source="CPH" title="12.3"></resource>
|
||||
<resource source="IUSACO" title="10.7 - Bipartite Graphs" starred></resource>
|
||||
<resource source="CPH" title="12.3 - Graph Traversal: Applications"></resource>
|
||||
<resource source="cp-algo" title="Bipartite Check" url="graph/bipartite-check.html">Uses BFS, but DFS accomplishes the same task.</resource>
|
||||
</resources>
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ title: Flood Fill
|
|||
author: Siyong Huang
|
||||
prerequisites:
|
||||
- Silver - Depth First Search
|
||||
description: "[Flood Fill](https://en.wikipedia.org/wiki/Flood_fill) refers to finding connected components in a graph that is respresented by a grid."
|
||||
description: "Flood Fill refers to finding connected components in a graph that is respresented by a grid."
|
||||
frequency: 3
|
||||
---
|
||||
|
||||
|
@ -33,9 +33,7 @@ export const metadata = {
|
|||
|
||||
<problems-list problems={metadata.problems.sample} />
|
||||
|
||||
## [Flood Fill](https://en.wikipedia.org/wiki/Flood_fill)
|
||||
|
||||
### Tutorial
|
||||
## Lesson
|
||||
|
||||
<resources>
|
||||
<resource source="IUSACO" title="10.5 - Flood Fill"></resource>
|
||||
|
|
|
@ -4,7 +4,7 @@ title: Functional Graphs
|
|||
author: Siyong Huang
|
||||
prerequisites:
|
||||
- Silver - Depth First Search
|
||||
description: A functional graph is a digraph in which every vertex has exactly one outgoing edge.
|
||||
description: A functional graph is a digraph (directed graph) in which every vertex has exactly one outgoing edge.
|
||||
frequency: 1
|
||||
---
|
||||
|
||||
|
@ -27,17 +27,22 @@ export const metadata = {
|
|||
}
|
||||
};
|
||||
|
||||
Consider graphs like the one presented in this problem:
|
||||
We'll consider graphs like the one presented in this problem:
|
||||
|
||||
<problems-list problems={metadata.problems.sample} />
|
||||
|
||||
### Tutorial
|
||||
## Lesson
|
||||
|
||||
Aka **successor graph**.
|
||||
|
||||
<resources>
|
||||
<resource source="CPH" title="16.3, 16.4 - Successor Graphs"></resource>
|
||||
</resources>
|
||||
|
||||
(floyd's algo?)
|
||||
|
||||
## Implementation
|
||||
|
||||
The following sample code counts the number of cycles in such a graph. The "stack" contains nodes that can reach the current node. If the current node points to a node `v` on the stack (`on_stack[v]` is true), then we know that a cycle has been created. However, if the current node points to a node `v` that has been previously visited but is not on the stack, then we know that the current chain of nodes points into a cycle that has already been considered.
|
||||
|
||||
```cpp
|
||||
|
@ -66,7 +71,6 @@ int main()
|
|||
}
|
||||
```
|
||||
|
||||
(floyd's algo?)
|
||||
|
||||
### Problems
|
||||
|
||||
|
|
|
@ -21,8 +21,8 @@ export const metadata = {
|
|||
## Additional Reading
|
||||
|
||||
<resources>
|
||||
<resource source="CPH" title="6"></resource>
|
||||
<resource source="PAPS" title="8"></resource>
|
||||
<resource source="CPH" title="6 - Greedy Algorithms" starred></resource>
|
||||
<resource source="PAPS" title="8 - Greedy Algorithms"></resource>
|
||||
<resource source="CPC" title="5 - Greedy Algorithms" url="05_greedy_algorithms"></resource>
|
||||
</resources>
|
||||
|
||||
|
|
|
@ -29,21 +29,22 @@ export const metadata = {
|
|||
|
||||
A **segment tree** allows you to do point update and range query in $O(\log N)$ time each for any associative operation.
|
||||
|
||||
<info-block title="Pro Tip">
|
||||
|
||||
For gold, you only need to know the basics (ex. sum, min queries). More advanced applications (such as *lazy propagation*) are restricted to platinum.
|
||||
|
||||
</info-block>
|
||||
|
||||
### Tutorials
|
||||
|
||||
<info-block title="Pro Tip">
|
||||
|
||||
For gold, you only need to know the basics (ex. sum, min queries). You can skip more advanced applications such as **lazy propagation** for now.
|
||||
|
||||
</info-block>
|
||||
|
||||
<resources>
|
||||
<resource source="CSA" title="Segment Trees" url="segment_trees" starred>interactive</resource>
|
||||
<resource source="CF" title="Efficient and easy segment trees" url="blog/entry/18051" starred>simple implementation</resource>
|
||||
<resource source="CPH" title="9.3 - Segment Trees" starred>same implementation as above</resource>
|
||||
<resource source="cp-algo" title="Segment Tree" url="data_structures/segment_tree.html"></resource>
|
||||
<resource source="CPC" title="3 - Data Structures" url="03_data_structures" starred>see slides after union-find</resource>
|
||||
<resource source="cp-algo" title="Segment Tree" url="data_structures/segment_tree.html" starred></resource>
|
||||
<resource source="PAPS" title="11.2.3"></resource>
|
||||
<resource source="CPC" title="3 - Data Structures" url="03_data_structures"></resource>
|
||||
</resources>
|
||||
|
||||
### Problems
|
||||
|
|
|
@ -10,6 +10,8 @@ D&C:
|
|||
|
||||
Mowing: http://www.usaco.org/index.php?page=viewproblem2&cpid=926
|
||||
|
||||
Miscellaneous Techniques: https://codeforces.com/blog/entry/47764
|
||||
|
||||
<info-block title="Pro Tip">
|
||||
|
||||
There are [plenty](https://github.com/bqi343/USACO/blob/master/Contests/USACO%20Links/Division-Specific/Platinum.md) of Platinum DP problems that are not covered by this guide; we recommend that you work through these on your own.
|
||||
|
|
|
@ -23,9 +23,6 @@ export const metadata = {
|
|||
new Problem("POI", "Tree Rotations", "https://szkopul.edu.pl/problemset/problem/sUe3qzxBtasek-RAWmZaxY_p/site/?key=statement", "Normal", false, ["Merging", "Indexed Set"], ""),
|
||||
new Problem("Gold", "Favorite Colors", "1042", "Hard", false, ["DSU"], "Small to large merging is mentioned in the editorial, but we were unable to break solutions that just merged naively. Alternatively, just merge linked lists in $O(1)$ time."),
|
||||
],
|
||||
treeRot: [
|
||||
new Problem("POI", "Tree Rotations 2", "https://szkopul.edu.pl/problemset/problem/b0BM0al2crQBt6zovEtJfOc6/site/?key=statement", "Very Hard", false, [], ""),
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -43,21 +40,32 @@ export const metadata = {
|
|||
|
||||
Let's consider a tree rooted at node $1$, where each node has a color.
|
||||
|
||||
For each node, let's store a set containing only that node, and we want to merge the sets in the nodes subtree together such that each node has a set consisting of all colors in the nodes subtree. Doing this allows us to solve a variety of problems, such as query the number of distinct colors in each subtree. Doing this naively, however, yields a runtime complexity of $O(N^2)$.
|
||||
For each node, let's store a set containing only that node, and we want to merge the sets in the nodes subtree together such that each node has a set consisting of all colors in the nodes subtree. Doing this allows us to solve a variety of problems, such as query the number of distinct colors in each subtree.
|
||||
|
||||
However, with just a few lines of code, we can significantly speed this up. Note that [swap](http://www.cplusplus.com/reference/utility/swap/) exchanges two sets in $O(1)$ time.
|
||||
### Naive Solution
|
||||
|
||||
Suppose that we want merge two sets $a$ and $b$ of sizes $n$ and $m$, respectively. One possiblility is the following:
|
||||
|
||||
```cpp
|
||||
if(a.size() < b.size()){ //for two sets a and b
|
||||
swap(a,b);
|
||||
}
|
||||
for (int x: b) a.insert(x);
|
||||
```
|
||||
|
||||
By merging the smaller set into the larger one, the runtime complexity becomes $O(N\log^2N)$.
|
||||
which runs in $O(m\log (n+m))$ time, yielding a runtime of $O(N^2\log N)$ in the worst case. If we instead maintain $a$ and $b$ as sorted vectors, we can merge them in $O(n+m)$ time, but $O(N^2)$ is also too slow.
|
||||
|
||||
### Proof
|
||||
### Better Solution
|
||||
|
||||
When merging two sets, you move from the smaller set to the larger set. If the size of the smaller set is $X$, then the size of the resulting set is at least $2X$. Thus, an element that has been moved $Y$ times will be in a set of size $2^Y$, and since the maximum size of a set is $N$ (the root), each element will be moved at most $O(\log N$) times leading to a total complexity of $O(N\log N)$.
|
||||
With just one additional line of code, we can significantly speed this up.
|
||||
|
||||
```cpp
|
||||
if (a.size() < b.size()) swap(a,b);
|
||||
for (int x: b) a.insert(x);
|
||||
```
|
||||
|
||||
Note that [swap](http://www.cplusplus.com/reference/utility/swap/) exchanges two sets in $O(1)$ time. Thus, merging a smaller set of size $m$ into the larger one of size $n$ takes $O(m\log n)$ time.
|
||||
|
||||
**Claim:** The solution runs in $O(N\log^2N)$ time.
|
||||
|
||||
**Proof:** When merging two sets, you move from the smaller set to the larger set. If the size of the smaller set is $X$, then the size of the resulting set is at least $2X$. Thus, an element that has been moved $Y$ times will be in a set of size at least $2^Y$, and since the maximum size of a set is $N$ (the root), each element will be moved at most $O(\log N$) times.
|
||||
|
||||
<spoiler title="Full Code">
|
||||
|
||||
|
@ -165,15 +173,8 @@ int main() {
|
|||
|
||||
(also: same solution w/o indexed set)
|
||||
|
||||
## Faster Merging (Optional)
|
||||
<optional-content title="Faster Merging">
|
||||
|
||||
It's easy to merge two sets of sizes $n\ge m$ in $O(n+m)$ or $(m\log n)$ time, but sometimes $O\left(m\log 1+\frac{n}{m}\right)$ can be significantly better than both of these.
|
||||
It's easy to merge two sets of sizes $n\ge m$ in $O(n+m)$ or $(m\log n)$ time, but sometimes $O\left(m\log \left(1+\frac{n}{m}\right)\right)$ can be significantly better than both of these. Check "Advanced - Treaps" for more details. Also see [this link](https://codeforces.com/blog/entry/49446) regarding merging segment trees.
|
||||
|
||||
<resources>
|
||||
<resource source="CF" title="Splitting & Merging Segment Trees" url="https://codeforces.com/blog/entry/49446"></resource>
|
||||
<resource source="CF" title="Splitting & Merging BSTs" url="https://codeforces.com/blog/entry/67980"></resource>
|
||||
</resources>
|
||||
|
||||
Requires knowledge of BSTs such as treaps or splay trees.
|
||||
|
||||
<problems-list problems={metadata.problems.treeRot} />
|
||||
</optional-content>
|
|
@ -62,7 +62,12 @@ Binary Indexed Trees can support range increments in addition to range sum queri
|
|||
|
||||
### Tutorial
|
||||
|
||||
- CPH 28.1 (Segment Trees Revisited)
|
||||
<resources>
|
||||
<resource source="CPH" title="28.1 - Segment Trees Revisited" starred>short description</resource>
|
||||
<resource source="CSA" title="Segment Trees" url="segment_trees" starred>interactive</resource>
|
||||
<resource source="cp-algo" title="Segment Tree" url="data_structures/segment_tree.html" starred>adding on segments, assigning</resource>
|
||||
<resource source="CF" title="Efficient and easy segment trees" url="blog/entry/18051">code is more confusing than recursive version</resource>
|
||||
</resources>
|
||||
|
||||
### Problems
|
||||
|
||||
|
|
|
@ -8,9 +8,96 @@ prerequisites:
|
|||
frequency: 2
|
||||
---
|
||||
|
||||
<info-block title="Pro Tip">
|
||||
Historically restricted to USACO Camp (aside from the exception below).
|
||||
</info-block>
|
||||
import { Problem } from "../models";
|
||||
|
||||
export const metadata = {
|
||||
problems: {
|
||||
treeRot: [
|
||||
new Problem("POI", "Tree Rotations 2", "https://szkopul.edu.pl/problemset/problem/b0BM0al2crQBt6zovEtJfOc6/site/?key=statement", "Normal", false, [], ""),
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
## Merging
|
||||
|
||||
## Splitting
|
||||
|
||||
## Merging (Arbitrary Keys)
|
||||
|
||||
<problems-list problems={metadata.problems.treeRot} />
|
||||
|
||||
|
||||
<spoiler title="Tree Rotations 2 Solution">
|
||||
|
||||
Apparently [this paper](https://www.cs.cmu.edu/~scandal/papers/treaps-spaa98.pdf) proves that this runs in $O(n\log n)$.
|
||||
|
||||
```cpp
|
||||
int n;
|
||||
ll ans, inv;
|
||||
|
||||
typedef struct tnode* pt;
|
||||
struct tnode {
|
||||
int pri, val; pt c[2]; // essential
|
||||
int sz; // for range queries
|
||||
tnode (int _val) {
|
||||
pri = rng(); val = _val;
|
||||
sz = 1; c[0] = c[1] = NULL;
|
||||
}
|
||||
};
|
||||
int getsz(pt x) { return x?x->sz:0; }
|
||||
pt calc(pt x) {
|
||||
x->sz = 1+getsz(x->c[0])+getsz(x->c[1]);
|
||||
return x;
|
||||
}
|
||||
pair<pt,pt> split(pt t, int v) { // >= v goes to the right
|
||||
if (!t) return {t,t};
|
||||
if (t->val >= v) {
|
||||
auto p = split(t->c[0], v); t->c[0] = p.s;
|
||||
return {p.f,calc(t)};
|
||||
} else {
|
||||
auto p = split(t->c[1], v); t->c[1] = p.f;
|
||||
return {calc(t),p.s};
|
||||
}
|
||||
}
|
||||
|
||||
pt merge(pt a, pt b) {
|
||||
if (!a || !b) return a?:b;
|
||||
if (a->pri > b->pri) {
|
||||
auto B = split(b,a->val);
|
||||
inv += (ll)(1+getsz(a->c[0]))*getsz(B.s);
|
||||
a->c[0] = merge(a->c[0],B.f); a->c[1] = merge(a->c[1],B.s);
|
||||
return calc(a);
|
||||
} else {
|
||||
auto A = split(a,b->val);
|
||||
inv += (ll)getsz(A.f)*(1+getsz(b->c[1]));
|
||||
b->c[0] = merge(A.f,b->c[0]); b->c[1] = merge(A.s,b->c[1]);
|
||||
return calc(b);
|
||||
}
|
||||
}
|
||||
|
||||
pt go() {
|
||||
int x; re(x);
|
||||
if (x) return new tnode(x);
|
||||
pt L = go(); pt R = go();
|
||||
ll tot = (ll)L->sz*R->sz; inv = 0;
|
||||
pt cur = merge(L,R); assert(inv <= tot); // dbg("HUH",tot,inv);
|
||||
ans += min(inv,tot-inv);
|
||||
return cur;
|
||||
}
|
||||
|
||||
int main() {
|
||||
setIO(); re(n); go();
|
||||
ps(ans);
|
||||
}
|
||||
```
|
||||
|
||||
</spoiler>
|
||||
|
||||
<optional-content>
|
||||
|
||||
[This](https://codeforces.com/blog/entry/67980) CF post describes a more general version of the problem above.
|
||||
|
||||
</optional-content>
|
||||
|
||||
## Tutorial
|
||||
|
||||
|
|
|
@ -24,6 +24,7 @@ const ModuleOrdering: {[key: string]: ModuleOrderingItem[]} = {
|
|||
{
|
||||
name: "Language-Specific",
|
||||
items: [
|
||||
"io-speed",
|
||||
"why-cpp",
|
||||
"macros",
|
||||
"debugging",
|
||||
|
|
|
@ -33,7 +33,7 @@ const Frequency = ({ frequency }: { frequency: ModuleFrequency }) => {
|
|||
'Rare (1-2 times)',
|
||||
'Not Frequent (3-4 times)',
|
||||
'Somewhat Frequent',
|
||||
'Very Frequent (historically ~ once per contest)',
|
||||
'Very Frequent (historically at least once per contest)',
|
||||
];
|
||||
|
||||
return (
|
||||
|
|
Reference in a new issue