remove general section

This commit is contained in:
Nathan Wang 2020-07-14 15:46:55 -07:00
parent f357195197
commit dc142686db
16 changed files with 294 additions and 408 deletions

View file

@ -1,31 +1,62 @@
---
id: debugging
title: Debugging C++
author: Benjamin Qi, Aaron Chew
description: Detecting issues within your program and figuring out how to avoid them in the first place.
---
## General
# Debugging C++
<resources>
<resource source="Errichto" title="Video - How to test your solution" url="https://www.youtube.com/watch?v=JXTVOyQpSGM" starred>using a script to stress test</resource>
<resource source="Errichto" title="Asking for help FAQ" url="https://codeforces.com/blog/entry/64993" starred>some parts from above video</resource>
<resource
source="Errichto"
title="Video - How to test your solution"
url="https://www.youtube.com/watch?v=JXTVOyQpSGM"
starred
>
using a script to stress test
</resource>
<resource
source="Errichto"
title="Asking for help FAQ"
url="https://codeforces.com/blog/entry/64993"
starred
>
some parts from above video
</resource>
</resources>
## Within Your Program
### Style
### Style
<resources>
<resource source="CF" title="Competitive C++ Manifesto: A Style Guide" url="blog/entry/64218" starred> don't agree with everything but important to read nonetheless</resource>
<resource
source="CF"
title="Competitive C++ Manifesto: A Style Guide"
url="blog/entry/64218"
starred
>
{' '}
don't agree with everything but important to read nonetheless
</resource>
</resources>
### Assertions & Warnings
<resources>
<resource title="Asserts" source="LearnCpp" url="https://www.learncpp.com/cpp-tutorial/7-12a-assert-and-static_assert/" starred>includes static_assert and #define NDEBUG</resource>
<resource title="Assertions" source="GFG" url="assertions-cc">subset of above</resource>
<resource title="Diagnostics" source="GNU" url="https://gcc.gnu.org/onlinedocs/cpp/Diagnostics.html" starred>#warning, #error</resource>
<resource
title="Asserts"
source="LearnCpp"
url="https://www.learncpp.com/cpp-tutorial/7-12a-assert-and-static_assert/"
starred
>
includes static_assert and #define NDEBUG
</resource>
<resource title="Assertions" source="GFG" url="assertions-cc">
subset of above
</resource>
<resource
title="Diagnostics"
source="GNU"
url="https://gcc.gnu.org/onlinedocs/cpp/Diagnostics.html"
starred
>
#warning, #error
</resource>
</resources>
### Printing Variables
@ -51,7 +82,7 @@ According to [this comment](https://codeforces.com/blog/entry/60999?#comment-449
### [Warning Options](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html)
`-Wall -Wextra -Wshadow`
`-Wall -Wextra -Wshadow`
[Variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) should be avoided whenever possible.
@ -94,10 +125,10 @@ AddressSanitizer:DEADLYSIGNAL
#1 0x7fff72208cc8 in start (libdyld.dylib:x86_64+0x1acc8)
==31035==Register values:
rax = 0xfffffffffffffffc rbx = 0x00007ffee913aa20 rcx = 0xfffffffffffffffc rdx = 0x20000fffffffffff
rdi = 0x00007ffee913aa40 rsi = 0x1fffffffffffffff rbp = 0x00007ffee913aaa0 rsp = 0x00007ffee913aa20
r8 = 0x0000000000000000 r9 = 0x0000000000000000 r10 = 0x0000000000000000 r11 = 0x0000000000000000
r12 = 0x00000fffdd227544 r13 = 0x00007ffee913aa80 r14 = 0x00007ffee913aa20 r15 = 0x0000000000000000
rax = 0xfffffffffffffffc rbx = 0x00007ffee913aa20 rcx = 0xfffffffffffffffc rdx = 0x20000fffffffffff
rdi = 0x00007ffee913aa40 rsi = 0x1fffffffffffffff rbp = 0x00007ffee913aaa0 rsp = 0x00007ffee913aa20
r8 = 0x0000000000000000 r9 = 0x0000000000000000 r10 = 0x0000000000000000 r11 = 0x0000000000000000
r12 = 0x00000fffdd227544 r13 = 0x00007ffee913aa80 r14 = 0x00007ffee913aa20 r15 = 0x0000000000000000
AddressSanitizer can not provide additional info.
SUMMARY: AddressSanitizer: SEGV (prog:x86_64+0x100001325) in main
==31035==ABORTING
@ -109,15 +140,15 @@ Finally, `g++ prog.cpp -o prog -D_GLIBCXX_DEBUG -g && ./prog` produces:
```
/usr/local/Cellar/gcc/9.2.0_1/include/c++/9.2.0/debug/vector:427:
In function:
std::__debug::vector<_Tp, _Allocator>::reference
std::__debug::vector<_Tp,
_Allocator>::operator[](std::__debug::vector<_Tp,
_Allocator>::size_type) [with _Tp = int; _Allocator =
std::allocator<int>; std::__debug::vector<_Tp, _Allocator>::reference =
int&; std::__debug::vector<_Tp, _Allocator>::size_type = long unsigned
std::__debug::vector<_Tp, _Allocator>::reference
std::__debug::vector<_Tp,
_Allocator>::operator[](std::__debug::vector<_Tp,
_Allocator>::size_type) [with _Tp = int; _Allocator =
std::allocator<int>; std::__debug::vector<_Tp, _Allocator>::reference =
int&; std::__debug::vector<_Tp, _Allocator>::size_type = long unsigned
int]
Error: attempt to subscript container with out-of-bounds index -1, but
Error: attempt to subscript container with out-of-bounds index -1, but
container only holds 0 elements.
Objects involved in the operation:
@ -146,8 +177,8 @@ prog.cpp:6:13: runtime error: index 5 out of bounds for type 'int [5]'
prog.cpp:6:13: runtime error: load of address 0x7ffee0a77a94 with insufficient space for an object of type 'int'
0x7ffee0a77a94: note: pointer points here
b0 7a a7 e0 fe 7f 00 00 25 b0 a5 0f 01 00 00 00 b0 7a a7 e0 fe 7f 00 00 c9 8c 20 72 ff 7f 00 00
^
32766%
^
32766%
```
`g++ prog.cpp -o prog -fsanitize=address && ./prog` produces:
@ -181,7 +212,7 @@ Shadow bytes around the buggy address:
0x1fffdde1c990: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
@ -219,9 +250,9 @@ zsh: segmentation fault ./$1
### Measuring Time & Memory Usage
- [CF Comment](https://codeforces.com/blog/entry/49371?#comment-333749)
- [time -v on Mac](https://stackoverflow.com/questions/32515381/mac-os-x-usr-bin-time-verbose-flag)
- use `gtime`
- [CF Comment](https://codeforces.com/blog/entry/49371?#comment-333749)
- [time -v on Mac](https://stackoverflow.com/questions/32515381/mac-os-x-usr-bin-time-verbose-flag)
- use `gtime`
For example, suppose that `prog.cpp` consists of the following:
@ -277,9 +308,9 @@ You can use a [simple script](https://github.com/bqi343/USACO/blob/master/Implem
(gdb, valgrind?)
Using a debugger varies from language to language and even IDE to different IDE. For now I will describe the basic operations of a debugger.
Using a debugger varies from language to language and even IDE to different IDE. For now I will describe the basic operations of a debugger.
A debugger allows you to pause a code in its execution and see the values as a given point in the debugger.
A debugger allows you to pause a code in its execution and see the values as a given point in the debugger.
To do this, set a "breakpoint" at a certain line of code. When the code runs to that breakpoint, it will pause and you will be able to inspect all the different variables at that certain instance.
@ -287,14 +318,14 @@ There are two more useful and common operations. Once you are at the breakpoint,
In essense, a debugger is a tool to "trace code" for you. It is not much different from just printing the values out at various points in your program.
Pros of using a debugger:
- No need to write print statements so you save time
- You can step through the code in real time
Pros of using a debugger:
- No need to write print statements so you save time
- You can step through the code in real time
Cons of using a debugger:
- You cannot see the overall "output" of your program at each stage. For example, if I wanted to see every single value of `i` in the program, I could not using a debugger.
- Most advanced competitive programmers do not use debuggers; it is quite time inefficient.
- You cannot see the overall "output" of your program at each stage. For example, if I wanted to see every single value of `i` in the program, I could not using a debugger.
- Most advanced competitive programmers do not use debuggers; it is quite time inefficient.
(actual details?)

View file

@ -1,9 +1,4 @@
---
id: io-speed
title: Input / Output Speed
author: Benjamin Qi, Nathan Chen
description: ""
---
# Input/Output
Generally, input and output speed isn't an issue. However, some platinum tasks have relatively large input files. The [USACO Instructions Page](http://www.usaco.org/index.php?page=instructions) briefly mentions some ways of speeding up I/O; let's check that these actually make a difference.
@ -15,9 +10,9 @@ The largest USACO input file I know of is test case 11 of [USACO Platinum - Robo
<CPPSection>
### Method 1: `freopen` with `cin`
### Method 1: `freopen` with `cin`
The slowest method.
The slowest method.
<spoiler title="973ms">
@ -65,6 +60,7 @@ int main() {
else printf("%lld",1000000000000000000LL);
}
```
</spoiler>
### Method 3: `ifstream` and `ofstream`
@ -122,18 +118,30 @@ int main() {
### Significance of `ios_base::sync_with_stdio(0); cin.tie(0);`
Adding this line as the first line of `main()` reduced the runtime of the first method to 254 ms.
Adding this line as the first line of `main()` reduced the runtime of the first method to 254 ms.
<resources>
<resource source="CF" url="blog/entry/5217" title="Yet again on C++ I/O" starred>timing various I/O methods</resource>
<resource source="SO" url="https://stackoverflow.com/questions/31162367/significance-of-ios-basesync-with-stdiofalse-cin-tienull" title="Significance of [above]"> </resource>
<resource
source="CF"
url="blog/entry/5217"
title="Yet again on C++ I/O"
starred
>
timing various I/O methods
</resource>
<resource
source="SO"
url="https://stackoverflow.com/questions/31162367/significance-of-ios-basesync-with-stdiofalse-cin-tienull"
title="Significance of [above]"
>
{' '}
</resource>
</resources>
<br />
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.
</CPPSection>
<JavaSection>
@ -150,20 +158,20 @@ import java.io.*;
//3188ms
public class roboherd_scanner {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("roboherd.in"));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
int N = sc.nextInt();
int K = sc.nextInt();
for(int i = 0; i < N; ++i) {
int M = sc.nextInt(); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = sc.nextInt();
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
@ -177,7 +185,7 @@ A common alternative to reading input for programming contests is [`BufferedRead
Reading input is more complicated when multiple, space-separated values are placed in a single line. In order to individually read the values in each line, the programmer usually uses the `.split()` method in `String` or the `.nextToken()` in [`StringTokenizer`](https://docs.oracle.com/javase/8/docs/api/java/util/StringTokenizer.html). Notice that `StringTokenizer` for splitting strings is slightly faster than `.split()`. Apparently [`StreamTokenizer`](https://docs.oracle.com/javase/8/docs/api/java/io/StreamTokenizer.html) is even faster!
*Reading input with `BufferedReader` and `.split()`*:
_Reading input with `BufferedReader` and `.split()`_:
<spoiler title="1209ms">
@ -187,13 +195,13 @@ import java.io.*;
//1209ms
public class roboherd_buffered_reader_string_split {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("roboherd.in"));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
String[] tokens = br.readLine().split(" ");
int N = Integer.parseInt(tokens[0]);
int K = Integer.parseInt(tokens[1]);
@ -202,17 +210,17 @@ public class roboherd_buffered_reader_string_split {
int M = Integer.parseInt(tokens[0]); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = Integer.parseInt(tokens[j+1]);
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
}
```
</spoiler>
*Reading input with `BufferedReader` and `StringTokenizer`*:
_Reading input with `BufferedReader` and `StringTokenizer`_:
<spoiler title="986ms">
@ -222,13 +230,13 @@ import java.io.*;
//986ms
public class roboherd_buffered_reader_string_tokenizer {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("roboherd.in"));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out")));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
@ -237,16 +245,17 @@ public class roboherd_buffered_reader_string_tokenizer {
int M = Integer.parseInt(st.nextToken()); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = Integer.parseInt(st.nextToken());
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
}
```
</spoiler>
*Reading input with `BufferedReader` and `StreamTokenizer`*:
_Reading input with `BufferedReader` and `StreamTokenizer`_:
<spoiler title="569ms">
@ -264,7 +273,7 @@ public class roboherd {
public static void main(String[] args) throws Exception {
in = new StreamTokenizer(new BufferedReader(new FileReader("roboherd.in")));
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
int N = nextInt();
int K = nextInt();
for(int i = 0; i < N; ++i) {
@ -291,30 +300,30 @@ import java.io.*;
//320ms
public class roboherd_is {
static int P[][] = new int[100000][];
public static void main(String[] args) throws Exception {
FastIO sc = new FastI("roboherd.in");
PrintWriter pw = new PrintWriter(new FileWriter("roboherd.out"));
int N = sc.nextInt();
int K = sc.nextInt();
for(int i = 0; i < N; ++i) {
int M = sc.nextInt(); P[i] = new int[M];
for(int j = 0; j < M; ++j) P[i][j] = sc.nextInt();
}
if(N == 3) pw.println(61);
else pw.println(1000000000000000000L);
pw.close();
}
// new FastI("file_name") to read a file
// new FastI(System.in) to read from stdin
// has similar syntax to Scanner, though much faster :)
static class FastI {
InputStream dis;
byte[] buffer = new byte[1 << 17];
int pointer = 0;
@ -393,6 +402,7 @@ public class roboherd_is {
}
}
```
</spoiler>
The most realistic input method to implement in contest is `BufferedReader`, as it is relatively fast for the amount of code necessary.
@ -442,4 +452,4 @@ When printing to the standard output stream in Java, it is faster to use `new Pr
</JavaSection>
</LanguageSection>
</LanguageSection>

View file

@ -1,25 +1,16 @@
---
id: running-cpp
title: Running C++
author: Nathan Wang, Benjamin Qi, Anthony Wang
description: Options for running C++ both online and locally.
---
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
- can be buggy sometimes
- supports files and file I/O
- [CSAcademy](https://csacademy.com/workspace/)
- pretty nice (unless you get "Estimated Queue Time: ...")
- "saved locally" will not save your code if you close the tab, press Command-S to save.
- [Ideone](http://ideone.com/)
- okay ... has the bare minimum you need for running C++
- make sure your code is not public (see below)
- sometimes erases your code when you first create it (so get in the habit of copying your code first)
- [OnlineGDB](https://www.onlinegdb.com/)
- online compiler with an embedded GDB debugger
- can be buggy sometimes
- supports files and file I/O
- [CSAcademy](https://csacademy.com/workspace/)
- pretty nice (unless you get "Estimated Queue Time: ...")
- "saved locally" will not save your code if you close the tab, press Command-S to save.
- [Ideone](http://ideone.com/)
- okay ... has the bare minimum you need for running C++
- make sure your code is not public (see below)
- sometimes erases your code when you first create it (so get in the habit of copying your code first)
<warning-block>
@ -36,12 +27,34 @@ You can also share code with [pastebin](https://pastebin.com/) or [hastebin](htt
These often have C++ support already built-in.
<resources>
<resource title="Visual Studio Code" url="https://code.visualstudio.com/" starred>Lightweight, fast IDE, but requires some configuration. See <a href="http://www.csc.kth.se/~jsannemo/slask/main.pdf">PAPC 2.1</a> for setup instructions.</resource>
<resource title="Geany" url="https://www.geany.org/" starred>Lightweight, frequently used at IOI.</resource>
<resource title="Visual Studio" url="https://visualstudio.microsoft.com/vs/">Heavier cousin of VS Code. VS Code is better for competitive programming.</resource>
<resource title="Codeblocks" url="http://www.codeblocks.org/">Bad on Mac.</resource>
<resource title="XCode" url="https://developer.apple.com/xcode/">Mac only.</resource>
<resource title="CLion" url="https://www.jetbrains.com/clion/">Requires a license, but <a href="https://www.jetbrains.com/community/education/#students">free for students</a>.</resource>
<resource
title="Visual Studio Code"
url="https://code.visualstudio.com/"
starred
>
Lightweight, fast IDE, but requires some configuration. See{' '}
<a href="http://www.csc.kth.se/~jsannemo/slask/main.pdf">PAPC 2.1</a> for
setup instructions.
</resource>
<resource title="Geany" url="https://www.geany.org/" starred>
Lightweight, frequently used at IOI.
</resource>
<resource title="Visual Studio" url="https://visualstudio.microsoft.com/vs/">
Heavier cousin of VS Code. VS Code is better for competitive programming.
</resource>
<resource title="Codeblocks" url="http://www.codeblocks.org/">
Bad on Mac.
</resource>
<resource title="XCode" url="https://developer.apple.com/xcode/">
Mac only.
</resource>
<resource title="CLion" url="https://www.jetbrains.com/clion/">
Requires a license, but{' '}
<a href="https://www.jetbrains.com/community/education/#students">
free for students
</a>
.
</resource>
</resources>
# Using Command Line
@ -51,22 +64,28 @@ Alternatively, run C++ from the command line and use a text editor of your choic
## Text Editors
<resources>
<resource title="Sublime Text 3" url="https://www.sublimetext.com/" starred>Fast, lightweight. Keeps asking you to purchase a license ...</resource>
<resource title="Atom" url="https://atom.io/">From the makers of Github.</resource>
<resource title="Vim" url="https://www.vim.org/">Classic text editor, usually preinstalled on Linux.</resource>
<resource title="Sublime Text 3" url="https://www.sublimetext.com/" starred>
Fast, lightweight. Keeps asking you to purchase a license ...
</resource>
<resource title="Atom" url="https://atom.io/">
From the makers of Github.
</resource>
<resource title="Vim" url="https://www.vim.org/">
Classic text editor, usually preinstalled on Linux.
</resource>
</resources>
Vim is probably the 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).
### Sublime Text Notes (Ben)
- I prefer the **Mariana** color scheme in place of the default.
- [`subl` symlink](https://www.sublimetext.com/docs/3/osx_command_line.html)
- Using `/usr/local/bin/subl` instead of `~/bin/subl` worked for me on OS X Mojave.
- [Snippets](https://www.granneman.com/webdev/editors/sublime-text/top-features-of-sublime-text/quickly-insert-text-and-code-with-sublime-text-snippets)
- I use [this python script](https://github.com/bqi343/USACO/blob/master/Contests/Tools/Other/makeSnip.py) to update all of my templates. (details?)
- [Package - Sublime Linter (GCC)](https://packagecontrol.io/packages/SublimeLinter-gcc)
- highlights compilation errors and warnings from `-Wall`
- I prefer the **Mariana** color scheme in place of the default.
- [`subl` symlink](https://www.sublimetext.com/docs/3/osx_command_line.html)
- Using `/usr/local/bin/subl` instead of `~/bin/subl` worked for me on OS X Mojave.
- [Snippets](https://www.granneman.com/webdev/editors/sublime-text/top-features-of-sublime-text/quickly-insert-text-and-code-with-sublime-text-snippets)
- I use [this python script](https://github.com/bqi343/USACO/blob/master/Contests/Tools/Other/makeSnip.py) to update all of my templates. (details?)
- [Package - Sublime Linter (GCC)](https://packagecontrol.io/packages/SublimeLinter-gcc)
- highlights compilation errors and warnings from `-Wall`
<!-- - [FastOlympicCoding Addon](https://github.com/Jatana/FastOlympicCoding)
- not that useful
@ -77,6 +96,7 @@ Vim is probably the easiest way to print syntax-highlighted code on Mac, see the
- no need to do this if you just use command line to compile & run
-->
## On Linux
GCC is usually preinstalled on most Linux distros. You can check if it is installed with
@ -114,14 +134,24 @@ Nathan Wang: If you want to code in (neo)vim, you can install WSL and code throu
### Installation
1. Open the **Terminal** application and familiarize yourself with some basic commands.
1. Open the **Terminal** application and familiarize yourself with some basic commands.
<resources>
<resource source="Jim Hoskins" title="Intro to OS X Command Line" url="https://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line" starred></resource>
<resource source="Rahul Saigal" title="Mac Terminal Cheat Sheet" url="https://www.makeuseof.com/tag/mac-terminal-commands-cheat-sheet/" starred></resource>
<resource
source="Jim Hoskins"
title="Intro to OS X Command Line"
url="https://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line"
starred
></resource>
<resource
source="Rahul Saigal"
title="Mac Terminal Cheat Sheet"
url="https://www.makeuseof.com/tag/mac-terminal-commands-cheat-sheet/"
starred
></resource>
</resources>
2. Install XCode command line tools.
2. Install XCode command line tools.
```
xcode-select --install
@ -134,9 +164,9 @@ Nathan Wang: If you want to code in (neo)vim, you can install WSL and code throu
softwareupdate -i -a # installs all updates
```
3. Install [Homebrew](https://brew.sh/).
3. Install [Homebrew](https://brew.sh/).
4. Install gcc with Homebrew.
4. Install gcc with Homebrew.
```
brew install gcc
@ -150,7 +180,7 @@ Nathan Wang: If you want to code in (neo)vim, you can install WSL and code throu
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
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
@ -215,10 +245,10 @@ 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 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)
- `-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 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.

View file

@ -0,0 +1 @@
who cares about java

View file

@ -1,10 +1,3 @@
---
id: running-python
title: Running Python
author: Hankai Zhang
description: Options for running Python both online and locally.
---
## Running Python Locally
Download Python through [the official website](https://python.org). On Windows and Mac, you can download executable files directly; on Linux, you must either download the Python source code and compile from source, or obtain Python through your package manager.

View file

@ -1,16 +1,17 @@
---
id: shorten-cpp
title: Shortening C++ Code
author: Benjamin Qi
description: How to make your code (un?)readable.
---
## Introduction
# Shortening C++
<resources>
<resource source="CPH" title="1.4 - Shortening Code" starred>Read before checking code below.</resource>
<resource source="GFG" url="cc-preprocessors" title="Macros"></resource>
<resource source="GCC" url="https://gcc.gnu.org/onlinedocs/cpp/Macros.html" title="Online Docs - Macros">reference</resource>
<resource source="CPH" title="1.4 - Shortening Code" starred>
Read before checking code below.
</resource>
<resource source="GFG" url="cc-preprocessors" title="Macros"></resource>
<resource
source="GCC"
url="https://gcc.gnu.org/onlinedocs/cpp/Macros.html"
title="Online Docs - Macros"
>
reference
</resource>
</resources>
## [My Template](https://github.com/bqi343/USACO/blob/master/Implementations/content/contest/template.cpp)
@ -32,7 +33,7 @@ Pretty annoying to keep typing `first` and `second` (especially if you have nest
### Vectors
```cpp
typedef vector<int> vi;
typedef vector<int> vi;
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
@ -41,7 +42,7 @@ typedef vector<int> vi;
It's generally a good idea to convert a size to a signed integer before doing anything with it to avoid cases like the following.
```cpp
vi x;
vi x;
cout << x.size()-1 << "\n"; // 18446744073709551615
cout << sz(x)-1 << "\n"; // -1
```
@ -63,7 +64,7 @@ const ll INF = 1e18;
const ld PI = acos((ld)-1);
```
$10^9+7$ is a prime that appears quite frequently in programming contests. Interestingly, $(10^9+7-1)/2=5\cdot 10^8+3$ is also prime. On the other hand, $998244353-1$ is divisible by $2^{23}$, which is useful for [NTT](https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform).
$10^9+7$ is a prime that appears quite frequently in programming contests. Interestingly, $(10^9+7-1)/2=5\cdot 10^8+3$ is also prime. On the other hand, $998244353-1$ is divisible by $2^{23}$, which is useful for [NTT](<https://en.wikipedia.org/wiki/Discrete_Fourier_transform_(general)#Number-theoretic_transform>).
Almost all USACO problems satisfy $N\le 2\cdot 10^5$, so that's what `MX` is for.
@ -78,18 +79,24 @@ See [neal's blog](https://codeforces.com/blog/entry/61587) about why `rand()` is
### Template
```cpp
template<class T> bool ckmin(T& a, const T& b) {
template<class T> bool ckmin(T& a, const T& b) {
return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
return a < b ? a = b, 1 : 0; }
```
See [negCyc](https://github.com/bqi343/USACO/blob/master/Implementations/content/graphs%20(12)/Basics/NegativeCycle%20(7.3).h) for an example of usage.
See [negCyc](<https://github.com/bqi343/USACO/blob/master/Implementations/content/graphs%20(12)/Basics/NegativeCycle%20(7.3).h>) for an example of usage.
### Lambda Expressions
<resources>
<resource source="GFG" url="lambda-expression-in-c" title = "Lambda Expressions in C++"> </resource>
<resource
source="GFG"
url="lambda-expression-in-c"
title="Lambda Expressions in C++"
>
{' '}
</resource>
</resources>
(describe more)
(describe more)

View file

@ -1,6 +1,6 @@
---
id: contest-strategy
title: Contest Strategy
title: (Optional) Contest Strategy
author: Nathan Chen
description: General ideas on how to strategize during a USACO contest.
---

View file

@ -72,7 +72,7 @@ You do not need to learn pointers (for now). Knowledge of structs and classes is
</info-block>
## Resources for Getting Started
## Additional Resources
<resources title="Getting Started">
<resource source="CodeSignal" title="CodeSignal" url="https://codesignal.com/" starred>can practice basics with "Arcade," "Interview Practice"</resource>

View file

@ -1,6 +1,6 @@
---
id: practicing
title: How to Practice
title: (Optional) How to Practice
author: Many
description: How to practice and when to read editorials (analyses) according to various USACO competitors.
---

View file

@ -0,0 +1,34 @@
---
id: running-code
title: Running Code
author: Benjamin Qi, Hankai Zhang, Anthony Wang, Nathan Wang
description: Options for running your language of choice.
---
import RunningCpp from "../../additionalContent/Running_Cpp.mdx";
import RunningJava from "../../additionalContent/Running_Java.mdx";
import RunningPython from "../../additionalContent/Running_Python.mdx";
Please let us know if these installation instructions do not work for you.
<LanguageSection>
<CPPSection>
<RunningCpp />
</CPPSection>
<JavaSection>
<RunningJava />
</JavaSection>
<PySection>
<RunningPython />
</PySection>
</LanguageSection>

View file

@ -1,8 +0,0 @@
---
id: running-java
title: Running Java
author: ?
description: Options for running Java both online and locally.
---
who cares about java

View file

@ -0,0 +1,26 @@
---
id: tips-tricks
title: Tips & Tricks
author: Benjamin Qi, Nathan Chen, Aaron Chew, Nathan Wang
description: "Tips & tricks that will help you code better and faster: I/O speed, Debugging, & Macros."
---
import InputOutput from "../../additionalcontent/Input_Output.mdx";
import DebuggingCpp from "../../additionalContent/Debugging_Cpp.mdx";
import ShortenCpp from "../../additionalContent/Shorten_Cpp.mdx";
<InputOutput />
<LanguageSection>
<CPPSection>
<DebuggingCpp />
<ShortenCpp />
</CPPSection>
<JavaSection />
<PythonSection />
</LanguageSection>

View file

@ -11,10 +11,6 @@ Skipping around is especially recommended for higher level contestants (Gold/Pla
For lower level contestants, the guide is generally designed to be completed in order. There are some exceptions; for example, the last module in "Silver -> Sorting" assumes knowledge of the first two modules in "Silver -> Ordered Sets & Maps." In any case, we will list **prerequisites** to each module as needed.
## The General Section
The following _section_ (not module!) "General" will contain a list of modules not specific to any division. We recommend you read through the ones you find interesting, but **skip the ones that aren't relevant to you!**<Asterisk>However, it's a good idea to read them all eventually :)</Asterisk> This is especially true for those just getting started with Competitive Programming.
## Features of this Guide
As you use this guide, here are some features that you may find helpful:

View file

@ -1,227 +0,0 @@
---
id: why-cpp
title: Why C++?
author: Benjamin Qi
description: Some reasons why choice of language matters significantly outside of USACO Bronze.
---
## Time Limit
Although both Python and Java receive two times the C++ time limit in USACO, this is not the case for most other websites (ex. CodeForces). Even with the extended time limits, Python and Java sometimes have trouble passing.
- Rewriting the C++ solution for [USACO Silver Wormsort](http://www.usaco.org/index.php?page=viewproblem2&cpid=992) in Python receives TLE (Time Limit Exceeded) on 2/10 cases. I'm not sure whether it is possible to pass this problem with Python.
<spoiler title="Python3 8/10 Solution">
```py
# 8/10 test cases ...
fin = open("wormsort.in","r")
lines = [line for line in fin]
N,M = map(int,lines[0].split())
p = list(map(lambda x: int(x)-1,lines[1].split()))
ed = []
for i in range(2,len(lines)):
a,b,w = map(int,lines[i].split())
a -= 1
b -= 1
ed.append([w,a,b])
ed.sort()
ed.reverse()
adj = [[] for i in range(N)]
vis = [0 for i in range(N)]
cnt = 0
def dfs(x):
global cnt
if vis[x] != 0:
return
vis[x] = cnt
for i in adj[x]:
dfs(i)
def ok(mid):
global cnt
for i in range(N):
vis[i] = 0
adj[i].clear()
for i in range(mid):
a,b = ed[i][1],ed[i][2]
adj[a].append(b)
adj[b].append(a)
for i in range(N):
if vis[i] == 0:
cnt += 1
todo = [i]
ind = 0
while ind < len(todo):
x = todo[ind]
ind += 1
vis[x] = cnt
for i in adj[x]:
if vis[i] == 0:
vis[i] = -cnt
todo.append(i)
ok = True
for i in range(N):
if vis[i] != vis[p[i]]:
ok = False
return ok
lo,hi = 0,M
while lo < hi:
mid = (lo+hi)//2
if ok(mid):
hi = mid
else:
lo = mid+1
fout = open("wormsort.out","w")
fout.write(str(-1 if lo == 0 else ed[lo-1][0]))
fout.write('\n')
```
</spoiler>
- A similar solution in Java requires almost 3s, which is fairly close to the time limit of 4s.
<spoiler title="Java Solution">
```java
import java.io.*; // from Nick Wu
import java.util.*;
public class wormsort {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new FileReader("wormsort.in"));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
loc = new int[n];
component = new int[n];
edges = new LinkedList[n];
for(int i = 0; i < n; i++) edges[i] = new LinkedList<>();
lhs = new int[m];
rhs = new int[m];
weight = new int[m];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) loc[i] = Integer.parseInt(st.nextToken())-1;
for(int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
lhs[i] = Integer.parseInt(st.nextToken())-1;
rhs[i] = Integer.parseInt(st.nextToken())-1;
weight[i] = Integer.parseInt(st.nextToken());
}
br.close();
int minW = 0;
int maxW = 1000000001;
while(minW != maxW) {
int mid = (minW + maxW + 1) / 2;
if(valid(mid)) minW = mid;
else maxW = mid-1;
}
if(minW > 1e9) minW = -1;
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("wormsort.out")));
pw.println(minW);
pw.close();
}
static int[] loc, lhs, rhs, weight;
static LinkedList<Integer>[] edges;
static int[] component;
private static void dfs(int curr, int label) {
if(component[curr] == label) return;
component[curr] = label;
for(int child: edges[curr]) dfs(child, label);
}
private static boolean valid(int minW) {
Arrays.fill(component, -1);
for(int i = 0; i < edges.length; i++) edges[i].clear();
for(int i = 0; i < lhs.length; i++) {
if(weight[i] >= minW) {
edges[lhs[i]].add(rhs[i]);
edges[rhs[i]].add(lhs[i]);
}
}
int numcomps = 0;
for(int i = 0; i < component.length; i++) {
if(component[i] < 0) {
dfs(i, numcomps++);
}
}
for(int i = 0; i < loc.length; i++) {
if(component[i] != component[loc[i]]) return false;
}
return true;
}
}
```
</spoiler>
- A comparable C++ solution runs in less than 700ms.
<spoiler title="C++ Solution">
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
const int MX = 1e5+5;
int loc[MX], comp[MX], lhs[MX], rhs[MX], wei[MX];
vi adj[MX];
int n,m;
void dfs(int cur, int label) {
if (comp[cur] == label) return;
comp[cur] = label;
for (int c: adj[cur]) dfs(c,label);
}
bool valid(int minW) {
for (int i = 0; i < n; ++i) {
comp[i] = -1;
adj[i].clear();
}
for (int i = 0; i < m; ++i) if (wei[i] >= minW)
adj[lhs[i]].push_back(rhs[i]), adj[rhs[i]].push_back(lhs[i]);
int numComps = 0;
for (int i = 0; i < n; ++i) if (comp[i] < 0)
dfs(i,numComps++);
for (int i = 0; i < n; ++i)
if (comp[i] != comp[loc[i]]) return 0;
return 1;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
freopen("wormsort.in","r",stdin);
freopen("wormsort.out","w",stdout);
cin >> n >> m;
for (int i = 0; i < n; ++i) cin >> loc[i], loc[i] --;
for (int i = 0; i < m; ++i) {
cin >> lhs[i], lhs[i] --;
cin >> rhs[i], rhs[i] --;
cin >> wei[i];
}
int minW = 0, maxW = (int)1e9+1;
while (minW != maxW) {
int mid = (minW+maxW+1)/2;
if (valid(mid)) minW = mid;
else maxW = mid-1;
}
if (minW > 1e9) minW = -1;
cout << minW;
}
```
</spoiler>
## Other Notes
- USACO problemsetters don't always test Java (and rarely Python) solutions when setting constraints.
- Python lacks a data structure that keeps its keys in sorted order (the equivalent of `set` in C++), which is required for some silver problems.
- Java lacks features such as `#define`, `typedef`, and `auto` that are present in C++ (which some contestants rely on extensively, see "macros").

View file

@ -14,27 +14,20 @@ const ModuleOrdering: {[key: string]: ModuleOrderingItem[]} = {
name: "Languages",
items: [
"lang",
"running-cpp",
"running-java",
"running-python",
"running-code",
"tips-tricks",
]
},
"data-types",
"io",
],
"general": [
"resources",
"practicing",
"contests",
"contest-strategy",
"proposing",
{
name: "Language-Specific",
name: "Other",
items: [
"io-speed",
"why-cpp",
"shorten-cpp",
"debugging",
"resources",
"contests",
"proposing",
]
},
],

View file

@ -196,7 +196,7 @@ export default function Template(props) {
{/* End Hero Section */}
<div className="pb-8" id="content">
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 pb-4">
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 pb-4">
<div
className="mb-8 bg-white shadow-md rounded-lg relative"
style={{ marginTop: '-12rem' }}
@ -237,7 +237,7 @@ export default function Template(props) {
</nav>
</div>
<ol className="list-inside py-8 px-8 text-lg space-y-1">
<ol className="list-inside p-4 sm:p-8 text-lg space-y-1">
{module.map((m, idx) => {
if (m.hasOwnProperty('items')) {
return (