diff --git a/1850/index.html b/1850/index.html new file mode 100644 index 0000000..01b0872 --- /dev/null +++ b/1850/index.html @@ -0,0 +1,1345 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Problems - Codeforces + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + +
+
+ + +
+ +
Codeforces Round 886 (Div. 4)
+
+ +
+
+ + + +
+
+ +
+ +
A. To My Critics
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Suneet has three digits $$$a$$$, $$$b$$$, and $$$c$$$.

Since math isn't his strongest point, he asks you to determine if you can choose any two digits to make a sum greater or equal to $$$10$$$.

Output "YES" if there is such a pair, and "NO" otherwise.

Input

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.

The only line of each test case contains three digits $$$a$$$, $$$b$$$, $$$c$$$ ($$$0 \leq a, b, c \leq 9$$$).

Output

For each test case, output "YES" if such a pair exists, and "NO" otherwise.

You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

Example
Input
5
8 1 2
4 4 5
9 9 9
0 0 0
8 5 3
Output
+YES
+NO
+YES
+NO
+YES
+
Note

For the first test case, by choosing the digits $$$8$$$ and $$$2$$$ we can obtain a sum of $$$8 + 2 = 10$$$ which satisfies the condition, thus the output should be "YES".

For the second test case, any combination of chosen digits won't be at least $$$10$$$, thus the output should be "NO" (note that we can not choose the digit on the same position twice).

For the third test case, any combination of chosen digits will have a sum equal to $$$18$$$, thus the output should be "YES".

+
+ + + + + +
+
+ + +
+ +
B. Ten Words of Wisdom
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

In the game show "Ten Words of Wisdom", there are $$$n$$$ participants numbered from $$$1$$$ to $$$n$$$, each of whom submits one response. The $$$i$$$-th response is $$$a_i$$$ words long and has quality $$$b_i$$$. No two responses have the same quality, and at least one response has length at most $$$10$$$.

The winner of the show is the response which has the highest quality out of all responses that are not longer than $$$10$$$ words. Which response is the winner?

Input

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases.

The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the number of responses.

Then $$$n$$$ lines follow, the $$$i$$$-th of which contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 50$$$) — the number of words and the quality of the $$$i$$$-th response, respectively.

Additional constraints on the input: in each test case, at least one value of $$$i$$$ satisfies $$$a_i \leq 10$$$, and all values of $$$b_i$$$ are distinct.

Output

For each test case, output a single line containing one integer $$$x$$$ ($$$1 \leq x \leq n$$$) — the winner of the show, according to the rules given in the statement.

It can be shown that, according to the constraints in the statement, exactly one winner exists for each test case.

Example
Input
3
5
7 2
12 5
9 3
9 4
10 1
3
1 2
3 4
5 6
1
1 43
Output
+4
+3
+1
+
Note

In the first test case, the responses provided are as follows:

  • Response 1: $$$7$$$ words, quality $$$2$$$
  • Response 2: $$$12$$$ words, quality $$$5$$$
  • Response 3: $$$9$$$ words, quality $$$3$$$
  • Response 4: $$$9$$$ words, quality $$$4$$$
  • Response 5: $$$10$$$ words, quality $$$1$$$

We can see that the responses with indices $$$1$$$, $$$3$$$, $$$4$$$, and $$$5$$$ have lengths not exceeding $$$10$$$ words. Out of these responses, the winner is the one with the highest quality.

Comparing the qualities, we find that:

  • Response 1 has quality $$$2$$$.
  • Response 3 has quality $$$3$$$.
  • Response 4 has quality $$$4$$$.
  • Response 5 has quality $$$1$$$.

Among these responses, Response 4 has the highest quality.

+
+ + + + + +
+
+ + +
+ +
C. Word on the Paper
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

On an $$$8 \times 8$$$ grid of dots, a word consisting of lowercase Latin letters is written vertically in one column, from top to bottom. What is it?

Input

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.

Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each character in the grid is either $$$\texttt{.}$$$ (representing a dot) or a lowercase Latin letter ($$$\texttt{a}$$$–$$$\texttt{z}$$$).

The word lies entirely in a single column and is continuous from the beginning to the ending (without gaps). See the sample input for better understanding.

Output

For each test case, output a single line containing the word made up of lowercase Latin letters ($$$\texttt{a}$$$–$$$\texttt{z}$$$) that is written vertically in one column from top to bottom.

Example
Input
5
........
........
........
........
...i....
........
........
........
........
.l......
.o......
.s......
.t......
........
........
........
........
........
........
........
......t.
......h.
......e.
........
........
........
........
........
.......g
.......a
.......m
.......e
a.......
a.......
a.......
a.......
a.......
a.......
a.......
a.......
Output
+i
+lost
+the
+game
+aaaaaaaa
+

+
+ + + + + +
+
+ + +
+ +
D. Balanced Round
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are the author of a Codeforces round and have prepared $$$n$$$ problems you are going to set, problem $$$i$$$ having difficulty $$$a_i$$$. You will do the following process:

  • remove some (possibly zero) problems from the list;
  • rearrange the remaining problems in any order you wish.

A round is considered balanced if and only if the absolute difference between the difficulty of any two consecutive problems is at most $$$k$$$ (less or equal than $$$k$$$).

What is the minimum number of problems you have to remove so that an arrangement of problems is balanced?

Input

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.

The first line of each test case contains two positive integers $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) and $$$k$$$ ($$$1 \leq k \leq 10^9$$$) — the number of problems, and the maximum allowed absolute difference between consecutive problems.

The second line of each test case contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the difficulty of each problem.

Note that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output

For each test case, output a single integer — the minimum number of problems you have to remove so that an arrangement of problems is balanced.

Example
Input
7
5 1
1 2 4 5 6
1 2
10
8 3
17 3 1 20 12 5 17 12
4 2
2 4 6 8
5 3
2 3 19 10 8
3 4
1 10 5
8 1
8 3 1 4 5 10 7 3
Output
+2
+0
+5
+0
+3
+1
+4
+
Note

For the first test case, we can remove the first $$$2$$$ problems and construct a set using problems with the difficulties $$$[4, 5, 6]$$$, with difficulties between adjacent problems equal to $$$|5 - 4| = 1 \leq 1$$$ and $$$|6 - 5| = 1 \leq 1$$$.

For the second test case, we can take the single problem and compose a round using the problem with difficulty $$$10$$$.

+
+ + + + + +
+
+ + +
+ +
E. Cardboard for Pictures
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Mircea has $$$n$$$ pictures. The $$$i$$$-th picture is a square with a side length of $$$s_i$$$ centimeters.

He mounted each picture on a square piece of cardboard so that each picture has a border of $$$w$$$ centimeters of cardboard on all sides. In total, he used $$$c$$$ square centimeters of cardboard. Given the picture sizes and the value $$$c$$$, can you find the value of $$$w$$$?

A picture of the first test case. Here $$$c = 50 = 5^2 + 4^2 + 3^2$$$, so $$$w=1$$$ is the answer.

Please note that the piece of cardboard goes behind each picture, not just the border.

Input

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases.

The first line of each test case contains two positive integers $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) and $$$c$$$ ($$$1 \leq c \leq 10^{18}$$$) — the number of paintings, and the amount of used square centimeters of cardboard.

The second line of each test case contains $$$n$$$ space-separated integers $$$s_i$$$ ($$$1 \leq s_i \leq 10^4$$$) — the sizes of the paintings.

The sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Additional constraint on the input: Such an integer $$$w$$$ exists for each test case.

Please note, that some of the input for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

Output

For each test case, output a single integer — the value of $$$w$$$ ($$$w \geq 1$$$) which was used to use exactly $$$c$$$ squared centimeters of cardboard.

Example
Input
+10
+3 50
+3 2 1
+1 100
+6
+5 500
+2 2 2 2 2
+2 365
+3 4
+2 469077255466389
+10000 2023
+10 635472106413848880
+9181 4243 7777 1859 2017 4397 14 9390 2245 7225
+7 176345687772781240
+9202 9407 9229 6257 7743 5738 7966
+14 865563946464579627
+3654 5483 1657 7571 1639 9815 122 9468 3079 2666 5498 4540 7861 5384
+19 977162053008871403
+9169 9520 9209 9013 9300 9843 9933 9454 9960 9167 9964 9701 9251 9404 9462 9277 9661 9164 9161
+18 886531871815571953
+2609 10 5098 9591 949 8485 6385 4586 1064 5412 6564 8460 2245 6552 5089 8353 3803 3764
+
Output
+1
+2
+4
+5
+7654321
+126040443
+79356352
+124321725
+113385729
+110961227
+
Note

The first test case is explained in the statement.

For the second test case, the chosen $$$w$$$ was $$$2$$$, thus the only cardboard covers an area of $$$c = (2 \cdot 2 + 6)^2 = 10^2 = 100$$$ squared centimeters.

For the third test case, the chosen $$$w$$$ was $$$4$$$, which obtains the covered area $$$c = (2 \cdot 4 + 2)^2 \times 5 = 10^2 \times 5 = 100 \times 5 = 500$$$ squared centimeters.

+
+ + + + + +
+
+ + +
+ +
F. We Were Both Children
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Mihai and Slavic were looking at a group of $$$n$$$ frogs, numbered from $$$1$$$ to $$$n$$$, all initially located at point $$$0$$$. Frog $$$i$$$ has a hop length of $$$a_i$$$.

Each second, frog $$$i$$$ hops $$$a_i$$$ units forward. Before any frogs start hopping, Slavic and Mihai can place exactly one trap in a coordinate in order to catch all frogs that will ever pass through the corresponding coordinate.

However, the children can't go far away from their home so they can only place a trap in the first $$$n$$$ points (that is, in a point with a coordinate between $$$1$$$ and $$$n$$$) and the children can't place a trap in point $$$0$$$ since they are scared of frogs.

Can you help Slavic and Mihai find out what is the maximum number of frogs they can catch using a trap?

Input

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows.

The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the number of frogs, which equals the distance Slavic and Mihai can travel to place a trap.

The second line of each test case contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the lengths of the hops of the corresponding frogs.

It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Output

For each test case output a single integer — the maximum number of frogs Slavic and Mihai can catch using a trap.

Example
Input
7
5
1 2 3 4 5
3
2 2 2
6
3 1 3 4 9 10
9
1 3 2 4 2 3 7 8 5
1
10
8
7 11 6 8 12 4 4 8
10
9 11 9 12 1 7 2 5 8 10
Output
+3
+3
+3
+5
+0
+4
+4
+
Note

In the first test case, the frogs will hop as follows:

  • Frog 1: $$$0 \to 1 \to 2 \to 3 \to \mathbf{\color{red}{4}} \to \cdots$$$
  • Frog 2: $$$0 \to 2 \to \mathbf{\color{red}{4}} \to 6 \to 8 \to \cdots$$$
  • Frog 3: $$$0 \to 3 \to 6 \to 9 \to 12 \to \cdots$$$
  • Frog 4: $$$0 \to \mathbf{\color{red}{4}} \to 8 \to 12 \to 16 \to \cdots$$$
  • Frog 5: $$$0 \to 5 \to 10 \to 15 \to 20 \to \cdots$$$
Therefore, if Slavic and Mihai put a trap at coordinate $$$4$$$, they can catch three frogs: frogs 1, 2, and 4. It can be proven that they can't catch any more frogs.

In the second test case, Slavic and Mihai can put a trap at coordinate $$$2$$$ and catch all three frogs instantly.

+
+ + + + + +
+
+ + +
+ +
G. The Morning Star
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

A compass points directly toward the morning star. It can only point in one of eight directions: the four cardinal directions (N, S, E, W) or some combination (NW, NE, SW, SE). Otherwise, it will break.

The directions the compass can point.

There are $$$n$$$ distinct points with integer coordinates on a plane. How many ways can you put a compass at one point and the morning star at another so that the compass does not break?

Input

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows.

The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$) — the number of points.

Then $$$n$$$ lines follow, each line containing two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^9 \leq x_i, y_i \leq 10^9$$$) — the coordinates of each point, all points have distinct coordinates.

It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output

For each test case, output a single integer — the number of pairs of points that don't break the compass.

Example
Input
5
3
0 0
-1 -1
1 1
4
4 5
5 7
6 9
10 13
3
-1000000000 1000000000
0 0
1000000000 -1000000000
5
0 0
2 2
-1 5
-1 10
2 11
3
0 0
-1 2
1 -2
Output
+6
+2
+6
+8
+0
+
Note

In the first test case, any pair of points won't break the compass:

  • The compass is at $$$(0,0)$$$, the morning star is at $$$(-1,-1)$$$: the compass will point $$$\text{SW}$$$.
  • The compass is at $$$(0,0)$$$, the morning star is at $$$(1,1)$$$: the compass will point $$$\text{NE}$$$.
  • The compass is at $$$(-1,-1)$$$, the morning star is at $$$(0,0)$$$: the compass will point $$$\text{NE}$$$.
  • The compass is at $$$(-1,-1)$$$, the morning star is at $$$(1,1)$$$: the compass will point $$$\text{NE}$$$.
  • The compass is at $$$(1,1)$$$, the morning star is at $$$(0,0)$$$: the compass will point $$$\text{SW}$$$.
  • The compass is at $$$(1,1)$$$, the morning star is at $$$(-1,-1)$$$: the compass will point $$$\text{SW}$$$.

In the second test case, only two pairs of points won't break the compass:

  • The compass is at $$$(6,9)$$$, the morning star is at $$$(10,13)$$$: the compass will point $$$\text{NE}$$$.
  • The compass is at $$$(10,13)$$$, the morning star is at $$$(6,9)$$$: the compass will point $$$\text{SW}$$$.

+
+ + + + + +
+
+ + +
+ +
H. The Third Letter
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

In order to win his toughest battle, Mircea came up with a great strategy for his army. He has $$$n$$$ soldiers and decided to arrange them in a certain way in camps. Each soldier has to belong to exactly one camp, and there is one camp at each integer point on the $$$x$$$-axis (at points $$$\cdots, -2, -1, 0, 1, 2, \cdots$$$).

The strategy consists of $$$m$$$ conditions. Condition $$$i$$$ tells that soldier $$$a_i$$$ should belong to a camp that is situated $$$d_i$$$ meters in front of the camp that person $$$b_i$$$ belongs to. (If $$$d_i < 0$$$, then $$$a_i$$$'s camp should be $$$-d_i$$$ meters behind $$$b_i$$$'s camp.)

Now, Mircea wonders if there exists a partition of soldiers that respects the condition and he asks for your help! Answer "YES" if there is a partition of the $$$n$$$ soldiers that satisfies all of the $$$m$$$ conditions and "NO" otherwise.

Note that two different soldiers may be placed in the same camp.

Input

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases.

The first line of each test case contains two positive integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$; $$$1 \leq m \leq n$$$) — the number of soldiers, and the number of conditions respectively.

Then $$$m$$$ lines follow, each of them containing $$$3$$$ integers: $$$a_i$$$, $$$b_i$$$, $$$d_i$$$ ($$$a_i \neq b_i$$$; $$$1 \leq a_i, b_i \leq n$$$; $$$-10^9 \leq d_i \leq 10^9$$$) — denoting the conditions explained in the statement. Note that if $$$d_i$$$ is positive, $$$a_i$$$ should be $$$d_i$$$ meters in front of $$$b_i$$$ and if it is negative, $$$a_i$$$ should be $$$-d_i$$$ meters behind $$$b_i$$$.

Note that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

Output

For each test case, output "YES" if there is an arrangement of the $$$n$$$ soldiers that satisfies all of the $$$m$$$ conditions and "NO" otherwise.

Example
Input
4
5 3
1 2 2
2 3 4
4 2 -6
6 5
1 2 2
2 3 4
4 2 -6
5 4 4
3 5 100
2 2
1 2 5
1 2 4
4 1
1 2 3
Output
+YES
+NO
+NO
+YES
+
Note

For the first test case, we can partition the soldiers into camps in the following way: soldier:

  • Soldier $$$1$$$ in the camp with the coordinate $$$x = 3$$$.
  • Soldier $$$2$$$ in the camp with the coordinate $$$x = 5$$$.
  • Soldier $$$3$$$ in the camp with the coordinate $$$x = 9$$$.
  • Soldier $$$4$$$ in the camp with the coordinate $$$x = 11$$$.

For the second test case, there is no partition that can satisfy all the constraints at the same time.

For the third test case, there is no partition that satisfies all the constraints since we get contradictory information about the same pair.

For the fourth test case, in order to satisfy the only condition, a possible partition is:

  • Soldier $$$1$$$ in the camp with the coordinate $$$x = 10$$$.
  • Soldier $$$2$$$ in the camp with the coordinate $$$x = 13$$$.
  • Soldier $$$3$$$ in the camp with the coordinate $$$x = -2023$$$.
  • Soldier $$$4$$$ in the camp with the coordinate $$$x = -2023$$$.

+
+ + + + + +
+
+ + + +
+
+ + + diff --git a/1850/src/bin/a.rs b/1850/src/bin/a.rs new file mode 100644 index 0000000..409cbfd --- /dev/null +++ b/1850/src/bin/a.rs @@ -0,0 +1,134 @@ +#![allow(unused_imports)] + +use self::input::*; +use self::math::*; +use self::output::*; + +fn can_make(mut nums: Vec) -> bool { + nums.sort(); + nums[1] + nums[2] >= 10 +} + +fn solve(s: &mut Scanner) { + let nums = s.next_vec::(3); + yesno(can_make(nums)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example() { + assert!(can_make(vec![8, 1, 2])); + assert!(!can_make(vec![4, 4, 5])); + assert!(can_make(vec![9, 9, 9])); + assert!(!can_make(vec![0, 0, 0])); + assert!(can_make(vec![8, 5, 3])); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/b.rs b/1850/src/bin/b.rs new file mode 100644 index 0000000..84b2d30 --- /dev/null +++ b/1850/src/bin/b.rs @@ -0,0 +1,151 @@ +#![allow(unused_imports)] + +use self::input::*; +use self::math::*; +use self::output::*; + +fn find_idx(responses: &[Vec]) -> usize { + let mut found_idx = responses.len(); + let mut found_quality = -1; + + for (i, r) in responses.iter().enumerate().filter(|(_, r)| r[0] <= 10) { + if r[1] > found_quality { + found_idx = i + 1; + found_quality = r[1]; + } + } + + found_idx +} + +fn solve(s: &mut Scanner) { + let n = s.next::(); + let input: Vec> = (0..n).map(|_| s.next_vec::(2)).collect(); + println!("{}", find_idx(&input)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn examples() { + assert_eq!( + find_idx(&vec![ + vec![7, 2], + vec![12, 5], + vec![9, 3], + vec![9, 4], + vec![10, 1], + ]), + 4 + ); + assert_eq!(find_idx(&vec![vec![1, 2], vec![3, 4], vec![5, 6],]), 3); + assert_eq!(find_idx(&vec![vec![1, 43]]), 1); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/c.rs b/1850/src/bin/c.rs new file mode 100644 index 0000000..bea310c --- /dev/null +++ b/1850/src/bin/c.rs @@ -0,0 +1,210 @@ +#![allow(unused_imports)] + +use self::input::*; +use self::math::*; +use self::output::*; + +fn follow(grid: &[Vec], mut y: usize, x: usize) -> String { + let mut found: String = String::new(); + + while y < grid.len() && grid[y][x] != '.' { + found.push(grid[y][x]); + y += 1; + } + + found +} + +fn find_word(grid: &[Vec]) -> String { + for (y, x) in (0..8).flat_map(|y| (0..8).map(move |x| (y, x))) { + if grid[y][x] != '.' { + return follow(grid, y, x); + } + } + + unreachable!() +} + +fn solve(s: &mut Scanner) { + let lines: Vec> = s + .next_vec::(8) + .into_iter() + .map(|l| l.chars().collect()) + .collect(); + + println!("{}", find_word(&lines)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn examples() { + assert_eq!( + find_word( + &vec![ + "........", "........", "........", "........", "...i....", "........", + "........", "........", + ] + .iter() + .map(|s| s.chars().collect::>()) + .collect::>>() + ), + "i".to_owned() + ); + assert_eq!( + find_word( + &vec![ + "........", ".l......", ".o......", ".s......", ".t......", "........", + "........", "........", + ] + .iter() + .map(|s| s.chars().collect::>()) + .collect::>>() + ), + "lost".to_owned() + ); + assert_eq!( + find_word( + &vec![ + "........", "........", "........", "........", "......t.", "......h.", + "......e.", "........", + ] + .iter() + .map(|s| s.chars().collect::>()) + .collect::>>() + ), + "the".to_owned() + ); + assert_eq!( + find_word( + &vec![ + "........", "........", "........", "........", ".......g", ".......a", + ".......m", ".......e", + ] + .iter() + .map(|s| s.chars().collect::>()) + .collect::>>() + ), + "game".to_owned() + ); + assert_eq!( + find_word( + &vec![ + "a.......", "a.......", "a.......", "a.......", "a.......", "a.......", + "a.......", "a.......", + ] + .iter() + .map(|s| s.chars().collect::>()) + .collect::>>() + ), + "aaaaaaaa".to_owned() + ); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/d.rs b/1850/src/bin/d.rs new file mode 100644 index 0000000..452dfa4 --- /dev/null +++ b/1850/src/bin/d.rs @@ -0,0 +1,155 @@ +#![allow(unused_imports)] + +// region ‹use› +use self::input::*; +use self::math::*; +use self::output::*; +use std::cmp::{max, min}; +// endregion ‹use› + +fn min_to_satisfy(k: i32, mut diffs: Vec) -> i32 { + diffs.sort(); + + let mut longest = 0; + let mut current_longest = 1; + for (&x, &y) in diffs.iter().zip(diffs.iter().skip(1)) { + if y - x > k { + longest = max(longest, current_longest); + current_longest = 1; + } else { + current_longest += 1; + } + } + longest = max(longest, current_longest); + + diffs.len() as i32 - longest +} + +fn solve(s: &mut Scanner) { + let n = s.next::(); + let k = s.next::(); + let diffs = s.next_vec::(n); + + println!("{}", min_to_satisfy(k, diffs)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn examples() { + assert_eq!(min_to_satisfy(1, vec![1, 2, 4, 5, 6]), 2); + assert_eq!(min_to_satisfy(2, vec![10]), 0); + assert_eq!(min_to_satisfy(3, vec![17, 3, 1, 20, 12, 5, 17, 12]), 5); + assert_eq!(min_to_satisfy(2, vec![2, 4, 6, 8]), 0); + assert_eq!(min_to_satisfy(3, vec![2, 3, 19, 10, 8]), 3); + assert_eq!(min_to_satisfy(4, vec![1, 10, 5]), 1); + assert_eq!(min_to_satisfy(1, vec![8, 3, 1, 4, 5, 10, 7, 3]), 4); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/e.rs b/1850/src/bin/e.rs new file mode 100644 index 0000000..ab96050 --- /dev/null +++ b/1850/src/bin/e.rs @@ -0,0 +1,286 @@ +#![allow(unused_imports)] + +// region ‹use› +use self::input::*; +use self::math::*; +use self::output::*; +use std::cmp::{max, min}; +// endregion ‹use› + +fn find_w(covered: i64, sizes: Vec) -> i64 { + let s: i64 = sizes.iter().sum(); + let s_squared: i64 = sizes.iter().map(|s| s * s).sum(); + + let a = 4 * sizes.len() as i128; + let b = (4 * s) as i128; + let c = (s_squared - covered) as i128; + let d = b * b - 4 * a * c; + + ((-b + d.isqrt()) / (2 * a)).try_into().unwrap() +} + +fn solve(s: &mut Scanner) { + let n = s.next::(); + let c = s.next::(); + let sizes = s.next_vec::(n); + println!("{}", find_w(c, sizes)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn examples() { + assert_eq!(find_w(50, vec![3, 2, 1]), 1); + assert_eq!(find_w(100, vec![6]), 2); + assert_eq!(find_w(500, vec![2, 2, 2, 2, 2]), 4); + assert_eq!(find_w(365, vec![3, 4]), 5); + assert_eq!(find_w(469077255466389, vec![10000, 2023]), 7654321); + assert_eq!( + find_w( + 635472106413848880, + vec![9181, 4243, 7777, 1859, 2017, 4397, 14, 9390, 2245, 7225] + ), + 126040443 + ); + assert_eq!( + find_w( + 176345687772781240, + vec![9202, 9407, 9229, 6257, 7743, 5738, 7966] + ), + 79356352 + ); + assert_eq!( + find_w( + 865563946464579627, + vec![ + 3654, 5483, 1657, 7571, 1639, 9815, 122, 9468, 3079, 2666, 5498, 4540, 7861, + 5384 + ] + ), + 124321725 + ); + assert_eq!( + find_w( + 977162053008871403, + vec![ + 9169, 9520, 9209, 9013, 9300, 9843, 9933, 9454, 9960, 9167, 9964, 9701, 9251, + 9404, 9462, 9277, 9661, 9164, 9161 + ] + ), + 113385729 + ); + assert_eq!( + find_w( + 886531871815571953, + vec![ + 2609, 10, 5098, 9591, 949, 8485, 6385, 4586, 1064, 5412, 6564, 8460, 2245, + 6552, 5089, 8353, 3803, 3764 + ] + ), + 110961227 + ); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } + + /// A trait implementing the unsigned bit shifts. + pub trait UnsignedShift { + fn unsigned_shl(self, n: u32) -> Self; + fn unsigned_shr(self, n: u32) -> Self; + } + + /// A trait implementing the integer square root. + pub trait ISqrt { + /// Find the integer square root. + /// + /// See [Integer_square_root on wikipedia][wiki_article] for more information (and also the + /// source of this algorithm) + /// + /// # Panics + /// + /// For negative numbers (`i` family) this function will panic on negative input + /// + /// [wiki_article]: https://en.wikipedia.org/wiki/Integer_square_root + fn isqrt(&self) -> Self + where + Self: Sized, + { + self.isqrt_checked() + .expect("cannot calculate square root of negative number") + } + + /// Find the integer square root, returning `None` if the number is negative (this can never + /// happen for unsigned types). + fn isqrt_checked(&self) -> Option + where + Self: Sized; + } + + macro_rules! math_traits_impl { + ($T:ty, $U: ty) => { + impl UnsignedShift for $T { + #[inline] + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + #[inline] + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + } + + impl ISqrt for $T { + #[inline] + fn isqrt_checked(&self) -> Option { + use core::cmp::Ordering; + match self.cmp(&<$T>::default()) { + // Hopefully this will be stripped for unsigned numbers (impossible condition) + Ordering::Less => return None, + Ordering::Equal => return Some(<$T>::default()), + _ => {} + } + + // Compute bit, the largest power of 4 <= n + let max_shift: u32 = <$T>::default().leading_zeros() - 1; + let shift: u32 = (max_shift - self.leading_zeros()) & !1; + let mut bit = <$T>::try_from(1).unwrap().unsigned_shl(shift); + + // Algorithm based on the implementation in: + // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2) + // Note that result/bit are logically unsigned (even if T is signed). + let mut n = *self; + let mut result = <$T>::default(); + while bit != <$T>::default() { + if n >= (result + bit) { + n -= result + bit; + result = result.unsigned_shr(1) + bit; + } else { + result = result.unsigned_shr(1); + } + bit = bit.unsigned_shr(2); + } + Some(result) + } + } + }; + } + + math_traits_impl!(i8, u8); + math_traits_impl!(u8, u8); + math_traits_impl!(i16, u16); + math_traits_impl!(u16, u16); + math_traits_impl!(i32, u32); + math_traits_impl!(u32, u32); + math_traits_impl!(i64, u64); + math_traits_impl!(u64, u64); + math_traits_impl!(i128, u128); + math_traits_impl!(u128, u128); + math_traits_impl!(isize, usize); + math_traits_impl!(usize, usize); +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/f.rs b/1850/src/bin/f.rs new file mode 100644 index 0000000..d761b95 --- /dev/null +++ b/1850/src/bin/f.rs @@ -0,0 +1,267 @@ +#![allow(unused_imports)] + +// region ‹use› +use self::input::*; +use self::math::*; +use self::output::*; +use std::cmp::{max, min}; +use std::collections::HashMap; +// endregion ‹use› + +fn can_catch(frogs: Vec) -> usize { + let mut freqs: HashMap = HashMap::new(); + for frog in &frogs { + freqs + .entry(*frog) + .and_modify(|counter| *counter += 1) + .or_insert(1); + } + + let max_position = frogs.len(); + let mut caught = vec![0; max_position]; + + for (frog, counter) in freqs.iter() { + for i in (*frog as usize..=max_position).step_by(*frog as usize) { + caught[i - 1] += counter; + } + } + + *caught.iter().max().expect("N >= 1") +} + +fn solve(s: &mut Scanner) { + let n = s.next::(); + let frogs = s.next_vec::(n); + + println!("{}", can_catch(frogs)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!(can_catch(vec![1, 2, 3, 4, 5]), 3); + } + #[test] + fn example_2() { + assert_eq!(can_catch(vec![2, 2, 2]), 3); + } + #[test] + fn example_3() { + assert_eq!(can_catch(vec![3, 1, 3, 4, 9, 10]), 3); + } + #[test] + fn example_4() { + assert_eq!(can_catch(vec![1, 3, 2, 4, 2, 3, 7, 8, 5]), 5); + } + #[test] + fn example_5() { + assert_eq!(can_catch(vec![10]), 0); + } + #[test] + fn example_6() { + assert_eq!(can_catch(vec![7, 11, 6, 8, 12, 4, 4, 8]), 4); + } + #[test] + fn example_7() { + assert_eq!(can_catch(vec![9, 11, 9, 12, 1, 7, 2, 5, 8, 10]), 4); + } + #[test] + fn timeout_2() { + assert_eq!( + can_catch(vec![2, 3, 5].into_iter().cycle().take(130000).collect()), + 130000 + ); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } + + /// A trait implementing the unsigned bit shifts. + pub trait UnsignedShift { + fn unsigned_shl(self, n: u32) -> Self; + fn unsigned_shr(self, n: u32) -> Self; + } + + /// A trait implementing the integer square root. + pub trait ISqrt { + fn isqrt(&self) -> Self + where + Self: Sized, + { + self.isqrt_checked() + .expect("cannot calculate square root of negative number") + } + + fn isqrt_checked(&self) -> Option + where + Self: Sized; + } + + macro_rules! math_traits_impl { + ($T:ty, $U: ty) => { + impl UnsignedShift for $T { + #[inline] + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + #[inline] + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + } + + impl ISqrt for $T { + #[inline] + fn isqrt_checked(&self) -> Option { + use core::cmp::Ordering; + match self.cmp(&<$T>::default()) { + // Hopefully this will be stripped for unsigned numbers (impossible condition) + Ordering::Less => return None, + Ordering::Equal => return Some(<$T>::default()), + _ => {} + } + + // Compute bit, the largest power of 4 <= n + let max_shift: u32 = <$T>::default().leading_zeros() - 1; + let shift: u32 = (max_shift - self.leading_zeros()) & !1; + let mut bit = <$T>::try_from(1).unwrap().unsigned_shl(shift); + + // Algorithm based on the implementation in: + // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2) + // Note that result/bit are logically unsigned (even if T is signed). + let mut n = *self; + let mut result = <$T>::default(); + while bit != <$T>::default() { + if n >= (result + bit) { + n -= result + bit; + result = result.unsigned_shr(1) + bit; + } else { + result = result.unsigned_shr(1); + } + bit = bit.unsigned_shr(2); + } + Some(result) + } + } + }; + } + + math_traits_impl!(i8, u8); + math_traits_impl!(u8, u8); + math_traits_impl!(i16, u16); + math_traits_impl!(u16, u16); + math_traits_impl!(i32, u32); + math_traits_impl!(u32, u32); + math_traits_impl!(i64, u64); + math_traits_impl!(u64, u64); + math_traits_impl!(i128, u128); + math_traits_impl!(u128, u128); + math_traits_impl!(isize, usize); + math_traits_impl!(usize, usize); +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/g.rs b/1850/src/bin/g.rs new file mode 100644 index 0000000..b613900 --- /dev/null +++ b/1850/src/bin/g.rs @@ -0,0 +1,277 @@ +#![allow(unused_imports)] + +// region ‹use› +use self::input::*; +use self::math::*; +use self::output::*; +use std::cmp::{max, min}; +use std::collections::HashMap; +// endregion ‹use› + +fn dont_break(points: Vec<(i64, i64)>) -> usize { + let mut x_axis: HashMap = HashMap::new(); + let mut y_axis: HashMap = HashMap::new(); + let mut diag_1: HashMap = HashMap::new(); + let mut diag_2: HashMap = HashMap::new(); + + // process the points + for (x, y) in points { + for counter in [ + x_axis.entry(x), + y_axis.entry(y), + diag_1.entry(x - y), + diag_2.entry(x + y), + ] { + counter.and_modify(|n| *n += 1).or_insert(1); + } + } + + // find the final sum + [ + x_axis.values(), + y_axis.values(), + diag_1.values(), + diag_2.values(), + ] + .map(|counters| counters.map(|n| n * (n - 1)).sum()) + .iter() + .sum() +} + +fn solve(s: &mut Scanner) { + let n = s.next::(); + let points: Vec<(i64, i64)> = (0..n) + .map(|_| { + let x = s.next::(); + let y = s.next::(); + (x, y) + }) + .collect(); + + println!("{}", dont_break(points)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!(dont_break(vec![(0, 0), (-1, -1), (1, 1)]), 6); + } + #[test] + fn example_2() { + assert_eq!(dont_break(vec![(4, 5), (5, 7), (6, 9), (10, 13)]), 2); + } + #[test] + fn example_3() { + assert_eq!( + dont_break(vec![ + (-1000000000, 1000000000), + (0, 0), + (1000000000, -1000000000) + ]), + 6 + ); + } + #[test] + fn example_4() { + assert_eq!( + dont_break(vec![(0, 0), (2, 2), (-1, 5), (-1, 10), (2, 11),]), + 8 + ); + } + #[test] + fn example_5() { + assert_eq!(dont_break(vec![(0, 0), (-1, 2), (1, -2)]), 0); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } + + /// A trait implementing the unsigned bit shifts. + pub trait UnsignedShift { + fn unsigned_shl(self, n: u32) -> Self; + fn unsigned_shr(self, n: u32) -> Self; + } + + /// A trait implementing the integer square root. + pub trait ISqrt { + fn isqrt(&self) -> Self + where + Self: Sized, + { + self.isqrt_checked() + .expect("cannot calculate square root of negative number") + } + + fn isqrt_checked(&self) -> Option + where + Self: Sized; + } + + macro_rules! math_traits_impl { + ($T:ty, $U: ty) => { + impl UnsignedShift for $T { + #[inline] + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + #[inline] + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + } + + impl ISqrt for $T { + #[inline] + fn isqrt_checked(&self) -> Option { + use core::cmp::Ordering; + match self.cmp(&<$T>::default()) { + // Hopefully this will be stripped for unsigned numbers (impossible condition) + Ordering::Less => return None, + Ordering::Equal => return Some(<$T>::default()), + _ => {} + } + + // Compute bit, the largest power of 4 <= n + let max_shift: u32 = <$T>::default().leading_zeros() - 1; + let shift: u32 = (max_shift - self.leading_zeros()) & !1; + let mut bit = <$T>::try_from(1).unwrap().unsigned_shl(shift); + + // Algorithm based on the implementation in: + // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2) + // Note that result/bit are logically unsigned (even if T is signed). + let mut n = *self; + let mut result = <$T>::default(); + while bit != <$T>::default() { + if n >= (result + bit) { + n -= result + bit; + result = result.unsigned_shr(1) + bit; + } else { + result = result.unsigned_shr(1); + } + bit = bit.unsigned_shr(2); + } + Some(result) + } + } + }; + } + + math_traits_impl!(i8, u8); + math_traits_impl!(u8, u8); + math_traits_impl!(i16, u16); + math_traits_impl!(u16, u16); + math_traits_impl!(i32, u32); + math_traits_impl!(u32, u32); + math_traits_impl!(i64, u64); + math_traits_impl!(u64, u64); + math_traits_impl!(i128, u128); + math_traits_impl!(u128, u128); + math_traits_impl!(isize, usize); + math_traits_impl!(usize, usize); +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +} diff --git a/1850/src/bin/h.rs b/1850/src/bin/h.rs new file mode 100644 index 0000000..e861730 --- /dev/null +++ b/1850/src/bin/h.rs @@ -0,0 +1,332 @@ +#![allow(unused_imports)] + +// region ‹use› +use self::input::*; +use self::math::*; +use self::output::*; +use std::cmp::{max, min}; +use std::collections::HashMap; +// endregion ‹use› + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Color { + White, + Gray, + Black, +} + +fn dfs( + g: &[Vec<(usize, i64)>], + positions: &mut Vec, + state: &mut Vec, + u: usize, + parent: usize, +) -> bool { + state[u] = Color::Gray; + + for (v, d) in &g[u] { + if *v == parent { + continue; + } + + if state[*v] != Color::White { + if positions[*v] != positions[u] + d { + // we have already assigned the soldier and it doesn't match + return false; + } else { + continue; + } + } + + positions[*v] = positions[u] + d; + if !dfs(g, positions, state, *v, u) { + return false; + } + } + + state[u] = Color::Black; + true +} + +fn can_arrange(n: usize, conditions: Vec<(usize, usize, i64)>) -> bool { + let mut graph = vec![vec![]; n]; + + // construct graph + for (u, v, d) in conditions { + graph[u - 1].push((v - 1, d)); + graph[v - 1].push((u - 1, -d)); + } + + // run DFS + let mut positions = vec![0; n]; + let mut state: Vec = vec![Color::White; n]; + for start in 0..n { + if state[start] != Color::White { + continue; + } + + if !dfs(&graph, &mut positions, &mut state, start, n) { + return false; + } + } + + true +} + +fn solve(s: &mut Scanner) { + let soldiers = s.next::(); + let n = s.next::(); + let conditions: Vec<(usize, usize, i64)> = (0..n) + .map(|_| { + let a = s.next(); + let b = s.next(); + let d = s.next(); + + (a, b, d) + }) + .collect(); + + yesno(can_arrange(soldiers, conditions)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert!(can_arrange(5, vec![(1, 2, 2), (2, 3, 4), (4, 2, -6)])); + } + #[test] + fn example_2() { + assert!(!can_arrange( + 6, + vec![(1, 2, 2), (2, 3, 4), (4, 2, -6), (5, 4, 4), (3, 5, 100)] + )); + } + #[test] + fn example_3() { + assert!(!can_arrange(2, vec![(1, 2, 5), (1, 2, 4)])); + } + #[test] + fn example_4() { + assert!(can_arrange(4, vec![(1, 2, 3)])); + } + #[test] + fn regression_1() { + assert!(can_arrange( + 4, + vec![(3, 1, 3), (4, 2, 0), (1, 3, -3), (2, 3, -4)] + )) + } + #[test] + fn regression_2() { + assert!(can_arrange(3, vec![(1, 2, 8), (2, 3, -1), (3, 1, -7)])) + } + #[test] + fn regression_3() { + assert!(!can_arrange( + 9, + vec![ + (1, 2, 536870912), + (2, 3, 536870912), + (3, 4, 536870912), + (4, 5, 536870912), + (5, 6, 536870912), + (6, 7, 536870912), + (7, 8, 536870912), + (8, 9, 536870912), + (1, 9, 0) + ] + )); + } +} + +// region runner +const SINGLE_TEST: bool = false; +fn main() { + let mut s = Scanner::new(); + + if SINGLE_TEST { + solve(&mut s) + } else { + let n = s.next::(); + for _ in 0..n { + solve(&mut s) + } + } +} +// endregion runner + +#[allow(dead_code)] +mod math { + const MOD: i64 = 1_000_000_007; + + pub fn add(a: i64, b: i64) -> i64 { + (a + b) % MOD + } + + pub fn sub(a: i64, b: i64) -> i64 { + ((a - b) % MOD + MOD) % MOD + } + + pub fn mul(a: i64, b: i64) -> i64 { + (a * b) % MOD + } + + pub fn exp(b: i64, e: i64) -> i64 { + if e == 0 { + return 1; + } + + let half = exp(b, e / 2); + if e % 2 == 0 { + return mul(half, half); + } + + mul(half, mul(half, b)) + } + + /// A trait implementing the unsigned bit shifts. + pub trait UnsignedShift { + fn unsigned_shl(self, n: u32) -> Self; + fn unsigned_shr(self, n: u32) -> Self; + } + + /// A trait implementing the integer square root. + pub trait ISqrt { + fn isqrt(&self) -> Self + where + Self: Sized, + { + self.isqrt_checked() + .expect("cannot calculate square root of negative number") + } + + fn isqrt_checked(&self) -> Option + where + Self: Sized; + } + + macro_rules! math_traits_impl { + ($T:ty, $U: ty) => { + impl UnsignedShift for $T { + #[inline] + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + #[inline] + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + } + + impl ISqrt for $T { + #[inline] + fn isqrt_checked(&self) -> Option { + use core::cmp::Ordering; + match self.cmp(&<$T>::default()) { + // Hopefully this will be stripped for unsigned numbers (impossible condition) + Ordering::Less => return None, + Ordering::Equal => return Some(<$T>::default()), + _ => {} + } + + // Compute bit, the largest power of 4 <= n + let max_shift: u32 = <$T>::default().leading_zeros() - 1; + let shift: u32 = (max_shift - self.leading_zeros()) & !1; + let mut bit = <$T>::try_from(1).unwrap().unsigned_shl(shift); + + // Algorithm based on the implementation in: + // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2) + // Note that result/bit are logically unsigned (even if T is signed). + let mut n = *self; + let mut result = <$T>::default(); + while bit != <$T>::default() { + if n >= (result + bit) { + n -= result + bit; + result = result.unsigned_shr(1) + bit; + } else { + result = result.unsigned_shr(1); + } + bit = bit.unsigned_shr(2); + } + Some(result) + } + } + }; + } + + math_traits_impl!(i8, u8); + math_traits_impl!(u8, u8); + math_traits_impl!(i16, u16); + math_traits_impl!(u16, u16); + math_traits_impl!(i32, u32); + math_traits_impl!(u32, u32); + math_traits_impl!(i64, u64); + math_traits_impl!(u64, u64); + math_traits_impl!(i128, u128); + math_traits_impl!(u128, u128); + math_traits_impl!(isize, usize); + math_traits_impl!(usize, usize); +} + +#[allow(dead_code)] +mod output { + pub fn yes() { + println!("YES"); + } + + pub fn no() { + println!("NO"); + } + + pub fn yesno(ans: bool) { + println!("{}", if ans { "YES" } else { "NO" }); + } +} + +#[allow(dead_code)] +mod input { + use std::collections::VecDeque; + use std::io; + use std::str::FromStr; + + pub struct Scanner { + buffer: VecDeque, + } + + impl Scanner { + pub fn new() -> Scanner { + Scanner { + buffer: VecDeque::new(), + } + } + + pub fn next(&mut self) -> T { + if self.buffer.is_empty() { + let mut input = String::new(); + + io::stdin().read_line(&mut input).ok(); + + for word in input.split_whitespace() { + self.buffer.push_back(word.to_string()) + } + } + + let front = self.buffer.pop_front().unwrap(); + front.parse::().ok().unwrap() + } + + pub fn next_vec(&mut self, n: usize) -> Vec { + let mut arr = vec![]; + + for _ in 0..n { + arr.push(self.next::()); + } + + arr + } + } +}