Distance II

  Your task is to calculate the distance between two $n$ dimensional vectors $x = \{x_1, x_2, ..., x_n\}$ and $y = \{y_1, y_2, ..., y_n\}$.

  The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance.

\[
D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)^{\frac{1}{p}}
\]

It can be the Manhattan distance

\[
D_{xy} = |x_1 - y_1| + |x_2 - y_2| + ... + |x_n - y_n|
\]

where $p = 1 $.

It can be the Euclidean distance

\[
D_{xy} = \sqrt{(|x_1 - y_1|)^{2} + (|x_2 - y_2|)^{2} + ... + (|x_n - y_n|)^{2}}
\]

where $p = 2 $.

Also, it can be the Chebyshev distance

\[
D_{xy} = max_{i=1}^n (|x_i - y_i|)
\]

where $p = \infty$

Write a program which reads two $n$ dimensional vectors $x$ and $y$, and calculates Minkowski's distance where $p = 1, 2, 3, \infty$ respectively.

Input

  In the first line, an integer $n$ is given. In the second and third line, $x = \{x_1, x_2, ... x_n\}$ and $y = \{y_1, y_2, ... y_n\}$ are given respectively. The elements in $x$ and $y$ are given in integers.

Output

  Print the distance where $p = 1, 2, 3$ and $\infty$ in a line respectively.
The output should not contain an absolute error greater than 10-5.

Constraints

$1 \leq n \leq 100$

$0 \leq x_i, y_i \leq 1000$

Sample Input

3
1 2 3
2 0 4

Sample Output

4.000000
2.449490
2.154435
2.000000

int solution() {
  int n;
  int x[100];
  int y[100];
  double ans[3] = {0.0};
  int ans_max = -1;

  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &x[i]);
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &y[i]);
  }

  for (int i = 0; i < n; i++) {
    double temp = (double)abs(x[i] - y[i]);
    ans[0] += temp;
    ans[1] += temp * temp;
    ans[2] += temp * temp * temp;
    if (ans_max < (int)temp) {
      ans_max = (int)temp;
    }
  }
  ans[1] = sqrt(ans[1]);
  ans[2] = cbrt(ans[2]);
  printf("%f\n%f\n%f\n%d\n", ans[0], ans[1], ans[2], ans_max);
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let n = s.trim().parse().unwrap();

    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let x: Vec<f64> = s
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect::<_>();

    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let y: Vec<f64> = s
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect::<_>();

    let mut a: f64 = 0.;
    for i in 0..n {
        a += (x[i] - y[i]).abs();
    }

    let mut b: f64 = 0.;
    for i in 0..n {
        b += (x[i] - y[i]).powi(2);
    }

    let mut c: f64 = 0.;
    for i in 0..n {
        c += (x[i] - y[i]).abs().powi(3);
    }

    let mut d: f64 = 0.;
    for i in 0..n {
        if d < (x[i] - y[i]).abs() {
            d = (x[i] - y[i]).abs();
        }
    }

    println!("{}\n{}\n{}\n{}", a, b.sqrt(), c.powf(1_f64 / 3_f64), d);
}


Score : <var>200</var> points

Problem Statement

We have <var>N</var> squares assigned the numbers <var>1,2,3,\ldots,N</var>. Each square has an integer written on it, and the integer written on Square <var>i</var> is <var>a_i</var>.

How many squares <var>i</var> satisfy both of the following conditions?

The assigned number, <var>i</var>, is odd.

The written integer is odd.

Constraints

All values in input are integers.

<var>1 \leq N, a_i \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> <var>\cdots</var> <var>a_N</var>

Output

Print the number of squares that satisfy both of the conditions.

Sample Input 1

5
1 3 4 5 7

Sample Output 1

2

Two squares, Square <var>1</var> and <var>5</var>, satisfy both of the conditions.

For Square <var>2</var> and <var>4</var>, the assigned numbers are not odd.

For Square <var>3</var>, the written integer is not odd.

Sample Input 2

15
13 76 46 15 50 98 93 77 31 43 84 90 6 24 14

Sample Output 2

3

fn solution() {
    let mut buf = String::new();
    std::io::stdin()
        .read_line(&mut buf)
        .expect("failed to read");
    buf.clear();
    std::io::stdin()
        .read_line(&mut buf)
        .expect("failed to read");
    let va: Vec<u32> = buf.split_whitespace().map(|e| e.parse().unwrap()).collect();

    let ct: usize = va
        .iter()
        .enumerate()
        .filter(|&(i, &x)| i % 2 == 0 && x % 2 == 1)
        .count();

    println!("{}", ct);
}


Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1    for i = 0 to k
2        do C[i] = 0
3    for j = 1 to length[A]
4        do C[A[j]] = C[A[j]]+1
5    /* C[i] now contains the number of elements equal to i */
6    for i = 1 to k
7    do C[i] = C[i] + C[i-1]
8    /* C[i] now contains the number of elements less than or equal to i */
9    for j = length[A] downto 1
10       do B[C[A[j]]] = A[j]
11          C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5

fn solution() {
    input!(n: usize, vs: [usize; n]);

    let nax = vs.iter().max().unwrap();
    let nax = *nax;
    let mut cs = vec![0usize; nax + 1];

    for i in 0..n {
        cs[vs[i]] += 1;
    }

    for i in 1..nax + 1 {
        cs[i] += cs[i - 1];
    }

    let mut bs = vec![0usize; n];
    for i in (0..n).rev() {
        bs[cs[vs[i]] - 1] = vs[i];

        cs[vs[i]] -= 1;
    }

    for i in 0..n {
        if i != n - 1 {
            print!("{} ", bs[i])
        } else {
            println!("{}", bs[i]);
        }
    }
}


Vasya has a sequence of cubes and exactly one integer is written on each cube. Vasya exhibited all his cubes in a row. So the sequence of numbers written on the cubes in the order from the left to the right equals to a1, a2, ..., an.While Vasya was walking, his little brother Stepan played with Vasya's cubes and changed their order, so now the sequence of numbers written on the cubes became equal to b1, b2, ..., bn. Stepan said that he swapped only cubes which where on the positions between l and r, inclusive, and did not remove or add any other cubes (i. e. he said that he reordered cubes between positions l and r, inclusive, in some way).Your task is to determine if it is possible that Stepan said the truth, or it is guaranteed that Stepan deceived his brother.

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let mut numbers = line.split_whitespace();

    let n: usize = numbers.next().unwrap().parse().unwrap();
    let l: usize = numbers.next().unwrap().parse().unwrap();
    let r: usize = numbers.next().unwrap().parse().unwrap();

    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let a1: Vec<usize> = line
        .split_whitespace()
        .map(|i| i.parse().unwrap())
        .collect();

    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let a2: Vec<usize> = line
        .split_whitespace()
        .map(|i| i.parse().unwrap())
        .collect();

    for i in 0..n {
        if a1[i] != a2[i] && (i + 1 < l || i + 1 > r) {
            return println!("LIE");
        }
    }
    println!("TRUTH");
}


Score : <var>200</var> points

Problem Statement

Let us define the FizzBuzz sequence <var>a_1,a_2,...</var> as follows:

If both <var>3</var> and <var>5</var> divides <var>i</var>, <var>a_i=\mbox{FizzBuzz}</var>.

If the above does not hold but <var>3</var> divides <var>i</var>, <var>a_i=\mbox{Fizz}</var>.

If none of the above holds but <var>5</var> divides <var>i</var>, <var>a_i=\mbox{Buzz}</var>.

If none of the above holds, <var>a_i=i</var>.

Find the sum of all numbers among the first <var>N</var> terms of the FizzBuzz sequence.

Constraints

<var>1 \leq N \leq 10^6</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the sum of all numbers among the first <var>N</var> terms of the FizzBuzz sequence.

Sample Input 1

15

Sample Output 1

60

The first <var>15</var> terms of the FizzBuzz sequence are:

<var>1,2,\mbox{Fizz},4,\mbox{Buzz},\mbox{Fizz},7,8,\mbox{Fizz},\mbox{Buzz},11,\mbox{Fizz},13,14,\mbox{FizzBuzz}</var>

Among them, numbers are <var>1,2,4,7,8,11,13,14</var>, and the sum of them is <var>60</var>.

Sample Input 2

1000000

Sample Output 2

266666333332

Watch out for overflow.

int solution() {
  int n = 0;
  unsigned long long total = 0;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    if (i % 3 != 0 && i % 5 != 0) {
      total += i;
    }
  }
  printf("%llu", total);

  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let n: i64 = s.trim().parse().unwrap();
    let itr = (1..=n).filter(|&e| !(e % 5 == 0 || e % 3 == 0));

    println!("{}", itr.sum::<i64>());
}


For his birthday, Kevin received the set of pairwise distinct numbers $$$1, 2, 3, \ldots, n$$$ as a gift.He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $$$p_1, p_2, \ldots, p_n$$$, he wants to maximize the value $$$$$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert,$$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Help Kevin to do that.

int solution() {
  int n;

  scanf("%d", &n);
  int A[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &A[i]);
  }
  for (int k = 0; k < n; k++) {
    int z = A[k];
    int a = z / 2;
    int b = 2 * a;
    for (int q = 1; q <= z / 2; q++) {

      printf("%d %d ", a, b);
      a--;
      b--;
    }

    if (z % 2 == 1) {
      printf("%d", z);
    }
    printf("\n");
  }
  return 0;
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(1)
        .flatten()
        .flat_map(|s| s.parse::<u16>())
        .for_each(|n| {
            for i in 0..(n.wrapping_div(2)) {
                write!(
                    buf,
                    "{} {} ",
                    n.wrapping_add(1).wrapping_div(2).wrapping_sub(i),
                    n.wrapping_sub(i)
                )
                .ok();
            }
            if (n & 1) == 1 {
                writeln!(buf, "1",).ok();
            } else {
                writeln!(buf).ok();
            }
        });
}


Score : <var>500</var> points

Problem Statement

There are <var>N</var> points on the 2D plane, <var>i</var>-th of which is located on <var>(x_i, y_i)</var>.
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points <var>(x_i, y_i)</var> and <var>(x_j, y_j)</var> is defined by <var>|x_i-x_j| + |y_i-y_j|</var>.

Constraints

<var>2 \leq N \leq 2 \times 10^5</var>

<var>1 \leq x_i,y_i \leq 10^9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>x_1</var> <var>y_1</var>
<var>x_2</var> <var>y_2</var>
<var>:</var>
<var>x_N</var> <var>y_N</var>

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is <var>|1-2|+|1-4|=4</var>, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0

int solution(void) {
  int n;
  scanf("%d", &n);
  long int x;
  long int y;
  long int minz = 2000000000;
  long int maxz = 2;
  long int minw = 1000000000;
  long int maxw = -1000000000;
  for (int i = 0; i < n; i++) {
    scanf("%ld %ld", &x, &y);
    if (x + y < minz) {
      minz = x + y;
    }
    if (x + y > maxz) {
      maxz = x + y;
    }
    if (x - y < minw) {
      minw = x - y;
    }
    if (x - y > maxw) {
      maxw = x - y;
    }
  }

  if (maxz - minz > maxw - minw) {
    printf("%ld\n", maxz - minz);
  } else {
    printf("%ld\n", maxw - minw);
  }
  return 0;
}

fn solution() {
    let n: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

    let (mut x, mut y) = (vec![0i64; n], vec![0i64; n]);
    for i in 0..n {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        x[i] = iter.next().unwrap().parse().unwrap();
        y[i] = iter.next().unwrap().parse().unwrap();
    }

    let ans = {
        *[
            (0..n).map(|i| x[i] + y[i]).max().unwrap() - (0..n).map(|i| x[i] + y[i]).min().unwrap(),
            (0..n).map(|i| x[i] - y[i]).max().unwrap() - (0..n).map(|i| x[i] - y[i]).min().unwrap(),
            (0..n).map(|i| -x[i] + y[i]).max().unwrap()
                - (0..n).map(|i| -x[i] + y[i]).min().unwrap(),
            (0..n).map(|i| -x[i] - y[i]).max().unwrap()
                - (0..n).map(|i| -x[i] - y[i]).min().unwrap(),
        ]
        .iter()
        .max()
        .unwrap()
    };
    println!("{}", ans);
}


Score : <var>300</var> points

Problem Statement

We have a grid of <var>H</var> rows and <var>W</var> columns of squares. The color of the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left <var>(1 \leq i \leq H, 1 \leq j \leq W)</var> is given to you as a character <var>c_{i,j}</var>: the square is white if <var>c_{i,j}</var> is ., and black if <var>c_{i,j}</var> is #.

Consider doing the following operation:

Choose some number of rows (possibly zero), and some number of columns (possibly zero). Then, paint red all squares in the chosen rows and all squares in the chosen columns.

You are given a positive integer <var>K</var>. How many choices of rows and columns result in exactly <var>K</var> black squares remaining after the operation? Here, we consider two choices different when there is a row or column chosen in only one of those choices.

Constraints

<var>1 \leq H, W \leq 6</var>

<var>1 \leq K \leq HW</var>

<var>c_{i,j}</var> is . or #.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>K</var>
<var>c_{1,1}c_{1,2}...c_{1,W}</var>
<var>c_{2,1}c_{2,2}...c_{2,W}</var>
<var>:</var>
<var>c_{H,1}c_{H,2}...c_{H,W}</var>

Output

Print an integer representing the number of choices of rows and columns satisfying the condition.

Sample Input 1

2 3 2
..#
###

Sample Output 1

5

Five choices below satisfy the condition.

The <var>1</var>-st row and <var>1</var>-st column

The <var>1</var>-st row and <var>2</var>-nd column

The <var>1</var>-st row and <var>3</var>-rd column

The <var>1</var>-st and <var>2</var>-nd column

The <var>3</var>-rd column

Sample Input 2

2 3 4
..#
###

Sample Output 2

1

One choice, which is choosing nothing, satisfies the condition.

Sample Input 3

2 2 3
##
##

Sample Output 3

0

Sample Input 4

6 6 8
..##..
.#..#.
#....#
######
#....#
#....#

Sample Output 4

208

int solution() {
  int H;
  int W;
  int K;
  scanf("%d %d %d", &H, &W, &K);
  char m[H * W];
  for (int i = 0; i < H * W; i++) {
    scanf(" %c", &m[i]);
  }
  int count = 0;
  for (int h = 0; h < 1 << H; h++) {
    for (int w = 0; w < 1 << W; w++) {
      int black = 0;
      for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
          if (h >> i & 1 && w >> j & 1 && m[(i * W) + j] == '#') {
            black++;
          }
        }
      }
      if (black == K) {
        count++;
      }
    }
  }
  printf("%d\n", count);
  return 0;
}

fn solution() {
    let mut x = String::new();
    io::stdin().read_line(&mut x).unwrap();
    let hwk: Vec<usize> = x
        .trim_end()
        .split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
    let h = hwk[0];
    let w = hwk[1];
    let k = hwk[2];
    let mut b: [[bool; 6]; 6] = Default::default();
    let lines = BufReader::new(io::stdin()).split(b'\n');
    for (row, line) in b.iter_mut().zip(lines) {
        for (cell, x) in row.iter_mut().zip(line.unwrap()) {
            if x == b'#' {
                *cell = true;
            }
        }
    }
    let mut ans = 0;
    for i in 0..1 << h {
        for j in 0..1 << w {
            let mut cnt = 0;
            for r in 0..h {
                if (i >> r) & 1 == 0 {
                    for c in 0..w {
                        if (j >> c) & 1 == 0 && b[r][c] {
                            cnt += 1;
                        }
                    }
                }
            }
            if cnt == k {
                ans += 1;
            }
        }
    }
    println!("{}", ans);
}


Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him.

fn solution() {
    let _ = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    };
    let v: Vec<i64> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i64>().unwrap())
            .collect()
    };
    let mut count = HashMap::new();
    v.iter().for_each(|i| *count.entry(i).or_insert(0) += 1);

    let n = v.iter().max().unwrap();
    let mut dp = HashMap::new();
    for i in 1..n + 1 {
        *dp.entry(i).or_insert(0) = std::cmp::max(
            (count.get(&i).unwrap_or(&0)) * i + dp.get(&(i - 2)).cloned().unwrap_or(0),
            dp.get(&(i - 1)).cloned().unwrap_or(0),
        )
    }
    println!("{:?}", dp.values().max().unwrap());
}


Score : <var>200</var> points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between <var>1</var> and <var>9</var> (inclusive) together.

Given an integer <var>N</var>, determine whether <var>N</var> can be represented as the product of two integers between <var>1</var> and <var>9</var>. If it can, print Yes; if it cannot, print No.

Constraints

<var>1 \leq N \leq 100</var>

<var>N</var> is an integer.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If <var>N</var> can be represented as the product of two integers between <var>1</var> and <var>9</var> (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

<var>10</var> can be represented as, for example, <var>2 \times 5</var>.

Sample Input 2

50

Sample Output 2

No

<var>50</var> cannot be represented as the product of two integers between <var>1</var> and <var>9</var>.

Sample Input 3

81

Sample Output 3

Yes

int solution(void) {
  int n = 0;
  int flag = 0;
  scanf("%d", &n);
  for (int i = 1; i <= 9; i++) {
    if (n == (n / i) * i && (n / i) <= 9) {
      flag = 1;
      break;
    }
  }
  if (flag == 1) {
    printf("Yes");
  } else {
    printf("No");
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let line: Vec<i32> = buf.split_whitespace().map(|s| s.parse().unwrap()).collect();
    let N = line[0];
    for i in 1..10 {
        for j in 1..10 {
            if i * j == N {
                println!("Yes");
                return;
            }
        }
    }
    println!("No")
}


int64_t solution(const int64_t *arr, const uint16_t length,
                           const int64_t n) {
  if (length == 0) {
    return -1;
  }

  uint32_t upper_bound = 1;
  while (upper_bound < length && arr[upper_bound] < n) {
    upper_bound = upper_bound * 2;
  }

  uint16_t lower_bound = upper_bound / 2;
  if (upper_bound >= length) {
    upper_bound = length - 1;
  }

  while (lower_bound <= upper_bound) {
    uint16_t middle_index = lower_bound + (upper_bound - lower_bound) / 2;

    if (arr[middle_index] == n) {
      return middle_index;
    }

    if (arr[middle_index] > n) {

      if (middle_index == 0) {
        break;
      }
      upper_bound = middle_index - 1;
    } else {

      lower_bound = middle_index + 1;
    }
  }

  return -1;
}

fn solution<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
    let len = arr.len();
    if len == 0 {
        return None;
    }
    let mut upper = 1;
    while (upper < len) && (&arr[upper] <= item) {
        upper *= 2;
    }
    if upper > len {
        upper = len
    }

    let mut lower = upper / 2;
    while lower < upper {
        let mid = lower + (upper - lower) / 2;

        match item.cmp(&arr[mid]) {
            Ordering::Less => upper = mid,
            Ordering::Equal => return Some(mid),
            Ordering::Greater => lower = mid + 1,
        }
    }
    None
}


A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. Each time a new user wants to register, he sends to the system a request with his name. If such a name does not exist in the system database, it is inserted into the database, and the user gets the response OK, confirming the successful registration. If the name already exists in the system database, the system makes up a new user name, sends it to the user as a prompt and also inserts the prompt into the database. The new name is formed by the following rule. Numbers, starting with 1, are appended one after another to name (name1, name2, ...), among these numbers the least i is found so that namei does not yet exist in the database.

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let n: i32 = s.trim().parse().unwrap();
    let mut map = HashMap::new();
    for _i in 0..n {
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        s = s.trim().to_string();
        let s2 = String::from(&s);
        let count = map.entry(s2).or_insert(0);
        if *count == 0 {
            println!("OK");
        } else {
            println!("{}{}", s, *count);
        }
        *count += 1;
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> integers <var>a_1, a_2, ..., a_N</var> not less than <var>1</var>.
The values of <var>a_1, a_2, ..., a_N</var> are not known, but it is known that <var>a_1 \times a_2 \times ... \times a_N = P</var>.

Find the maximum possible greatest common divisor of <var>a_1, a_2, ..., a_N</var>.

Constraints

<var>1 \leq N \leq 10^{12}</var>

<var>1 \leq P \leq 10^{12}</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>P</var>

Output

Print the answer.

Sample Input 1

3 24

Sample Output 1

2

The greatest common divisor would be <var>2</var> when, for example, <var>a_1=2, a_2=6</var> and <var>a_3=2</var>.

Sample Input 2

5 1

Sample Output 2

1

As <var>a_i</var> are positive integers, the only possible case is <var>a_1 = a_2 = a_3 = a_4 = a_5 = 1</var>.

Sample Input 3

1 111

Sample Output 3

111

Sample Input 4

4 972439611840

Sample Output 4

206

int solution(void) {
  long N;
  long P;
  long ans = 1;
  scanf("%ld %ld", &N, &P);

  if (N == 1) {
    printf("%ld", P);
    return 0;
  }

  int div = 0;

  for (int i = 2; P > 1 && i <= sqrt(P); i++) {
    div = 0;
    while (P % i == 0) {
      P /= i;
      div++;
      if (div >= N) {
        ans *= i;
        div -= N;
      }
    }
  }

  printf("%ld", ans);

  return 0;
}

fn solution() {
    let mut stdin = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();
    let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();

    let n = get!();
    let mut p = get!();
    if n == 1 {
        println!("{}", p);
        return;
    }

    let mut ans = 1_i64;
    let mut i = 2;
    while i * i <= p {
        if p % i == 0 {
            let mut c = 0;
            while p % i == 0 {
                p /= i;
                c += 1;
            }
            let x = c / n;
            for _ in 0..x {
                ans *= i;
            }
        }
        i += 1;
    }
    println!("{}", ans);
}


Consider the array $$$a$$$ composed of all the integers in the range $$$[l, r]$$$. For example, if $$$l = 3$$$ and $$$r = 7$$$, then $$$a = [3, 4, 5, 6, 7]$$$.Given $$$l$$$, $$$r$$$, and $$$k$$$, is it possible for $$$\gcd(a)$$$ to be greater than $$$1$$$ after doing the following operation at most $$$k$$$ times?   Choose $$$2$$$ numbers from $$$a$$$.  Permanently remove one occurrence of each of them from the array.  Insert their product back into $$$a$$$. $$$\gcd(b)$$$ denotes the greatest common divisor (GCD) of the integers in $$$b$$$.

int solution(void) {
  int n;
  scanf("%d", &n);
  while (n--) {
    int l;
    int r;
    int k;
    scanf("%d %d %d", &l, &r, &k);
    int j = 0;
    if (l == r && l > 1) {
      j = 1;
    } else {
      int number = r - l + 1;
      int js = number / 2;
      if (l % 2 && r % 2) {
        js++;
      }
      if (js < number && js <= k) {
        j = 1;
      }
    }
    if (j == 1) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }
  }
}

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).unwrap();
    let mut input = input.split_ascii_whitespace().flat_map(str::parse);
    let t = input.next().unwrap();
    let mut output = String::new();
    for _ in 0..t {
        let l = input.next().unwrap();
        let r = input.next().unwrap();
        let k = input.next().unwrap();
        let len = r - l;
        let can = if len == 0 {
            l != 1
        } else if len % 2 == 0 {
            k >= len / 2 + l % 2
        } else {
            k > len / 2
        };
        if can {
            writeln!(output, "YES").unwrap();
        } else {
            writeln!(output, "NO").unwrap();
        }
    }
    print!("{}", output);
}


You are given three integers $$$a$$$, $$$b$$$, and $$$c$$$. Determine if one of them is the sum of the other two.

fn solution() {
    let mut line = String::new();

    std::io::stdin().read_line(&mut line).unwrap();

    let line_len = line.trim().parse::<i32>().unwrap();

    for _ in 0..line_len {
        line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();

        let num_strs: Vec<&str> = line.trim().split(" ").collect();

        let a = num_strs.first().unwrap().parse::<i32>().unwrap();
        let b = num_strs.get(1).unwrap().parse::<i32>().unwrap();
        let c = num_strs.get(2).unwrap().parse::<i32>().unwrap();

        if a == b + c || b == a + c || c == a + b {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>700</var> points

Problem Statement

We have a sequence of <var>N \times K</var> integers: <var>X=(X_0,X_1,\cdots,X_{N \times K-1})</var>.
Its elements are represented by another sequence of <var>N</var> integers: <var>A=(A_0,A_1,\cdots,A_{N-1})</var>. For each pair <var>i, j</var> (<var>0 \leq i \leq K-1,\ 0 \leq j \leq N-1</var>), <var>X_{i \times N + j}=A_j</var> holds.

Snuke has an integer sequence <var>s</var>, which is initially empty.
For each <var>i=0,1,2,\cdots,N \times K-1</var>, in this order, he will perform the following operation:

If <var>s</var> does not contain <var>X_i</var>: add <var>X_i</var> to the end of <var>s</var>.

If <var>s</var> does contain <var>X_i</var>: repeatedly delete the element at the end of <var>s</var> until <var>s</var> no longer contains <var>X_i</var>. Note that, in this case, we do not add <var>X_i</var> to the end of <var>s</var>.

Find the elements of <var>s</var> after Snuke finished the operations.

Constraints

<var>1 \leq N \leq 2 \times 10^5</var>

<var>1 \leq K \leq 10^{12}</var>

<var>1 \leq A_i \leq 2 \times 10^5</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>A_0</var> <var>A_1</var> <var>\cdots</var> <var>A_{N-1}</var>

Output

Print the elements of <var>s</var> after Snuke finished the operations, in order from beginning to end, with spaces in between.

Sample Input 1

3 2
1 2 3

Sample Output 1

2 3

In this case, <var>X=(1,2,3,1,2,3)</var>.
We will perform the operations as follows:

<var>i=0</var>: <var>s</var> does not contain <var>1</var>, so we add <var>1</var> to the end of <var>s</var>, resulting in <var>s=(1)</var>.

<var>i=1</var>: <var>s</var> does not contain <var>2</var>, so we add <var>2</var> to the end of <var>s</var>, resulting in <var>s=(1,2)</var>.

<var>i=2</var>: <var>s</var> does not contain <var>3</var>, so we add <var>3</var> to the end of <var>s</var>, resulting in <var>s=(1,2,3)</var>.

<var>i=3</var>: <var>s</var> does contain <var>1</var>, so we repeatedly delete the element at the end of <var>s</var> as long as <var>s</var> contains <var>1</var>, which causes the following changes to <var>s</var>: <var>(1,2,3)→(1,2)→(1)→()</var>.

<var>i=4</var>: <var>s</var> does not contain <var>2</var>, so we add <var>2</var> to the end of <var>s</var>, resulting in <var>s=(2)</var>.

<var>i=5</var>: <var>s</var> does not contain <var>3</var>, so we add <var>3</var> to the end of <var>s</var>, resulting in <var>s=(2,3)</var>.

Sample Input 2

5 10
1 2 3 2 3

Sample Output 2

3

Sample Input 3

6 1000000000000
1 1 2 2 3 3

Sample Output 3

<var>s</var> may be empty in the end.

Sample Input 4

11 97
3 1 4 1 5 9 2 6 5 3 5

Sample Output 4

9 2 6

fn solution() {
    let mut input_str = String::new();
    std::io::stdin().read_to_string(&mut input_str).unwrap();

    let input_parts = input_str.split_whitespace().collect::<Vec<_>>();
    let mut input_parts_it = input_parts.iter().cloned();

    let n: usize = input_parts_it.next().unwrap().parse().unwrap();
    let k: u64 = input_parts_it.next().unwrap().parse().unwrap();

    let a: Vec<u32> = (0..n)
        .map(|_| input_parts_it.next().unwrap().parse().unwrap())
        .collect();

    const NONE: usize = 0xffffffff;
    let mut group_end: Vec<usize> = vec![NONE; a.len()];

    let mut next_a_same_value_for_a: Vec<usize> = vec![NONE; a.len()];
    let mut last_a_for_aval: Vec<usize> = vec![NONE; 200001];

    for (i, &aval) in a.iter().enumerate().rev() {
        next_a_same_value_for_a[i] = last_a_for_aval[aval as usize];
        last_a_for_aval[aval as usize] = i;
    }

    for (i, &aval) in a.iter().enumerate() {
        let mut k = next_a_same_value_for_a[i];
        if k == NONE {
            k = last_a_for_aval[aval as usize];
            debug_assert!(k != NONE);
            k += a.len();
        }
        k += 1;

        group_end[i] = k;
    }

    let mut cycle_len = 0;
    {
        let mut i = 0;
        loop {
            let hop = group_end[i] - i;
            cycle_len += hop as u64;
            i = group_end[i];
            while i >= a.len() {
                i -= a.len();
            }
            if i == 0 {
                break;
            }
        }
    }

    let mut step = n as u64 * k;
    step %= cycle_len;

    let mut state: Vec<u32> = Vec::with_capacity(a.len());
    let mut index: Vec<usize> = vec![NONE; 200001];

    {
        let mut i = 0;
        let mut remaining_steps = step;

        while remaining_steps >= (group_end[i] - i) as u64 {
            remaining_steps -= (group_end[i] - i) as u64;
            i = group_end[i];
            while i >= a.len() {
                i -= a.len();
            }
        }

        while remaining_steps > 0 {
            let aval = a[i];

            if index[aval as usize] == NONE {
                index[aval as usize] = state.len();
                state.push(aval);
            } else {
                while state.len() > index[aval as usize] {
                    let k = state.pop().unwrap();
                    index[k as usize] = NONE;
                }
            }

            i += 1;
            while i >= a.len() {
                i -= a.len();
            }
            remaining_steps -= 1;
        }
    }

    if state.is_empty() {
        println!();
    } else {
        print!("{}", state[0]);
        for &x in state[1..].iter() {
            print!(" {}", x);
        }
    }
}


Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number.Help Igor find the maximum number he can write on the fence.

fn solution() {
    let stdin = io::stdin();
    let mut s = String::new();
    let mut t = String::new();

    stdin.read_line(&mut s).unwrap();
    stdin.read_line(&mut t).unwrap();

    let n: i32 = s.trim().parse().unwrap();
    let v: Vec<i32> = t.trim().split(' ').map(|x| x.parse().unwrap()).collect();

    let mut cheapest_idx = 8;
    let mut cost = 100_001;
    for i in (0..v.len()).rev() {
        if v[i] < cost {
            cost = v[i];
            cheapest_idx = i;
        }
    }

    let mut len = n / cost;

    if len == 0 {
        println!("-1");
        return;
    }

    let mut spare = n % cost;
    let mut i = v.len() - 1;
    let mut s = String::new();

    while spare > 0 && i > cheapest_idx {
        if cost + spare >= v[i] {
            s = format!("{}{}", s, i + 1);
            spare -= v[i] - cost;
            len -= 1;
        } else {
            i -= 1;
        }
    }

    if len > 0 {
        let tail: String = vec![(cheapest_idx + 1).to_string(); len as usize]
            .into_iter()
            .collect();
        s = format!("{}{}", s, tail);
    }

    println!("{}", s);
}


One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$, where $$$a_{i} \neq 0$$$, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order.  select two indices $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$) such that $$$a_i$$$ and $$$a_j$$$ have different signs. In other words, one must be positive and one must be negative.  swap the signs of $$$a_{i}$$$ and $$$a_{j}$$$. For example if you select $$$a_i=3$$$ and $$$a_j=-2$$$, then they will change to $$$a_i=-3$$$ and $$$a_j=2$$$. Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.

int solution() {
  unsigned short t;
  scanf("%hu", &t);
  while (t--) {
    unsigned short n;
    scanf("%hu", &n);
    int arr[n];
    unsigned short neg_count = 0;
    for (unsigned register short i = 0; i < n; i++) {
      scanf("%i", &arr[i]);
      neg_count += arr[i] < 0;
    }
    for (unsigned register short i = 0; i < n; i++) {
      arr[i] = abs(arr[i]);
    }
    bool neg_order = true, pos_order = true;
    for (unsigned register short i = 0; i < n - 1; i++) {
      if (i < neg_count - 1 && neg_count > 0) {
        if (arr[i] < arr[i + 1]) {
          neg_order = 0;
          break;
        }
      }
      if (i > neg_count - 1) {
        if (arr[i] > arr[i + 1]) {
          pos_order = 0;
          break;
        }
      }
    }
    (neg_order && pos_order) ? printf("YES\n") : printf("NO\n");
  }
}

fn solution() {
    let stdin = io::stdin();
    let lines = stdin
        .lock()
        .lines()
        .collect::<Vec<Result<String, std::io::Error>>>();
    let mut lines = lines.iter();
    lines.next();
    lines.next();

    for line in lines.step_by(2) {
        let line = line.as_ref().unwrap();
        let numbers = line
            .split_whitespace()
            .map(|s| s.parse::<i32>().unwrap())
            .collect::<Vec<_>>();
        let negative_count = numbers.iter().filter(|x| x < &&0).count();
        let numbers = numbers.iter().map(|x| x.abs()).collect::<Vec<_>>();
        let (negatives, positives) = (
            numbers.iter().take(negative_count),
            numbers.iter().skip(negative_count),
        );
        if negatives
            .fold(Some(i32::MAX), |x, y| {
                if let Some(x) = x {
                    if x >= *y {
                        Some(*y)
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .is_some()
            && positives
                .fold(Some(-1), |x, y| {
                    if let Some(x) = x {
                        if x <= *y {
                            Some(*y)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                })
                .is_some()
        {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>100</var> points

Problem Statement

You have three tasks, all of which need to be completed.

First, you can complete any one task at cost <var>0</var>.

Then, just after completing the <var>i</var>-th task, you can complete the <var>j</var>-th task at cost <var>|A_j - A_i|</var>.

Here, <var>|x|</var> denotes the absolute value of <var>x</var>.

Find the minimum total cost required to complete all the task.

Constraints

All values in input are integers.

<var>1 \leq A_1, A_2, A_3 \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>A_1</var> <var>A_2</var> <var>A_3</var>

Output

Print the minimum total cost required to complete all the task.

Sample Input 1

1 6 3

Sample Output 1

5

When the tasks are completed in the following order, the total cost will be <var>5</var>, which is the minimum:

Complete the first task at cost <var>0</var>.

Complete the third task at cost <var>2</var>.

Complete the second task at cost <var>3</var>.

Sample Input 2

11 5 5

Sample Output 2

6

Sample Input 3

100 100 100

Sample Output 3

0

fn solution() {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).unwrap();
    let mut task: Vec<i32> = n.split_whitespace().map(|x| x.parse().unwrap()).collect();

    task.sort();

    let mut ans = 0;
    for i in 1..task.len() {
        ans += task[i] - task[i - 1];
    }
    println!("{}", ans);
}


Cowboy Vlad has a birthday today! There are $$$n$$$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from $$$1$$$ to $$$n$$$ in a circle order, that is, for every $$$i$$$ child with number $$$i$$$ will stand next to the child with number $$$i+1$$$, also the child with number $$$1$$$ stands next to the child with number $$$n$$$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.

fn solution() {
    let mut sin = String::new();
    std::io::stdin().read_line(&mut sin).expect("read error");
    sin.clear();

    std::io::stdin().read_line(&mut sin).expect("read error");
    let mut vi32: Vec<i32> = sin.split_whitespace().map(|c| c.parse().unwrap()).collect();
    vi32.sort_unstable();

    let mut i: i32 = 0;
    let mut rev = 0;
    loop {
        print!("{} ", vi32[i as usize]);
        if rev == 0 {
            i += 2;
            if i as usize >= vi32.len() {
                rev = 1;
                if vi32.len().is_multiple_of(2) {
                    i = vi32.len() as i32 - 1;
                } else {
                    i = vi32.len() as i32 - 2;
                }
            }
        } else {
            i -= 2;
            if i == -1 {
                break;
            }
        }
    }
    println!();
}


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

fn solution() {
    let mut t = String::new();
    io::stdin().read_line(&mut t).unwrap();
    let t = t.trim().parse::<i32>().unwrap();

    for _i in 0..t {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let mut input = input.split_whitespace();

        let n = input.next().unwrap().parse::<i32>().unwrap();
        let m = input.next().unwrap().parse::<i32>().unwrap();

        if m % 2 != 0 {
            println!("NO");

            for _q in 0..n {
                let mut up = String::new();
                io::stdin().read_line(&mut up).unwrap();
                let _up = up.split_whitespace();

                let mut down = String::new();
                io::stdin().read_line(&mut down).unwrap();
                let _down = down.split_whitespace();
            }
        } else {
            let mut correct = false;

            for _q in 0..n {
                let mut up = String::new();
                io::stdin().read_line(&mut up).unwrap();
                let mut up = up.split_whitespace();

                let _x1 = up.next().unwrap().parse::<i32>().unwrap();
                let x2 = up.next().unwrap().parse::<i32>().unwrap();

                let mut down = String::new();
                io::stdin().read_line(&mut down).unwrap();
                let mut down = down.split_whitespace();

                let x3 = down.next().unwrap().parse::<i32>().unwrap();
                let _x4 = down.next().unwrap().parse::<i32>().unwrap();

                if !correct && x2 == x3 {
                    println!("YES");
                    correct = true;
                }
            }

            if !correct {
                println!("NO");
            }
        }
    }
}


Score : <var>500</var> points

Problem Statement

You are given a sequence with <var>N</var> integers: <var>A = \{ A_1, A_2, \cdots, A_N \}</var>.
For each of these <var>N</var> integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:

If <var>A_i</var> and <var>A_j</var> <var>(i < j)</var> are painted with the same color, <var>A_i < A_j</var>.

Find the minimum number of colors required to satisfy the condition.

Constraints

<var>1 \leq N \leq 10^5</var>

<var>0 \leq A_i \leq 10^9</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var>
<var>:</var>
<var>A_N</var>

Output

Print the minimum number of colors required to satisfy the condition.

Sample Input 1

5
2
1
4
5
3

Sample Output 1

2

We can satisfy the condition with two colors by, for example, painting <var>2</var> and <var>3</var> red and painting <var>1</var>, <var>4</var>, and <var>5</var> blue.

Sample Input 2

4
0
0
0
0

Sample Output 2

4

We have to paint all the integers with distinct colors.

int solution(void) {
  int n;
  scanf("%d", &n);
  int ary[n];

  int bry[n];
  int length = 0;
  for (int i = 0; i < n; i++) {
    bry[i] = -1;
    scanf("%d", &ary[i]);
    int k = 0;
    while (bry[k] >= ary[i]) {
      k++;
    }
    if (bry[k] == -1) {
      length++;
    }
    bry[k] = ary[i];
  }
  printf("%d\n", length);

  return 0;
}

fn solution() {
    input! {
        n: usize,
        v: [usize; n]
    }
    let mut c = vec![v[0]];
    for &a in &v[1..] {
        if a > c[0] {
            c[0] = a;
            continue;
        }
        let mut l = 0;
        let mut r = c.len();
        while l + 1 < r {
            let m = (l + r) / 2;
            if c[m] >= a {
                l = m;
            } else {
                r = m;
            }
        }
        if r == c.len() {
            c.push(a);
        } else {
            c[r] = a;
        }
    }
    println!("{}", c.len());
}


void solution(int arr[], int i, int j) {
  int temp;
  int k;
  if (arr[i] > arr[j]) {
    temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
  if ((i + 1) >= j) {
    return;
  }
  k = ((j - i + 1) / 3);
  stoogesort(arr, i, j - k);
  stoogesort(arr, i + k, j);
  stoogesort(arr, i, j - k);
}

fn solution<T: Ord>(arr: &mut [T]) {
    if arr.is_empty() {
        return;
    }

    fn sort<T: Ord>(arr: &mut [T], start: usize, end: usize) {
        if arr[start] > arr[end] {
            arr.swap(start, end);
        }

        if start + 1 >= end {
            return;
        }

        let k = (end - start + 1) / 3;

        sort(arr, start, end - k);
        sort(arr, start + k, end);
        sort(arr, start, end - k);
    }

    sort(arr, 0, arr.len() - 1);
}


Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:  Root the tree at node 1.  Count the number of nodes at an even depth. Let it be evenCnt.  Count the number of nodes at an odd depth. Let it be oddCnt.  The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

fn solution() {
    use std::io;
    use std::io::prelude::*;

    let mut input = String::new();

    io::stdin().read_to_string(&mut input).unwrap();

    let n: usize = input.trim().parse().unwrap();

    let _g = "1 2
1 3
2 4
2 5
3 6
4 7
4 8\n";

    let g = "1 2
1 3
1 4
2 5
2 6\n";

    let mut ans = String::new();

    if n < 6 {
        ans.push_str("-1\n");
    } else {
        ans.push_str(g);
        for i in 6 + 1..n + 1 {
            ans.push_str(&format!("2 {}\n", i));
        }
    }
    for i in 2..n + 1 {
        ans.push_str(&format!("1 {}\n", i));
    }

    println!("{}", ans);
}


Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...Let's define a Rooted Dead Bush (RDB) of level $$$n$$$ as a rooted tree constructed as described below.A rooted dead bush of level $$$1$$$ is a single vertex. To construct an RDB of level $$$i$$$ we, at first, construct an RDB of level $$$i-1$$$, then for each vertex $$$u$$$:   if $$$u$$$ has no children then we will add a single child to it;  if $$$u$$$ has one child then we will add two children to it;  if $$$u$$$ has more than one child, then we will skip it.   Rooted Dead Bushes of level $$$1$$$, $$$2$$$ and $$$3$$$. Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:  The center of the claw is the vertex with label $$$1$$$. Lee has a Rooted Dead Bush of level $$$n$$$. Initially, all vertices of his RDB are green.In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo $$$10^9+7$$$.

int solution(int argc, char const *argv[]) {
  const long long int N = 2e6;
  const long long int T = 1e4 + 1;
  const long long int mod = 1e9 + 7;

  long long int a[N];

  long long int n;
  long long int max = 0;
  a[0] = 0;
  a[1] = 0;
  a[2] = 0;
  a[3] = 4;
  if (scanf("%lld", &n) != EOF) {
  };
  long long int q[T];
  long long int i;
  for (i = 0; i < n; i++) {
    if (scanf("%lld", &q[i]) != EOF) {
    }
    if (q[i] > max) {
      max = q[i];
    }
  }
  for (i = 4; i <= max; i++) {
    a[i] = 2 * a[i - 2] + a[i - 1];
    a[i] = a[i] % mod;
    if (i % 3 == 0) {
      a[i] = (a[i] + 4) % mod;
    }
  }
  for (i = 0; i < n; i++) {
    printf("%lld\n", a[q[i]]);
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    let mut xs: Vec<i64> = Vec::new();
    for _ in 0..t {
        let x: i64 = lines.next().unwrap().unwrap().parse().unwrap();
        xs.push(x);
    }
    let m = xs.iter().max().unwrap();
    let mut memo: Vec<i64> = vec![0; *m as usize + 1];
    memo[3] = 4;
    memo[4] = 4;
    memo[5] = 12;
    for i in 6..(*m as usize + 1) {
        if i % 3 == 0 {
            memo[i] = (memo[i - 2] + 4 * memo[i - 3] + 4 * memo[i - 4] + 4) % 1000000007;
        } else {
            memo[i] = (memo[i - 1] + 2 * memo[i - 2]) % 1000000007;
        }
    }
    for i in 0..t {
        println!("{}", memo[xs[i] as usize]);
    }
}


There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.    Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1] Polycarpus has bought a posh piano and is thinking about how to get it into the house. In order to carry out his plan, he needs to take exactly k consecutive planks from the fence. Higher planks are harder to tear off the fence, so Polycarpus wants to find such k consecutive planks that the sum of their heights is minimal possible.Write the program that finds the indexes of k consecutive planks with minimal total height. Pay attention, the fence is not around Polycarpus's home, it is in front of home (in other words, the fence isn't cyclic).

int solution(void) {
  int n = 0;
  int k = 0;

  scanf("%d %d", &n, &k);

  int arr[n];

  for (int i = 0, a = 0, b = 0; i < n; i++) {
    scanf("%d", &a);
    arr[i] = a + b;
    b = arr[i];
  }

  int m = arr[k - 1];
  int r = 0;

  for (int i = 1, j = k; j < n; i++, j++) {
    int tmp = arr[j] - arr[i - 1];
    if (m > tmp) {
      r = i + 1;
      m = tmp;
    }
  }

  printf("%d\n", r > 0 ? r : 1);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let input = &mut String::new();

    input.clear();
    stdin.read_line(input);

    let A: Vec<usize> = input
        .trim()
        .split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
    let n = A[0];
    let k = A[1];

    input.clear();
    stdin.read_line(input);

    let h: Vec<u32> = input
        .trim()
        .split(' ')
        .map(|s| s.parse().unwrap())
        .collect();

    let mut C = vec![0u32; n - k + 1];

    C[0] = h.iter().take(k).sum();

    for i in 1..n - k + 1 {
        C[i] = C[i - 1] - h[i - 1] + h[i + k - 1];
    }

    println!(
        "{}",
        C.iter()
            .enumerate()
            .min_by_key(|&(_, item)| item)
            .unwrap()
            .0
            + 1
    );
}


You are given a multiset (i. e. a set that can contain multiple equal integers) containing $$$2n$$$ integers. Determine if you can split it into exactly $$$n$$$ pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by $$$2$$$, the remainder is $$$1$$$).

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    scanf("%d", &n);
    int A[2 * n];
    int sum = 0;
    int even = 0;
    int odd = 0;
    for (int i = 0; i < 2 * n; i++) {
      scanf("%d", &A[i]);

      if (A[i] % 2 == 0) {
        even++;
      }
      if (A[i] % 2 == 1) {
        odd++;
      }
    }
    if (odd == even) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }
  }
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let (l, e) = l
            .unwrap()
            .trim()
            .split(' ')
            .map(|w| w.parse::<u32>().unwrap())
            .fold((0, 0), |(c, e), n| {
                if n % 2 == 0 {
                    (c + 1, e + 1)
                } else {
                    (c + 1, e)
                }
            });
        writeln!(o, "{}", if l / 2 == e { "Yes" } else { "No" }).ok();
    }
}


Score : <var>300</var> points

Problem Statement

You are given two non-negative integers <var>L</var> and <var>R</var>.
We will choose two integers <var>i</var> and <var>j</var> such that <var>L \leq i < j \leq R</var>.
Find the minimum possible value of <var>(i \times j) \mbox{ mod } 2019</var>.

Constraints

All values in input are integers.

<var>0 \leq L < R \leq 2 \times 10^9</var>

Input

Input is given from Standard Input in the following format:

<var>L</var> <var>R</var>

Output

Print the minimum possible value of <var>(i \times j) \mbox{ mod } 2019</var> when <var>i</var> and <var>j</var> are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When <var>(i, j) = (2020, 2021)</var>, <var>(i \times j) \mbox{ mod } 2019  = 2</var>.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: <var>(i, j) = (4, 5)</var>.

int solution() {
  long long L = 0;
  long long R = 0;
  long long i = 0;
  long long j = 0;
  long long ans = 0;
  long long min = -1;
  scanf("%lld %lld", &L, &R);
  if (R - L >= 2019) {
    min = 0;
  } else {
    for (i = 0; L + i < R; i++) {
      for (j = i + 1; L + j <= R; j++) {
        ans = (((L + i) % 2019) * ((L + j) % 2019)) % 2019;

        if (ans < min || min == -1) {
          min = ans;
        }
      }
    }
  }
  printf("%lld", min);
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let l: u64 = itr.next().unwrap().parse().unwrap();
    let r: u64 = itr.next().unwrap().parse().unwrap();

    if r - l >= 2019 {
        println!("0");
    } else {
        let mut ans = 1u64 << 60;
        for i in l..r + 1 {
            for j in i + 1..r + 1 {
                ans = std::cmp::min(ans, i % 2019 * j % 2019);
            }
        }
        println!("{}", ans);
    }
}


This is an interactive problem.This is an easy version of the problem. The difference from the hard version is that in the easy version $$$t=1$$$ and the number of queries is limited to $$$20$$$.Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polycarp wins if he guesses the position of the $$$k$$$-th zero from the left $$$t$$$ times.Polycarp can make no more than $$$20$$$ requests of the following type:   ? $$$l$$$ $$$r$$$ — find out the sum of all elements in positions from $$$l$$$ to $$$r$$$ ($$$1 \le l \le r \le n$$$) inclusive. In this (easy version) of the problem, this paragraph doesn't really make sense since $$$t=1$$$ always. To make the game more interesting, each guessed zero turns into one and the game continues on the changed array. More formally, if the position of the $$$k$$$-th zero was $$$x$$$, then after Polycarp guesses this position, the $$$x$$$-th element of the array will be replaced from $$$0$$$ to $$$1$$$. Of course, this feature affects something only for $$$t>1$$$.Help Polycarp win the game.

int solution() {
  int n;
  int t;
  int k;
  int l = 1;
  int r;
  int mid;
  int cnt;
  scanf("%d%d%d", &n, &t, &k);
  r = n;
  while (l <= r) {
    mid = (l + r) / 2;
    printf("? 1 %d\n", mid);
    fflush(stdout);
    scanf("%d", &cnt);
    if (mid - cnt >= k) {
      r = mid - 1;
    } else {
      l = mid + 1;
    }
  }
  printf("! %d", l);
  return 0;
}

fn solution() {
    let std_in = stdin();
    let in_lock = std_in.lock();
    let input = BufReader::new(in_lock);

    let std_out = stdout();
    let out_lock = std_out.lock();
    let mut output = BufWriter::new(out_lock);

    let mut lines = input.lines().map(|x| x.unwrap());

    let s = lines.next().unwrap();
    let mut it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());
    let n = it.next().unwrap();
    let t = it.next().unwrap();

    'cases: for _ in 0..t {
        let k = lines.next().unwrap().parse::<usize>().unwrap();

        let mut low = 0;
        let mut up = n;

        while low + 1 < up {
            let i = (low + up) / 2;

            writeln!(&mut output, "? {} {}", 1, i).unwrap();
            output.flush().unwrap();
            let resp = lines.next().unwrap().parse::<usize>().unwrap();

            let x = i - resp;

            if x >= k {
                up = i;
            } else {
                low = i;
            }

            dbg!(low, up);
        }

        let ans = up;

        writeln!(&mut output, "! {}", ans).unwrap();
    }
}


Score : <var>400</var> points

Problem Statement

We have an <var>H</var>-by-<var>W</var> matrix.
Let <var>a_{ij}</var> be the element at the <var>i</var>-th row from the top and <var>j</var>-th column from the left.
In this matrix, each <var>a_{ij}</var> is a lowercase English letter.

Snuke is creating another <var>H</var>-by-<var>W</var> matrix, <var>A'</var>, by freely rearranging the elements in <var>A</var>.
Here, he wants to satisfy the following condition:

Every row and column in <var>A'</var> can be read as a palindrome.

Determine whether he can create a matrix satisfying the condition.

Note

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and abcba are all palindromes, while ab, abab and abcda are not.

Constraints

<var>1 ≤ H, W ≤ 100</var>

<var>a_{ij}</var> is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>a_{11}</var><var>a_{12}</var><var>...</var><var>a_{1W}</var>
<var>:</var>
<var>a_{H1}</var><var>a_{H2}</var><var>...</var><var>a_{HW}</var>

Output

If Snuke can create a matrix satisfying the condition, print Yes; otherwise, print No.

Sample Input 1

3 4
aabb
aabb
aacc

Sample Output 1

Yes

For example, the following matrix satisfies the condition.

abba
acca
abba

Sample Input 2

2 2
aa
bb

Sample Output 2

No

It is not possible to create a matrix satisfying the condition, no matter how we rearrange the elements in <var>A</var>.

Sample Input 3

5 1
t
w
e
e
t

Sample Output 3

Yes

For example, the following matrix satisfies the condition.

t
e
w
e
t

Sample Input 4

2 5
abxba
abyba

Sample Output 4

No

Sample Input 5

1 1
z

Sample Output 5

Yes

int solution(void) {

  int h;
  int w;
  scanf("%d %d", &h, &w);
  char a[h][w + 1];
  for (int i = 0; i < h; i++) {
    scanf("%s", a[i]);
  }
  int alp[26];
  for (int i = 0; i < 26; i++) {
    alp[i] = 0;
  }
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      alp[a[i][j] - 'a']++;
    }
  }
  int need_4 = (h / 2) * (w / 2);
  int need_2 = 0;
  if (h % 2 == 1) {
    need_2 += w / 2;
  }
  if (w % 2 == 1) {
    need_2 += h / 2;
  }
  int stock_4 = 0;
  int stock_2 = 0;
  for (int i = 0; i < 26; i++) {
    stock_4 += alp[i] / 4;
    if (alp[i] % 4 == 2) {
      stock_2++;
    }
  }
  if (stock_4 >= need_4) {
    stock_2 += (stock_4 - need_4) * 2;
    if (stock_2 >= need_2) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }
  } else {
    printf("No\n");
  }

  return 0;
}

fn solution() {
    let (H, W): (usize, usize) = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };
    let S: Vec<Vec<char>> = (0..H)
        .map(|_| {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().chars().collect()
        })
        .collect();

    let mut c = std::collections::HashMap::new();
    for i in 0..H {
        for j in 0..W {
            *(c.entry(S[i][j]).or_insert(0)) += 1;
        }
    }
    let mut dp = [0, 0, 0, 0];
    for &v in c.values() {
        dp[v % 4] += 1;
    }

    let ans = if (H % 2 == 0 && W % 2 == 0 && dp[1] == 0 && dp[2] == 0 && dp[3] == 0)
        || (H % 2 == 0 && W % 2 == 1 && dp[1] == 0 && dp[3] == 0 && dp[2] <= H / 2)
        || (H % 2 == 1 && W % 2 == 0 && dp[1] == 0 && dp[3] == 0 && dp[2] <= W / 2)
        || (H % 2 == 1 && W % 2 == 1 && dp[1] + dp[3] <= 1 && dp[2] + dp[3] <= H / 2 + W / 2)
    {
        "Yes"
    } else {
        "No"
    };

    println!("{}", ans);
}


Omkar is building a waterslide in his water park, and he needs your help to ensure that he does it as efficiently as possible.Omkar currently has $$$n$$$ supports arranged in a line, the $$$i$$$-th of which has height $$$a_i$$$. Omkar wants to build his waterslide from the right to the left, so his supports must be nondecreasing in height in order to support the waterslide. In $$$1$$$ operation, Omkar can do the following: take any contiguous subsegment of supports which is nondecreasing by heights and add $$$1$$$ to each of their heights. Help Omkar find the minimum number of operations he needs to perform to make his supports able to support his waterslide!An array $$$b$$$ is a subsegment of an array $$$c$$$ if $$$b$$$ can be obtained from $$$c$$$ by deletion of several (possibly zero or all) elements from the beginning and several (possibly zero or all) elements from the end.An array $$$b_1, b_2, \dots, b_n$$$ is called nondecreasing if $$$b_i\le b_{i+1}$$$ for every $$$i$$$ from $$$1$$$ to $$$n-1$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t) {
    int n;
    long long d = 0;
    long long sum = 0;
    scanf("%d", &n);
    long long a[n];
    for (long long i = 0; i < n; i++) {
      scanf("%lld ", &a[i]);
    }

    for (int i = n - 1; i > 0; i--) {
      d = a[i - 1] - a[i];
      if (d > 0) {
        sum = sum + d;
      }
    }
    printf("%lld\n", sum);
    t--;
  }
}

fn solution() {
    let t: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

    for _ in 0..t {
        let n: usize = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            buf.trim_end().parse().unwrap()
        };

        let a: Vec<i64> = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let iter = buf.split_whitespace();
            iter.map(|x| x.parse().unwrap()).collect()
        };

        let mut ans = 0;
        for i in 0..(n - 1) {
            if a[i] > a[i + 1] {
                ans += a[i] - a[i + 1];
            }
        }
        println!("{}", ans);
    }
}


Ashish has a binary string $$$s$$$ of length $$$n$$$ that he wants to sort in non-decreasing order.He can perform the following operation:   Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $$$k$$$ such that $$$1 \leq k \leq n$$$ and any sequence of $$$k$$$ indices $$$1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n$$$ such that $$$s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}$$$.  Reverse this subsequence in-place. Formally, swap $$$s_{i_1}$$$ with $$$s_{i_k}$$$, swap $$$s_{i_2}$$$ with $$$s_{i_{k-1}}$$$, $$$\ldots$$$ and swap $$$s_{i_{\lfloor k/2 \rfloor}}$$$ with $$$s_{i_{\lceil k/2 \rceil + 1}}$$$ (Here $$$\lfloor x \rfloor$$$ denotes the largest integer not exceeding $$$x$$$, and $$$\lceil x \rceil$$$ denotes the smallest integer not less than $$$x$$$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $$$n$$$ operations.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    char string[n + 1];
    scanf("%s", string);
    int ans[n + 1];

    int one = 0;
    int zero = 0;
    for (int i = 0; i < n; i++) {
      if (string[i] == '1') {
        one++;
      } else {
        zero++;
      }
    }
    int wrong = 0;
    for (int i = 0; i < zero; i++) {
      if (string[i] == '1') {
        wrong++;
        ans[wrong] = i + 1;
      }
    }
    for (int i = zero; i < n; i++) {
      if (string[i] == '0') {
        wrong++;
        ans[wrong] = i + 1;
      }
    }

    ans[0] = wrong;
    if (wrong == 0) {
      printf("0\n");
      continue;
    }
    printf("1\n");
    for (int i = 0; i <= wrong; i++) {
      printf("%d ", ans[i]);
    }
    printf("\n");
  }
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let (mut x, mut y) = (vec![], vec![]);
        for (j, c) in l.unwrap().chars().enumerate() {
            if c == '0' {
                x.push(j)
            } else {
                y.push(j)
            }
        }
        x.reverse();

        let m = x.iter().zip(y.iter()).take_while(|(x, y)| x > y).count();

        if m == 0 {
            writeln!(o, "0").ok();
        } else {
            write!(o, "1\n{} ", m * 2).ok();
            for n in y[..m].iter().chain(x[..m].iter().rev()) {
                write!(o, "{} ", n + 1).ok();
            }
            writeln!(o).ok();
        }
    }
}


Score : <var>500</var> points

Problem Statement

We have <var>N</var> bulbs arranged on a number line, numbered <var>1</var> to <var>N</var> from left to right.
Bulb <var>i</var> is at coordinate <var>i</var>.

Each bulb has a non-negative integer parameter called intensity.
When there is a bulb of intensity <var>d</var> at coordinate <var>x</var>, the bulb illuminates the segment from coordinate <var>x-d-0.5</var> to <var>x+d+0.5</var>.
Initially, the intensity of Bulb <var>i</var> is <var>A_i</var>. We will now do the following operation <var>K</var> times in a row:

For each integer <var>i</var> between <var>1</var> and <var>N</var> (inclusive), let <var>B_i</var> be the number of bulbs illuminating coordinate <var>i</var>. Then, change the intensity of each bulb <var>i</var> to <var>B_i</var>.

Find the intensity of each bulb after the <var>K</var> operations.

Constraints

<var>1 \leq N \leq 2 \times 10^5</var>

<var>1 \leq K \leq 2 \times 10^5</var>

<var>0 \leq A_i \leq N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>A_1</var> <var>A_2</var> <var>\ldots</var> <var>A_N</var>

Output

Print the intensity <var>A{'}_i</var> of each bulb <var>i</var> after the <var>K</var> operations to Standard Output in the following format:

<var>A{'}_1</var> <var>A{'}_2</var> <var>\ldots</var> <var>A{'}_N</var>

Sample Input 1

5 1
1 0 0 1 0

Sample Output 1

1 2 2 1 2

Initially, only Bulb <var>1</var> illuminates coordinate <var>1</var>, so the intensity of Bulb <var>1</var> becomes <var>1</var> after the operation.
Similarly, the bulbs initially illuminating coordinate <var>2</var> are Bulb <var>1</var> and <var>2</var>, so the intensity of Bulb <var>2</var> becomes <var>2</var>.

Sample Input 2

5 2
1 0 0 1 0

Sample Output 2

3 3 4 4 3

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    let mut itr = is.split_whitespace().map(|e| e.parse::<usize>().unwrap());
    let n: usize = itr.next().unwrap();
    let k: usize = itr.next().unwrap();
    is.clear();
    stdin().read_line(&mut is).ok();
    let mut a = is
        .split_whitespace()
        .map(|e| e.parse::<usize>().unwrap())
        .collect::<Vec<usize>>();

    for _ in 0..k {
        let mut b = vec![0usize; n + 1];
        for i in 0..n {
            let l = i.saturating_sub(a[i]);
            let r = min(i + a[i] + 1, n);
            b[l] = b[l].wrapping_add(1);
            b[r] = b[r].wrapping_add(!0);
        }
        a = vec![0; n];
        for i in 0..n {
            a[i] = a[if i > 0 { i - 1 } else { 0 }].wrapping_add(b[i]);
        }

        if a.iter().all(|e| e == &n) {
            break;
        }
    }

    let mut flg = false;
    for e in a {
        if flg {
            print!(" ");
        }
        print!("{}", e);
        flg = true;
    }
    println!();
}


Score : <var>500</var> points

Problem Statement

Snuke received a positive integer <var>N</var> from Takahashi.
A positive integer <var>m</var> is called a favorite number when the following condition is satisfied:

The quotient and remainder of <var>N</var> divided by <var>m</var> are equal, that is, <var>\lfloor \frac{N}{m} \rfloor = N \bmod m</var> holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

<var>1 \leq N \leq 10^{12}</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: <var>3</var> and <var>7</var>. Print the sum of these, <var>10</var>.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.

int solution() {
  long long int n = 0;
  long long int sum = 0;
  scanf("%lld\n", &n);
  for (long long int i = 1; i * (i + 1) + 1 <= n; i++) {
    if ((n - i) % i == 0) {
      sum += (n - i) / i;
    }
  }
  printf("%lld\n", sum);
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();

    let mut ans = 0;
    let mut i = 1;
    while i * i <= n {
        if n.is_multiple_of(i) {
            let d = n / i;
            if i > 1 && d == n % (i - 1) {
                ans += i - 1;
            }

            if n / i != i {
                let d = i;
                if n / i > 1 && d == n % (n / i - 1) {
                    ans += n / i - 1;
                }
            }
        }
        i += 1;
    }

    println!("{}", ans);
}


Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4

int solution() {
  int N = 0;
  int number = 0;
  int i = 0;
  int divide = 0;
  int count = 0;
  int flag = 0;

  scanf("%d", &N);
  for (i = 0; i < N; i++) {
    scanf("%d", &number);
    divide = 2;
    flag = 0;
    while (divide * divide <= number) {
      if ((number % divide) == 0) {
        flag = 1;
        break;
      }
      divide++;
    }

    if (flag != 1) {
      count++;
    }
  }

  printf("%d\n", count);

  return 0;
}

fn solution() {
    let mut s = String::new();
    let stdin = io::stdin();

    let _ = stdin.read_line(&mut s);

    let n: usize = s.trim().parse().unwrap();

    s.clear();

    let nums = stdin
        .lock()
        .lines()
        .take(n)
        .map(|s| s.ok().unwrap().trim().parse().unwrap_or(0));

    let answer = nums
        .filter(|&x| {
            let m = f64::sqrt(x as f64).ceil() as u64;

            x == 2 || (2..(m + 1)).all(|y| x % y != 0)
        })
        .count();

    println!("{}", answer);
}


Score : <var>400</var> points

Problem Statement

We have a string <var>s</var> consisting of lowercase English letters.
Snuke can perform the following operation repeatedly:

Insert a letter x to any position in <var>s</var> of his choice, including the beginning and end of <var>s</var>.

Snuke's objective is to turn <var>s</var> into a palindrome.
Determine whether the objective is achievable. If it is achievable, find the minimum number of operations required.

Notes

A palindrome is a string that reads the same forward and backward.
For example, a, aa, abba and  abcba are palindromes, while ab, abab and abcda are not.

Constraints

<var>1 \leq |s| \leq 10^5</var>

<var>s</var> consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

<var>s</var>

Output

If the objective is achievable, print the number of operations required.
If it is not, print -1 instead.

Sample Input 1

xabxa

Sample Output 1

2

One solution is as follows (newly inserted x are shown in bold):

xabxa → xaxbxa → xaxbxax

Sample Input 2

ab

Sample Output 2

-1

No sequence of operations can turn <var>s</var> into a palindrome.

Sample Input 3

a

Sample Output 3

0

<var>s</var> is a palindrome already at the beginning.

Sample Input 4

oxxx

Sample Output 4

3

One solution is as follows:

oxxx → xoxxx → xxoxxx → xxxoxxx

int solution() {
  int ans = 0;
  int flag = 0;
  int first = 0;
  int last = 99999;
  char s[100001];
  scanf("%s", s);

  last = strlen(s) - 1;
  while (flag == 0) {
    if (s[first] != s[last] && s[first] != 'x' && s[last] != 'x') {
      flag++;
    } else if (s[first] == s[last]) {
      first++;
      last--;
    } else if (s[first] == 'x' && s[last] != 'x') {
      first++;
      ans++;
    } else if (s[first] != 'x' && s[last] == 'x') {
      last--;
      ans++;
    }

    if (first >= last) {
      printf("%d", ans);
      return 0;
    }
  }
  printf("-1");
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let s: Vec<char> = itr.next().unwrap().chars().collect();

    let mut l = 0;
    let mut r = s.len() - 1;
    let mut ans = 0;
    while r > l {
        if s[l] == s[r] {
            l += 1;
            r -= 1;
        } else if s[l] == 'x' {
            l += 1;
            ans += 1;
        } else if s[r] == 'x' {
            r -= 1;
            ans += 1;
        } else {
            println!("-1");
            return;
        }
    }
    println!("{}", ans);
}


Score : <var>400</var> points

Problem Statement

An altar enshrines <var>N</var> stones arranged in a row from left to right. The color of the <var>i</var>-th stone from the left <var>(1 \leq i \leq N)</var> is given to you as a character <var>c_i</var>; R stands for red and W stands for white.

You can do the following two kinds of operations any number of times in any order:

Choose two stones (not necessarily adjacent) and swap them.

Choose one stone and change its color (from red to white and vice versa).

According to a fortune-teller, a white stone placed to the immediate left of a red stone will bring a disaster. At least how many operations are needed to reach a situation without such a white stone?

Constraints

<var>2 \leq N \leq 200000</var>

<var>c_i</var> is R or W.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>c_{1}c_{2}...c_{N}</var>

Output

Print an integer representing the minimum number of operations needed.

Sample Input 1

4
WWRR

Sample Output 1

2

For example, the two operations below will achieve the objective.

Swap the <var>1</var>-st and <var>3</var>-rd stones from the left, resulting in RWWR.

Change the color of the <var>4</var>-th stone from the left, resulting in RWWW.

Sample Input 2

2
RR

Sample Output 2

0

It can be the case that no operation is needed.

Sample Input 3

8
WRWWRWRR

Sample Output 3

3

int solution(void) {
  int n;
  scanf("%d", &n);
  char s[n + 1];
  scanf("%s", s);
  int r = 0;
  int w = 0;
  int ans[n];
  for (int i = 0; i < n; i++) {
    ans[i] = w;
    (*(s[i] == 'R' ? &r : &w))++;
  }
  printf("%d\n", r < n ? ans[r] : 0);
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    let n: usize = s.trim().parse().ok().unwrap();
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();

    let (mut r, mut w) = (VecDeque::new(), VecDeque::new());
    r.push_back(0);
    for (i, c) in s.trim().chars().enumerate() {
        match c {
            'R' => r.push_back(i),
            'W' => w.push_front(i),
            _ => exit(1),
        };
    }
    w.push_front(n);
    let c = r
        .iter()
        .rev()
        .zip(w.iter().rev())
        .filter(|(x, y)| x > y)
        .count();
    println!("{}", c);
}


int solution(const int *arr, int x, size_t n) {
  if (n == 0)
    return -1;

  size_t step = (size_t)floor(sqrt((double)n));
  size_t prev = 0;
  size_t current_limit;

  while (1) {
    current_limit = (step < n) ? step : n;

    if (arr[current_limit - 1] >= x) {
      break;
    }

    prev = step;
    step += (size_t)floor(sqrt((double)n));

    if (prev >= n) {
      return -1;
    }
  }

  current_limit = (step < n) ? step : n;
  while (arr[prev] < x) {
    prev++;
    if (prev == current_limit) {
      return -1;
    }
  }

  if (arr[prev] == x) {
    return (int)prev;
  }

  return -1;
}

fn solution<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
    let len = arr.len();
    if len == 0 {
        return None;
    }
    let mut step = (len as f64).sqrt() as usize;
    let mut prev = 0;

    while &arr[min(len, step) - 1] < item {
        prev = step;
        step += (len as f64).sqrt() as usize;
        if prev >= len {
            return None;
        }
    }
    while &arr[prev] < item {
        prev += 1;
    }
    if &arr[prev] == item {
        return Some(prev);
    }
    None
}


Suppose you are living with two cats: A and B. There are $$$n$$$ napping spots where both cats usually sleep.Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:   Cat A changes its napping place in order: $$$n, n - 1, n - 2, \dots, 3, 2, 1, n, n - 1, \dots$$$ In other words, at the first hour it's on the spot $$$n$$$ and then goes in decreasing order cyclically;  Cat B changes its napping place in order: $$$1, 2, 3, \dots, n - 1, n, 1, 2, \dots$$$ In other words, at the first hour it's on the spot $$$1$$$ and then goes in increasing order cyclically. The cat B is much younger, so they have a strict hierarchy: A and B don't lie together. In other words, if both cats'd like to go in spot $$$x$$$ then the A takes this place and B moves to the next place in its order (if $$$x < n$$$ then to $$$x + 1$$$, but if $$$x = n$$$ then to $$$1$$$). Cat B follows his order, so it won't return to the skipped spot $$$x$$$ after A frees it, but will move to the spot $$$x + 2$$$ and so on.Calculate, where cat B will be at hour $$$k$$$?

fn solution() {
    let mut t = String::new();
    io::stdin().read_line(&mut t).unwrap();
    let t: usize = t.trim().parse().unwrap();

    let mut n_k = String::new();
    for _t in 0..t {
        n_k.clear();
        io::stdin().read_line(&mut n_k).unwrap();
        let mut n_k = n_k.split_whitespace();
        let n: u64 = n_k.next().unwrap().parse().unwrap();
        let k: u64 = n_k.next().unwrap().parse().unwrap();
        let mut b_position: u64;
        if n.is_multiple_of(2) {
            b_position = k % n;
        } else {
            let times_crossed = (k - 1) / (n / 2);
            b_position = (k + times_crossed) % n;
        }

        if b_position == 0 {
            b_position = n;
        }

        println!("{}", b_position);
    }
}


Drawing Lots

Let's play Amidakuji.

In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines.

In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first step, 2 and 4 are swaped by the first horizontal line which connects second and fourth vertical lines (we call this operation (2, 4)). Likewise, we perform (3, 5), (1, 2) and (3, 4), then obtain "4 1 2 5 3" in the bottom.

Your task is to write a program which reads the number of vertical lines <var>w</var> and configurations of horizontal lines and prints the final state of the Amidakuji. In the starting pints, numbers 1, 2, 3, ..., <var>w</var> are assigne to the vertical lines from left to right.

Input

<var>w</var>
<var>n</var>
<var>a1</var>,<var>b1</var>
<var>a2</var>,<var>b2</var>
.
.
<var>an</var>,<var>bn</var>

<var>w</var> (<var>w</var> ≤ 30) is the number of vertical lines. <var>n</var> (<var>n</var> ≤ 30) is the number of horizontal lines. A pair of two integers <var>ai</var> and <var>bi</var> delimited by a comma represents the <var>i</var>-th horizontal line.

Output

The number which should be under the 1st (leftmost) vertical line

The number which should be under the 2nd vertical line

:

The number which should be under the <var>w</var>-th vertical line

Sample Input

5
4
2,4
3,5
1,2
3,4

Output for the Sample Input

4
1
2
5
3

int solution() {
  int i = 0;
  int count = 0;
  int tate = 0;
  int yoko = 0;
  int change = 0;
  int in_out_box[30 + 1];
  int num1 = 0;
  int num1_index = 0;
  int num2 = 0;
  int num2_index = 0;
  char str[10];

  scanf("%d", &tate);

  fgets(str, (sizeof(str)), stdin);
  for (i = 0; i < tate; i++) {
    in_out_box[i] = i + 1;
  }

  scanf("%d", &yoko);

  fgets(str, (sizeof(str)), stdin);

  for (count = 0; count < yoko; count++) {
    scanf("%d,%d", &num1, &num2);
    for (i = 0; i < tate; i++) {
      if (i + 1 == num1) {
        change = in_out_box[i];
        num1_index = i;
      }
      if (i + 1 == num2) {
        in_out_box[num1_index] = in_out_box[i];
        in_out_box[i] = change;
      }
    }
  }

  for (i = 0; i < tate; i++) {
    printf("%d\n", in_out_box[i]);
  }
  return 0;
}

fn solution() {
    let mut w: u32 = 0;
    for i in 0..2 {
        let mut buf = String::new();
        stdin().read_line(&mut buf).unwrap();
        match i {
            0 => w = buf.trim().parse().unwrap(),
            _ => break,
        }
    }
    let reader = BufReader::new(stdin());
    let mut hlines = vec![];
    for line in reader.lines() {
        let l: Vec<u32> = line
            .unwrap()
            .trim()
            .split(',')
            .filter_map(|x| x.parse::<u32>().ok())
            .collect();
        hlines.push((l[0], l[1]));
    }

    let mut answer = Vec::with_capacity((w + 1) as usize);
    for i in 1..w + 2 {
        answer.push(i);
    }
    for i in 1..w + 1 {
        let mut current = i;
        for hline in &hlines {
            if hline.0 == current {
                current = hline.1;
            } else if hline.1 == current {
                current = hline.0;
            }
        }
        answer[(current - 1) as usize] = i;
    }
    for i in 0..w {
        println!("{}", answer[i as usize]);
    }
}


You are given a board of size $$$2 \times n$$$ ($$$2$$$ rows, $$$n$$$ columns). Some cells of the board contain chips. The chip is represented as '*', and an empty space is represented as '.'. It is guaranteed that there is at least one chip on the board.In one move, you can choose any chip and move it to any adjacent (by side) cell of the board (if this cell is inside the board). It means that if the chip is in the first row, you can move it left, right or down (but it shouldn't leave the board). Same, if the chip is in the second row, you can move it left, right or up.If the chip moves to the cell with another chip, the chip in the destination cell disappears (i. e. our chip captures it).Your task is to calculate the minimum number of moves required to leave exactly one chip on the board.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t = 0;
  int n = 0;
  char s[2][200001] = {};

  int res = 0;

  int visited[2][200000] = {};
  int rchip[2][200000] = {};

  res = scanf("%d", &t);

  while (t > 0) {
    int cnt[2] = {};
    int min = 0;
    int ans = 0;
    res = scanf("%d", &n);
    res = scanf("%s", s[0]);
    res = scanf("%s", s[1]);
    min = n;
    for (int i = 0; i < 2; i++) {
      int tmp_min = n;
      for (int j = n - 1; j >= 0; j--) {
        rchip[i][j] = tmp_min;
        if (s[i][j] == '*') {
          cnt[i]++;
          if (j < tmp_min) {
            tmp_min = j;
          }
        }
        visited[i][j] = 0;
      }
      if (tmp_min < min) {
        min = tmp_min;
      }
    }
    ans = 2 * n;
    for (int i = 0; i < 2; i++) {
      if (s[i][min] == '*') {
        int ci = i;
        int cj = min;
        int tmp_cnt = 1;
        int tmp_ans = 0;
        while (tmp_cnt < cnt[0] + cnt[1]) {
          visited[ci][cj] = i + 1;
          if (visited[1 - ci][cj] < i + 1 && s[1 - ci][cj] == '*') {
            if (rchip[1 - ci][cj] < rchip[ci][cj]) {
              ci = 1 - ci;
            } else {
              visited[1 - ci][cj] = i + 1;
              if (s[ci][cj] != '*') {
                tmp_cnt++;
              }
            }
          } else {
            cj++;
          }
          tmp_ans++;
          if (s[ci][cj] == '*') {
            tmp_cnt++;
          }
        }
        if (tmp_ans < ans) {
          ans = tmp_ans;
        }
      }
    }
    printf("%d\n", ans);
    t--;
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let stdin = stdin.lock();
    let mut lines = stdin.lines();
    lines.next();
    while let (Some(_), Some(Ok(first_line)), Some(Ok(second_line))) =
        (lines.next(), lines.next(), lines.next())
    {
        let (mut a, mut b) = (false, false);
        let mut count = 0;
        let mut prospective_count = 0;
        let iterator = first_line.chars().zip(second_line.chars());
        iterator
            .skip_while(|&(c1, c2)| c1 == '.' && c2 == '.')
            .for_each(|(c1, c2)| match (c1, c2) {
                ('.', '.') => {
                    prospective_count += 1;
                }
                ('.', '*') => {
                    if b {
                        count += 1;

                        a = false;
                        b = true;
                    } else if a {
                        count += 2;

                        a = true;
                        b = true;
                    } else {
                        a = false;
                        b = true;
                    }
                    count += prospective_count;
                    prospective_count = 0;
                }
                ('*', '.') => {
                    if a {
                        count += 1;

                        a = true;
                        b = false;
                    } else if b {
                        count += 2;

                        a = true;
                        b = true;
                    } else {
                        a = true;
                        b = false;
                    }
                    count += prospective_count;
                    prospective_count = 0;
                }
                ('*', '*') => {
                    if a || b {
                        count += 2;

                        a = true;
                        b = true;
                    } else {
                        count += 1;

                        a = true;
                        b = true;
                    }
                    count += prospective_count;
                    prospective_count = 0;
                }
                _ => panic!("invalid input"),
            });
        println!("{}", count);
    }
}


Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer $$$n$$$, he encrypts it in the following way: he picks three integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$l \leq a,b,c \leq r$$$, and then he computes the encrypted value $$$m = n \cdot a + b - c$$$.Unfortunately, an adversary intercepted the values $$$l$$$, $$$r$$$ and $$$m$$$. Is it possible to recover the original values of $$$a$$$, $$$b$$$ and $$$c$$$ from this information? More formally, you are asked to find any values of $$$a$$$, $$$b$$$ and $$$c$$$ such that  $$$a$$$, $$$b$$$ and $$$c$$$ are integers,  $$$l \leq a, b, c \leq r$$$,  there exists a strictly positive integer $$$n$$$, such that $$$n \cdot a + b - c = m$$$.

int solution() {

  int t;
  long long l;
  long long r;
  long long m;
  scanf("%d", &t);
  while (t--) {
    scanf("%lld %lld %lld", &l, &r, &m);
    long long min = m + l - r;
    long long max = m - l + r;

    for (long long a = l; a <= r; a++) {
      if ((max / a) * a >= min && (max / a > 0)) {

        long long tmp = m - ((max / a) * a);
        long long b;
        long long c;
        if (tmp > 0) {
          b = r;
          c = b - tmp;
        } else {
          c = r;
          b = tmp + c;
        }
        printf("%lld %lld %lld\n", a, b, c);
        break;
      }
    }
  }
}

fn solution() {
    let t: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

    for _ in 0..t {
        let (l, r, m): (u64, u64, u64) = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        for a in l..=r {
            let p = m % a;
            let q = a - p;

            if m >= a && p <= r - l {
                let b = r;
                let c = r - p;
                println!("{} {} {}", a, b, c);
                break;
            } else if q <= r - l {
                let b = l;
                let c = l + q;
                println!("{} {} {}", a, b, c);
                break;
            }
        }
    }
}


Kristina has two arrays $$$a$$$ and $$$b$$$, each containing $$$n$$$ non-negative integers. She can perform the following operation on array $$$a$$$ any number of times:   apply a decrement to each non-zero element of the array, that is, replace the value of each element $$$a_i$$$ such that $$$a_i > 0$$$ with the value $$$a_i - 1$$$ ($$$1 \le i \le n$$$). If $$$a_i$$$ was $$$0$$$, its value does not change. Determine whether Kristina can get an array $$$b$$$ from an array $$$a$$$ in some number of operations (probably zero). In other words, can she make $$$a_i = b_i$$$ after some number of operations for each $$$1 \le i \le n$$$?For example, let $$$n = 4$$$, $$$a = [3, 5, 4, 1]$$$ and $$$b = [1, 3, 2, 0]$$$. In this case, she can apply the operation twice:   after the first application of the operation she gets $$$a = [2, 4, 3, 0]$$$;  after the second use of the operation she gets $$$a = [1, 3, 2, 0]$$$. Thus, in two operations, she can get an array $$$b$$$ from an array $$$a$$$.

int solution() {
  int a[50000];
  int b[50000];
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    for (int i = 0; i < n; i++) {
      scanf("%d", &b[i]);
    }
    int max = 0;
    for (int i = 0; i < n; i++) {
      int c = a[i] - b[i];
      max = max > c ? max : c;
    }
    int flag = 0;
    for (int i = 0; i < n; i++) {
      if (!flag && a[i] - b[i] != max && b[i] != 0) {
        printf("NO\n");
        flag = 1;
      }
    }
    if (!flag) {
      printf("YES\n");
    }
  }
}

fn solution() {
    let mut num = String::new();
    io::stdin().read_line(&mut num).unwrap();
    let num = num.trim().parse::<u32>().unwrap();
    'main: for _ in 0..num {
        let mut _ln: String = String::new();
        io::stdin().read_line(&mut _ln).unwrap();
        let ln: usize = _ln.trim().parse::<u32>().unwrap() as usize;
        let mut ai: String = String::new();
        io::stdin().read_line(&mut ai).unwrap();
        let mut bi: String = String::new();
        io::stdin().read_line(&mut bi).unwrap();
        let a: Vec<u128> = ai
            .split_whitespace()
            .map(|num| num.parse::<u128>().unwrap())
            .collect();
        let b: Vec<u128> = bi
            .split_whitespace()
            .map(|num| num.parse::<u128>().unwrap())
            .collect();
        let mut delta: u128 = 0;
        let mut flag: bool = false;
        for i in 0..ln {
            if a[i] < b[i] {
                println!("NO");
                continue 'main;
            }
            let local_delta: u128 = a[i] - b[i];
            if b[i] == 0 {
                if flag {
                    if local_delta > delta {
                        println!("NO");
                        continue 'main;
                    }
                } else {
                    delta = max(delta, local_delta);
                }
            } else {
                if !flag {
                    flag = true;
                    if local_delta < delta {
                        println!("NO");
                        continue 'main;
                    }
                    delta = local_delta;
                } else {
                    if local_delta != delta {
                        println!("NO");
                        continue 'main;
                    }
                }
            }
        }
        println!("YES");
    }
}