Score : <var>100</var> points

Problem Statement

Takahashi is going to set a <var>3</var>-character password.

How many possible passwords are there if each of its characters must be a digit between <var>1</var> and <var>N</var> (inclusive)?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.

int solution() {

  int N = 0;
  scanf("%d", &N);

  printf("%d\n", N * N * N);

  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to get input");
    let input: u32 = input.trim().parse().expect("failed to parse to u32");
    println!("{}", input * input * input);
}


You are given four integers $$$a$$$, $$$b$$$, $$$x$$$ and $$$y$$$. Initially, $$$a \ge x$$$ and $$$b \ge y$$$. You can do the following operation no more than $$$n$$$ times:  Choose either $$$a$$$ or $$$b$$$ and decrease it by one. However, as a result of this operation, value of $$$a$$$ cannot become less than $$$x$$$, and value of $$$b$$$ cannot become less than $$$y$$$. Your task is to find the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.You have to answer $$$t$$$ independent test cases.

int solution() {
  unsigned long long int a;
  unsigned long long int b;
  unsigned long long int x;
  unsigned long long int y;
  unsigned long long int n;
  unsigned long long int t;
  unsigned counter0 = 0;
  scanf("%llu", &t);
  unsigned long long int arr[t];
  while (counter0 < t) {
    scanf("%llu%llu%llu%llu%llu", &a, &b, &x, &y, &n);

    if (n >= (a - x) + (b - y)) {
      arr[counter0] = x * y;
    }

    else if ((a <= b) && (x <= y)) {
      if (n <= (a - x)) {
        a = a - n;
        arr[counter0] = a * b;
      } else if ((n > (a - x))) {
        b = b - (n - (a - x));
        a = a - (a - x);
        arr[counter0] = a * b;
      }

    }

    else if ((a <= b) && (x >= y)) {
      if (n <= (b - x)) {
        if (n <= (a - x)) {
          a = a - n;
          arr[counter0] = a * b;
        } else {
          b = b - (n - (a - x));
          a = a - (a - x);
          arr[counter0] = a * b;
        }
      } else if (n > (b - x)) {
        if (n <= (b - y)) {
          b = b - n;
          arr[counter0] = a * b;
        } else if (n > (b - y)) {
          a = a - (n - (b - y));
          b = b - (b - y);
          arr[counter0] = a * b;
        }
      }
    }

    else if ((a >= b) && (x <= y)) {
      if (n <= (a - y)) {
        if (n <= (b - y)) {
          b = b - n;
          arr[counter0] = a * b;
        } else if (n > (b - y)) {
          a = a - (n - (b - y));
          b = b - (b - y);
          arr[counter0] = a * b;
        }
      } else if (n > (a - y)) {
        if (n <= (a - x)) {
          a = a - n;
          arr[counter0] = a * b;
        } else if (n > (a - x)) {
          b = b - (n - (a - x));
          a = a - (a - x);
          arr[counter0] = a * b;
        }
      }
    }

    else if ((a >= b) && (x >= y)) {
      if (n <= (b - y)) {
        b = b - n;
        arr[counter0] = a * b;
      } else if (n > (b - y)) {
        a = a - (n - (b - y));
        b = b - (b - y);
        arr[counter0] = a * b;
      }
    }

    counter0++;
  }
  for (counter0 = 0; counter0 < t; counter0++) {
    printf("%llu\n", arr[counter0]);
  }
  return 0;
}

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

    let mut ans = Vec::with_capacity(t);
    for _ in 0..t {
        let (a, b, x, y, n): (i64, i64, i64, i64, i64) = {
            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(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        use std::cmp;
        let res1 = {
            let i = cmp::min(a - x, n);
            let j = cmp::min(b - y, n - i);
            (a - i) * (b - j)
        };
        let res2 = {
            let i = cmp::min(b - y, n);
            let j = cmp::min(a - x, n - i);
            (b - i) * (a - j)
        };
        ans.push(cmp::min(res1, res2));
    }
    println!(
        "{}",
        ans.iter()
            .map(|val| val.to_string())
            .collect::<Vec<_>>()
            .join("\n")
    );
}


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.Let instability of the array be the following value: $$$\max\limits_{i = 1}^{n} a_i - \min\limits_{i = 1}^{n} a_i$$$.You have to remove exactly one element from this array to minimize instability of the resulting $$$(n-1)$$$-elements array. Your task is to calculate the minimum possible instability.

int solution(void) {
  int n = 0;
  scanf("%d\n", &n);

  if (n == 2) {
    printf("0\n");
    return 0;
  }

  int arr[n];

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

  int min1 = 1e9;
  int min2 = 1e9;

  int max1 = -1;
  int max2 = -1;

  for (int j = 0; j < n; j++) {
    if (min1 > arr[j]) {
      min2 = min1;
      min1 = arr[j];
    } else if (min2 > arr[j]) {
      min2 = arr[j];
    }

    if (max2 < arr[j]) {
      max1 = max2;
      max2 = arr[j];
    } else if (max1 < arr[j]) {
      max1 = arr[j];
    }
  }

  printf("%d\n", ((max1 - min1) > (max2 - min2) ? max2 - min2 : max1 - min1));

  return 0;
}

fn solution() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();

    let n = get!(usize);

    if n == 2 {
        println!("0");
        return;
    }

    let mut xs = vec![];
    for _ in 0..n {
        xs.push(get!());
    }
    xs.sort();

    let ans = min(xs[n - 1] - xs[1], xs[n - 2] - xs[0]);

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


Score : <var>200</var> points

Problem Statement

Takahashi is competing in a sumo tournament.
The tournament lasts for <var>15</var> days, during which he performs in one match per day.
If he wins <var>8</var> or more matches, he can also participate in the next tournament.

The matches for the first <var>k</var> days have finished.
You are given the results of Takahashi's matches as a string <var>S</var> consisting of o and x.
If the <var>i</var>-th character in <var>S</var> is o, it means that Takahashi won the match on the <var>i</var>-th day; if that character is x, it means that Takahashi lost the match on the <var>i</var>-th day.

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO if there is no such possibility.

Constraints

<var>1 \leq k \leq 15</var>

<var>S</var> is a string of length <var>k</var> consisting of o and x.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO otherwise.

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

Takahashi has <var>7</var> wins and <var>7</var> losses before the last match. If he wins that match, he will have <var>8</var> wins.

Sample Input 2

xxxxxxxx

Sample Output 2

NO

int solution(void) {
  int cnt = 15;
  int s = 0;
  char i;
  char *mes = "YES";
  while (1) {
    scanf("%c", &i);
    if (i == '\n') {
      break;
    }
    if (i == 'o') {
      s++;
    }
    cnt--;
  }
  if (cnt + s < 8) {
    mes = "NO";
  }
  printf("%s\n", mes);
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let chars: Vec<char> = buf.trim().chars().collect();

    let mut lose_cnt = 0;
    for c in chars.iter() {
        if *c == 'x' {
            lose_cnt += 1;
        }
    }

    println!("{}", if lose_cnt >= 8 { "NO" } else { "YES" });
}


Score : <var>100</var> points

Problem Statement

Ringo is giving a present to Snuke.

Ringo has found out that Snuke loves yakiniku (a Japanese term meaning grilled meat. yaki: grilled, niku: meat). He supposes that Snuke likes grilled things starting with YAKI in Japanese, and does not like other things.

You are given a string <var>S</var> representing the Japanese name of Ringo's present to Snuke. Determine whether <var>S</var> starts with YAKI.

Constraints

<var>1 \leq |S| \leq 10</var>

<var>S</var> consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> starts with YAKI, print Yes; otherwise, print No.

Sample Input 1

YAKINIKU

Sample Output 1

Yes

YAKINIKU starts with YAKI.

Sample Input 2

TAKOYAKI

Sample Output 2

No

TAKOYAKI (a Japanese snack. tako: octopus) does not start with YAKI.

Sample Input 3

YAK

Sample Output 3

No

int solution(void) {
  char po[114];
  scanf("%s", po);
  if (strlen(po) >= 4 && po[0] == 'Y' && po[1] == 'A' && po[2] == 'K' &&
      po[3] == 'I') {
    printf("Yes");
  } else {
    printf("No");
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    if s.chars().take(4).collect::<String>() == "YAKI" {
        println!("Yes");
    } else {
        println!("No");
    }
}


You are given an array $$$a[0 \dots n-1]$$$ of $$$n$$$ integers. This array is called a "valley" if there exists exactly one subarray $$$a[l \dots r]$$$ such that:  $$$0 \le l \le r \le n-1$$$,  $$$a_l = a_{l+1} = a_{l+2} = \dots = a_r$$$,  $$$l = 0$$$ or $$$a_{l-1} > a_{l}$$$,  $$$r = n-1$$$ or $$$a_r < a_{r+1}$$$. Here are three examples:  The first image shows the array [$$$3, 2, 2, 1, 2, 2, 3$$$], it is a valley because only subarray with indices $$$l=r=3$$$ satisfies the condition.The second image shows the array [$$$1, 1, 1, 2, 3, 3, 4, 5, 6, 6, 6$$$], it is a valley because only subarray with indices $$$l=0, r=2$$$ satisfies the codition.The third image shows the array [$$$1, 2, 3, 4, 3, 2, 1$$$], it is not a valley because two subarrays $$$l=r=0$$$ and $$$l=r=6$$$ that satisfy the condition.You are asked whether the given array is a valley or not.Note that we consider the array to be indexed from $$$0$$$.

fn solution() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());

    let t = scan.token::<usize>();

    for _k in 0..t {
        let n = scan.token::<usize>();

        let mut A = vec![];
        for _i in 0..n {
            let a = scan.token::<usize>();
            A.push(a);
        }

        let mut left_side_is_ok = true;
        let mut cnt = 0;

        for i in 0..n {
            if i == n - 1 {
                if left_side_is_ok {
                    cnt += 1;
                }
            } else if A[i] < A[i + 1] {
                if left_side_is_ok {
                    cnt += 1;
                    left_side_is_ok = false;
                } else {
                    left_side_is_ok = false;
                }
            } else if A[i] == A[i + 1] {
            } else if A[i] > A[i + 1] {
                left_side_is_ok = true;
            }
        }

        if cnt == 1 {
            writeln!(out, "YES");
        } else {
            writeln!(out, "NO");
        }
    }
}


Score : <var>300</var> points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up <var>M</var> cans of energy drinks.

There are <var>N</var> stores that sell energy drinks. In the <var>i</var>-th store, he can buy at most <var>B_i</var> cans of energy drinks for <var>A_i</var> yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy <var>M</var> cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy <var>M</var> cans of energy drinks.

Constraints

All values in input are integers.

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

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

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

<var>B_1 + ... + B_N \geq M</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>B_1</var>
<var>A_2</var> <var>B_2</var>
<var>\vdots</var>
<var>A_N</var> <var>B_N</var>

Output

Print the minimum amount of money with which Takahashi can buy <var>M</var> cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With <var>12</var> yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy <var>5</var> drinks with <var>11</var> yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a <var>32</var>-bit integer type.

int solution(void) {
  long long int n;
  long long int m;
  long long int i;
  long long int kei = 0;
  long long int a[100000];
  long long int b[100000];
  scanf("%lld %lld", &n, &m);
  for (i = 0; i < n; i++) {
    scanf("%lld %lld", &a[i], &b[i]);
  }

  int j;
  int increment;
  int temp;
  int temp_b;
  increment = 4;
  int array_size = n;
  while (increment > 0) {
    for (i = 0; i < array_size; i++) {
      j = i;
      temp = a[i];
      temp_b = b[i];
      while ((j >= increment) && (a[j - increment] > temp)) {
        a[j] = a[j - increment];
        b[j] = b[j - increment];
        j = j - increment;
      }
      a[j] = temp;
      b[j] = temp_b;
    }
    if (increment / 2 != 0) {
      increment = increment / 2;
    } else if (increment == 1) {
      increment = 0;
    } else {
      increment = 1;
    }
  }
  for (i = 0; i < n; i++) {
    if (m >= b[i]) {
      kei = (a[i] * b[i]) + kei;
    } else if (m == 0) {
      break;
    } else {
      kei = kei + (a[i] * m);
      break;
    }
    m = m - b[i];
  }
  printf("%lld", kei);
  return 0;
}

fn solution() {
    let mut nm = String::new();
    stdin().read_line(&mut nm).unwrap();
    let nm: Vec<usize> = nm.split_whitespace().flat_map(str::parse).collect();
    let (n, m) = (nm[0], nm[1]);
    let mut stores: Vec<(usize, usize)> = (0..n)
        .map(|_| {
            let mut a = String::new();
            stdin().read_line(&mut a).unwrap();
            let a: Vec<usize> = a.split_whitespace().flat_map(str::parse).collect();
            (a[0], a[1])
        })
        .collect();
    stores.sort();
    let mut count = m;
    let mut result = 0;
    for (yen, stock) in stores {
        let needs = if stock > count { count } else { stock };
        count -= needs;
        result += yen * needs;
        if count == 0 {
            break;
        }
    }
    println!("{}", result);
}


T is playing a game with his friend, HL.There are $$$n$$$ piles of stones, the $$$i$$$-th pile initially has $$$a_i$$$ stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in the previous turn (the pile that was chosen by the other player, or if the current turn is the first turn then the player can choose any non-empty pile). The player who cannot choose a pile in his turn loses, and the game ends.Assuming both players play optimally, given the starting configuration of $$$t$$$ games, determine the winner of each game.

int solution() {
  int t;
  scanf("%d", &t);
  int n;
  int i;
  int j;
  int b;
  int max;
  int a[102];
  for (; t > 0; t--) {
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    max = 0;
    for (i = 0; i < n; i++) {
      if (a[i] > a[max]) {
        max = i;
      }
    }
    a[max]--;
    b = max;
    for (j = 1;; j++) {
      max = -1;
      for (i = 0; i < n; i++) {
        if (i != b && a[i] > 0) {
          if (max < 0) {
            max = i;
          } else if (a[i] > a[max]) {
            max = i;
          }
        }
      }
      if (max < 0) {
        break;
      }
      b = max;
      a[b]--;
    }
    if (j % 2 > 0) {
      printf("T\n");
    } else {
      printf("HL\n");
    }
  }
  return 0;
}

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<i32> = {
            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 max = *a.iter().max().unwrap();
        let sum = a.iter().sum::<i32>();
        if max > sum / 2 || sum % 2 == 1 {
            println!("T");
        } else {
            println!("HL");
        }
    }
}


Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?

int solution() {
  long n;
  long m = 1000000000;
  long k;
  long long t = 0;
  int c = 0;
  scanf("%ld %ld", &n, &k);
  long a[n];
  long r[n];
  for (long i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
    if (a[i] < m) {
      m = a[i];
    }
  }
  for (long i = 0; i < n; i++) {
    r[i] = a[i] - m;
    if (r[i] % k == 0) {
      t = t + (r[i] / k);
    } else {
      c = 1;
      break;
    }
  }
  if (c == 1) {
    printf("%d", -1);
  } else {
    printf("%lld", t);
  }
  return 0;
}

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

    io::stdin().read_line(&mut line).expect("read error");

    let tmp: Vec<&str> = line.split_whitespace().collect();

    let _n = tmp[0].parse::<i32>().expect("parse error");
    let k = tmp[1].parse::<i32>().expect("parse error");

    let mut line2 = String::new();

    io::stdin().read_line(&mut line2).expect("read error");

    let mut a: Vec<i32> = line2
        .split_whitespace()
        .map(|x| x.parse::<i32>().expect("parse error"))
        .collect::<Vec<i32>>();

    a.sort();

    let mut ans: i64 = 0;
    let mut flag = false;

    for x in &a {
        let mut diff = *x - a[0];
        if diff % k != 0 {
            flag = true;
            break;
        }
        diff /= k;
        let tmp = diff as i64;
        ans += tmp;
    }

    if flag {
        println!("-1");
    } else {
        println!("{}", ans);
    }
}


Score : <var>400</var> points

Problem Statement

For an integer <var>N</var>, we will choose a permutation <var>\{P_1, P_2, ..., P_N\}</var> of <var>\{1, 2, ..., N\}</var>.

Then, for each <var>i=1,2,...,N</var>, let <var>M_i</var> be the remainder when <var>i</var> is divided by <var>P_i</var>.

Find the maximum possible value of <var>M_1 + M_2 + \cdots + M_N</var>.

Constraints

<var>N</var> is an integer satisfying <var>1 \leq N \leq 10^9</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the maximum possible value of <var>M_1 + M_2 + \cdots + M_N</var>.

Sample Input 1

2

Sample Output 1

1

When the permutation <var>\{P_1, P_2\} = \{2, 1\}</var> is chosen, <var>M_1 + M_2 = 1 + 0 = 1</var>.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0

int solution() {
  long long n = 0;
  long long result = 0;
  scanf("%lld", &n);
  result = n * (n - 1) / 2;
  printf("%lld", result);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.lock().read_line(&mut input).expect("read line!");
    let input: String = input;
    let n: u64 = input.trim().parse().unwrap();
    println!("{}", (n * (n - 1)) / 2);
}


Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.

int solution(void) {
  int n = 0;
  int num = 0;
  int cnt = 0;
  int top = -1;
  int target = 1;
  char cmd[20] = {
      0,
  };
  int stack[300001] = {
      0,
  };

  scanf("%d", &n);
  n *= 2;

  while (n--) {
    scanf("%s", cmd);
    if (cmd[0] == 'a') {
      scanf("%d", &num);
      stack[++top] = num;
    } else {
      if (top >= 0) {
        if (stack[top] != target) {
          top = -1;
          cnt++;
        } else {
          top--;
        }
      }

      target++;
    }
  }

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

  return 0;
}

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

    let mut stack: Vec<u32> = Vec::with_capacity(n as usize);
    let mut ans = 0;
    let mut counter = 1;

    for _ in 0..(2 * n) {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        let input: Vec<_> = input.split_whitespace().collect();
        if input.len() == 2 {
            let k = input.last().unwrap().parse::<u32>().unwrap();

            stack.push(k);
        } else {
            match stack.pop() {
                Some(p) if p != counter => {
                    stack.clear();
                    ans += 1;
                }
                _ => (),
            }
            counter += 1;
        }
    }

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


Score : <var>200</var> points

Problem Statement

There are <var>N</var> apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from <var>1</var> through <var>N</var> to the trees. An inspector deployed under the <var>i</var>-th tree <var>(1 \leq i \leq N)</var> will inspect the trees with numbers between <var>i-D</var> and <var>i+D</var> (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

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

<var>1 \leq D \leq 20</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>D</var>

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree <var>3</var> and Tree <var>4</var>.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3

int solution() {
  int N = 0;
  int D = 0;
  int c = 0;
  scanf("%d %d", &N, &D);
  while (N > 0) {
    N = N - (2 * D + 1);
    c++;
  }
  printf("%d\n", c);

  return 0;
}

fn solution() {
    let mut nd = String::new();
    stdin().read_line(&mut nd).unwrap();
    let nd: Vec<usize> = nd.split_whitespace().flat_map(str::parse).collect();
    let (n, d) = (nd[0], nd[1]);

    println!(
        "{}",
        (n / (2 * d + 1)) + if n % (2 * d + 1) > 0 { 1 } else { 0 }
    );
}


Naive String Search

  Find places where a string <var>P</var> is found within a text <var>T</var>.

  Print all indices of <var>T</var> where <var>P</var> found. The indices of <var>T</var> start with 0.

Input

  In the first line, a text <var>T</var> is given. In the second line, a string <var>P</var> is given.

output

  Print an index of <var>T</var> where <var>P</var> found in a line. Print the indices in ascending order.

Constraints

 1 ≤ length of <var>T</var> ≤ 1000

 1 ≤ length of <var>P</var> ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output3

The ouput should be empty.

fn solution() {
    let mut read = String::new();
    std::io::stdin().read_line(&mut read).expect("");
    let mut s = read.clone();
    s = s.trim().to_string();
    read = String::new();
    std::io::stdin().read_line(&mut read).expect("");
    let f = read.trim();
    if f.len() > s.len() {
        std::process::exit(0);
    }
    for i in 0..(s.len() - f.len() + 1) {
        if &s[i..i + f.len()] == f {
            println!("{}", i);
        }
    }
}


Score : <var>300</var> points

Problem Statement

Takahashi has <var>N</var> balls. Initially, an integer <var>A_i</var> is written on the <var>i</var>-th ball.

He would like to rewrite the integer on some balls so that there are at most <var>K</var> different integers written on the <var>N</var> balls.

Find the minimum number of balls that Takahashi needs to rewrite the integers on them.

Constraints

<var>1 \leq K \leq N \leq 200000</var>

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

All input values are integers.

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>A_N</var>

Output

Print the minimum number of balls that Takahashi needs to rewrite the integers on them.

Sample Input 1

5 2
1 1 2 2 5

Sample Output 1

1

For example, if we rewrite the integer on the fifth ball to <var>2</var>, there are two different integers written on the balls: <var>1</var> and <var>2</var>.
On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print <var>1</var>.

Sample Input 2

4 4
1 1 2 2

Sample Output 2

0

Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.

Sample Input 3

10 3
5 1 3 2 4 1 1 2 3 4

Sample Output 3

3

int solution() {
  int N;
  int K;
  int i;
  int tmp;
  int count = 0;
  int ans = 0;

  scanf("%d %d", &N, &K);

  int A[N + 1];
  int d[N + 1];
  for (i = 0; i <= N; i++) {
    A[i] = 0;
    d[i] = 0;
  }
  for (i = 0; i < N; i++) {
    scanf("%d", &tmp);
    A[tmp]++;
  }

  for (i = 0; i <= N; i++) {
    d[A[i]]++;
  }

  for (i = N; i > 0; i--) {
    if (count >= K) {
      ans += i * d[i];
    } else if (count + d[i] > K) {
      ans += i * (count + d[i] - K);
    }
    count += d[i];
  }

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

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut stdin = stdin.lock();
    stdin.read_until(b' ', &mut Vec::new()).unwrap();
    let mut k = String::new();
    stdin.read_line(&mut k).unwrap();
    let k: usize = k.trim_end().parse().unwrap();

    let mut amt: Vec<u32> = stdin
        .split(b' ')
        .map(|r| {
            String::from_utf8(r.unwrap())
                .unwrap()
                .trim_end()
                .parse::<u32>()
                .unwrap()
        })
        .fold(HashMap::with_capacity(200_000), |mut map, a| {
            *map.entry(a).or_insert(0) += 1;
            map
        })
        .values()
        .cloned()
        .collect();

    amt.sort();
    println!(
        "{}",
        amt.iter().take(amt.len().saturating_sub(k)).sum::<u32>()
    );
}


Moamen has an array of $$$n$$$ distinct integers. He wants to sort that array in non-decreasing order by doing the following operations in order exactly once:  Split the array into exactly $$$k$$$ non-empty subarrays such that each element belongs to exactly one subarray.  Reorder these subarrays arbitrary.  Merge the subarrays in their new order. A sequence $$$a$$$ is a subarray of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Can you tell Moamen if there is a way to sort the array in non-decreasing order using the operations written above?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int k;
    int c = 0;
    int i;
    int j;
    scanf("%d %d", &n, &k);
    long ara[n];
    long p;
    for (i = 0; i < n; i++) {
      scanf("%ld", &ara[i]);
    }
    for (i = 0; i < n; i++) {
      if (ara[i] < p || i == 0) {
        c++;
      } else if ((ara[i] - p) == 1) {
        p = ara[i];
        continue;
      } else {
        for (j = 0; j < n; j++) {
          if (ara[j] > p && ara[j] < ara[i]) {
            c++;
            break;
          }
        }
      }
      p = ara[i];
    }
    if (c <= k) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() -> Result<(), Box<dyn Error>> {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    let t: i32 = lines.next().unwrap()?.parse()?;
    for _ in 0..t {
        let (_, mut k): (i32, i32) = {
            let line = lines.next().unwrap()?;
            let mut lines = line.split(" ").map(|s| s.parse());
            (lines.next().unwrap()?, lines.next().unwrap()?)
        };
        let mut a: Vec<(i32, usize)> = lines
            .next()
            .unwrap()?
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .enumerate()
            .map(|s| (s.1, s.0))
            .collect();
        let b: HashMap<i32, usize> = a.clone().into_iter().collect();
        a.sort_by_key(|k| k.0);

        let mut row_prev: Option<usize> = None;
        for (v, i) in a {
            let j = b[&v];
            if let Some(rp) = &row_prev
                && rp + 1 != j {
                    row_prev = None;
                    k -= 1;
                }
            row_prev = Some(i);
        }

        if k > 0 {
            println!("Yes");
        } else {
            println!("No");
        }
    }
    Ok(())
}


In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

int solution() {
  int n = 0;
  int a[100];
  int s = 0;
  int max = 0;
  int i = 0;
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  for (i = 0; i < n; i++) {
    if (max < a[i]) {
      max = a[i];
    }
  }
  for (i = 0; i < n; i++) {
    s += max - a[i];
  }
  printf("%d", s);

  return 0;
}

fn solution() {
    io::stdin().read_line(&mut String::new()).unwrap();

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

    let mut max_welfare = 0;
    let mut total_welfare = 0;
    let mut population = 0;

    for welfare in welfare_input.split_whitespace().map(|x| x.parse().unwrap()) {
        total_welfare += welfare;
        max_welfare = cmp::max(max_welfare, welfare);
        population += 1;
    }

    println!("{}", population * max_welfare - total_welfare);
}


International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

int solution() {
  int n;
  int k;
  int res = 0;
  int res2 = 0;
  scanf("%d %d", &n, &k);
  int d;
  int mods[101];
  for (int i = 0; i < 101; i++) {
    mods[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &d);
    if (d % k == 0) {
      res++;
    } else {
      mods[d % k]++;
    }
  }

  for (int i = 1; i < 101; i++) {

    if (mods[i] != 0 && mods[k - i] != 0) {
      if (i == k - i) {
        res2 += (mods[i] / 2) * 2;
        continue;
      }
      if (mods[i] < mods[k - i]) {
        res2 += mods[i] * 2;
        mods[i] = 0;
        mods[k - i] = 0;
      } else {
        res2 += mods[k - i] * 2;
        mods[i] = 0;
        mods[k - i] = 0;
      }
    }
  }

  printf("%d", ((res / 2) * 2) + res2);

  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let mut l1 = String::new();
    let mut l2 = String::new();
    stdin.read_line(&mut l1).unwrap();
    stdin.read_line(&mut l2).unwrap();
    let v1: Vec<i32> = l1.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let d: Vec<i32> = l2.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let k = v1[1] as usize;

    let mut group_count = vec![0i32; k];
    for x in &d {
        let g = (*x % k as i32) as usize;

        group_count[g] += 1;
    }

    let ans: i32 = (0..k)
        .map(|i| {
            if i == k - i || i == 0 {
                group_count[i] - group_count[i] % 2
            } else {
                std::cmp::min(group_count[i], group_count[k - i])
            }
        })
        .sum();

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


Score : <var>300</var> points

Problem Statement

A company has <var>N</var> members, who are assigned ID numbers <var>1, ..., N</var>.

Every member, except the member numbered <var>1</var>, has exactly one immediate boss with a smaller ID number.

When a person <var>X</var> is the immediate boss of a person <var>Y</var>, the person <var>Y</var> is said to be an immediate subordinate of the person <var>X</var>.

You are given the information that the immediate boss of the member numbered <var>i</var> is the member numbered <var>A_i</var>. For each member, find how many immediate subordinates it has.

Constraints

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

<var>1 \leq A_i < i</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_2</var> <var>...</var> <var>A_N</var>

Output

For each of the members numbered <var>1, 2, ..., N</var>, print the number of immediate subordinates it has, in its own line.

Sample Input 1

5
1 1 2 2

Sample Output 1

2
2
0
0
0

The member numbered <var>1</var> has two immediate subordinates: the members numbered <var>2</var> and <var>3</var>.

The member numbered <var>2</var> has two immediate subordinates: the members numbered <var>4</var> and <var>5</var>.

The members numbered <var>3</var>, <var>4</var>, and <var>5</var> do not have immediate subordinates.

Sample Input 2

10
1 1 1 1 1 1 1 1 1

Sample Output 2

9
0
0
0
0
0
0
0
0
0

Sample Input 3

7
1 2 3 4 5 6

Sample Output 3

1
1
1
1
1
1
0

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

    std::io::stdin().read_to_string(&mut buf).unwrap();

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let a: Vec<usize> = (0..n - 1)
        .map(|_| iter.next().unwrap().parse().unwrap())
        .collect();
    let mut ans = vec![0; n];

    for x in a {
        ans[x - 1] += 1;
    }

    println!(
        "{}",
        ans.into_iter()
            .map(|v| v.to_string())
            .collect::<Vec<_>>()
            .join("\n")
    );
}


NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $$$\operatorname{or} z$$$. Can you solve this problem too?You are given a 1-indexed array of $$$n$$$ integers, $$$a$$$, and an integer $$$z$$$. You can do the following operation any number (possibly zero) of times:  Select a positive integer $$$i$$$ such that $$$1\le i\le n$$$. Then, simutaneously set $$$a_i$$$ to $$$(a_i\operatorname{or} z)$$$ and set $$$z$$$ to $$$(a_i\operatorname{and} z)$$$. In other words, let $$$x$$$ and $$$y$$$ respectively be the current values of $$$a_i$$$ and $$$z$$$. Then set $$$a_i$$$ to $$$(x\operatorname{or}y)$$$ and set $$$z$$$ to $$$(x\operatorname{and}y)$$$. Here $$$\operatorname{or}$$$ and $$$\operatorname{and}$$$ denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in $$$a$$$ after any number (possibly zero) of operations.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int z;
    scanf("%d %d", &n, &z);
    int a[n + 10];
    int p[(2 * n) + 10];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      p[i] = z | a[i];
    }
    int max = p[0];
    for (int i = 0; i < n; i++) {
      if (max < p[i]) {
        max = p[i];
      }
    }
    printf("%d\n", max);
  }
}

fn solution() {
    input! {
        name = cf,
        t: usize
    }
    for _ in 0..t {
        input! {
            use cf,
            n: usize,
            z: u32,
            a: [u32; n]
        }
        let ans = a.iter().map(|a| z | a).max().unwrap();
        println!("{}", ans);
    }
}


CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example:  Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example:  $$$7 \mod 3=1$$$, because $$$7 = 3 \cdot 2 + 1$$$,  $$$15 \mod 4=3$$$, because $$$15 = 4 \cdot 3 + 3$$$.

int solution() {
  int test;
  scanf("%d", &test);
  while (test--) {
    int num;
    scanf("%d", &num);
    long long int fact = 1;
    for (int i = 3; i <= 2 * num; i++) {
      fact = (fact * i) % 1000000007;
    }
    printf("%lld\n", fact);
  }
  return 0;
}

fn solution() {
    let mut t = String::new();
    std::io::stdin().read_line(&mut t).expect("");
    let t: i32 = t.trim().parse().expect("");

    for _x in 0..t {
        let mut n = String::new();
        std::io::stdin().read_line(&mut n).expect("");
        let n: u128 = n.trim().parse().expect("");
        let mut result: u128 = 1;
        for x in 3..((2 * n) + 1) {
            result = result * x % 1000000007;
        }
        println!("{}", result);
    }
}


Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.For example, Zookeeper can use two such operations: AABABBA $$$\to$$$ AABBA $$$\to$$$ AAA.Zookeeper wonders what the shortest string he can make is. Can you help him find the length of the shortest string?

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let test: i32 = str.trim().parse().unwrap();
    for _ in 0..test {
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        let s: Vec<char> = str.trim().chars().collect();
        let mut d = 0;
        let mut last = 0;
        for i in s {
            if d == 0 {
                d = 1;
                if i == 'A' {
                    last = 1;
                } else {
                    last = 0;
                }
            } else {
                if i == 'A' {
                    last += 1;
                    d += 1;
                } else {
                    if last > 0 {
                        last -= 1;
                        d -= 1;
                    } else if d > 0 {
                        d -= 1;
                    } else {
                        d = 1;
                    }
                }
            }
        }
        println!("{}", d);
    }
}


You are given a range of positive integers from $$$l$$$ to $$$r$$$.Find such a pair of integers $$$(x, y)$$$ that $$$l \le x, y \le r$$$, $$$x \ne y$$$ and $$$x$$$ divides $$$y$$$.If there are multiple answers, print any of them.You are also asked to answer $$$T$$$ independent queries.

int solution() {
  int a;
  int b;
  scanf("%d", &a);
  while (a--) {
    scanf("%d %*d", &b);
    printf("%d %d\n", b, 2 * b);
  }
  return 0;
}

fn solution() {
    let mut tt = String::new();
    stdin().read_line(&mut tt).ok();
    let t: u32 = tt.trim().parse().unwrap();
    for _i in 0..t {
        let mut lrs = String::new();
        stdin().read_line(&mut lrs).ok();
        let lr: Vec<u32> = lrs.split_whitespace().map(|x| x.parse().unwrap()).collect();
        if lr[0] * 2 <= lr[1] {
            println!("{} {}", lr[0], lr[0] * 2);
        } else {
            println!("1 1");
        }
    }
}


The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:  The query to swap two table rows;  The query to swap two table columns;  The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.

int solution() {
  int i;
  int j;
  int swaptmp;
  int n;
  int m;
  int k;
  char s[2];
  int p[1005][1005];
  int indexx[1005];
  int indexy[1005];
  scanf("%d%d%d", &n, &m, &k);
  for (i = 0; i < n; i++) {
    indexx[i] = i;
  }
  for (i = 0; i < m; i++) {
    indexy[i] = i;
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      scanf("%d", &p[i][j]);
    }
  }
  while (k--) {
    scanf("%s%d%d", s, &i, &j);
    i -= 1;
    j -= 1;
    if (s[0] == 'c') {
      swaptmp = indexy[i];
      indexy[i] = indexy[j];
      indexy[j] = swaptmp;
    } else if (s[0] == 'r') {
      swaptmp = indexx[i];
      indexx[i] = indexx[j];
      indexx[j] = swaptmp;
    } else {
      printf("%d\n", p[indexx[i]][indexy[j]]);
    }
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let stdout = io::stdout();
    let stdin_lock = stdin.lock();
    let mut lines = stdin_lock.lines();
    let mut stdout_lock = BufWriter::new(stdout.lock());
    let (n, m, k) = {
        let tmp: Vec<_> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().ok().unwrap())
            .collect();
        (tmp[0], tmp[1], tmp[2])
    };
    let a: Vec<Vec<usize>> = (0..n)
        .map(|_| {
            lines
                .next()
                .unwrap()
                .unwrap()
                .split(' ')
                .map(|x| x.parse().ok().unwrap())
                .collect()
        })
        .collect();
    let mut ii: Vec<_> = (0..n).collect();
    let mut jj: Vec<_> = (0..m).collect();
    (0..k).for_each(|_| {
        let (c, x, y): (_, usize, usize) = {
            let line = lines.next().unwrap().unwrap();
            let tmp: Vec<_> = line.split(' ').collect();
            (
                tmp[0].parse().ok().unwrap(),
                tmp[1].parse().ok().unwrap(),
                tmp[2].parse().ok().unwrap(),
            )
        };

        match c {
            'r' => {
                ii.swap(x - 1, y - 1);
            }
            'c' => {
                jj.swap(x - 1, y - 1);
            }
            _ => {
                writeln!(stdout_lock, "{}", a[ii[x - 1]][jj[y - 1]]);
            }
        }
    });
}


The title is a reference to the very first Educational Round from our writers team, Educational Round 18.There is a bag, containing colored balls. There are $$$n$$$ different colors of balls, numbered from $$$1$$$ to $$$n$$$. There are $$$\mathit{cnt}_i$$$ balls of color $$$i$$$ in the bag. The total amount of balls in the bag is odd (e. g. $$$\mathit{cnt}_1 + \mathit{cnt}_2 + \dots + \mathit{cnt}_n$$$ is odd).In one move, you can choose two balls with different colors and take them out of the bag.At some point, all the remaining balls in the bag will have the same color. That's when you can't make moves anymore.Find any possible color of the remaining balls.

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    scanf("%d", &n);
    int cnt[n];
    for (int j = 0; j < n; j++) {
      scanf("%d", &cnt[j]);
    }

    int a = 0;
    int b = 1;
    while (a < n && b < n) {
      cnt[a]--;
      cnt[b]--;
      while (cnt[a] == 0) {
        a++;
      }
      while (cnt[b] == 0 || a == b) {
        b++;
      }
    }

    for (int j = 0; j < n; j++) {
      if (cnt[j]) {
        printf("%d\n", j + 1);
      }
    }
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut num = String::new();
    stdin.read_line(&mut num).expect("Failed to parse line");
    let num: i32 = num.trim().parse().expect("Please type a number!");
    for _ in 0..num {
        let mut num2 = String::new();
        stdin.read_line(&mut num2).expect("Failed to parse line");
        let mut line = String::new();
        stdin.read_line(&mut line).expect("Failed to parse line");
        let balls: Vec<Balls> = line
            .split(" ")
            .map(|s| s.trim().parse().unwrap())
            .enumerate()
            .map(|(idx, n)| Balls { idx, count: n })
            .collect();

        if balls.len() < 2 {
            println!("{}", 1);
            continue;
        }

        let mut numbers: Vec<Balls> = balls;
        loop {
            numbers = numbers
                .iter()
                .map(|balls| Balls {
                    idx: balls.idx,
                    count: balls.count - 1,
                })
                .filter(|balls| balls.count > 0)
                .collect();
            if numbers.is_empty() {
                println!("{}", 1);
                break;
            }
            if numbers.len() == 1 {
                println!("{}", numbers[0].idx + 1);
                break;
            }
        }
    }
}


There are $$$n$$$ people who want to participate in a boat competition. The weight of the $$$i$$$-th participant is $$$w_i$$$. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.So, if there are $$$k$$$ teams $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, $$$\dots$$$, $$$(a_k, b_k)$$$, where $$$a_i$$$ is the weight of the first participant of the $$$i$$$-th team and $$$b_i$$$ is the weight of the second participant of the $$$i$$$-th team, then the condition $$$a_1 + b_1 = a_2 + b_2 = \dots = a_k + b_k = s$$$, where $$$s$$$ is the total weight of each team, should be satisfied.Your task is to choose such $$$s$$$ that the number of teams people can create is the maximum possible. Note that each participant can be in no more than one team.You have to answer $$$t$$$ independent test cases.

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 w: Vec<usize> = {
            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 c: Vec<usize> = vec![0; 100];
        for i in 0..n {
            c[w[i]] += 1;
        }

        let mut ans = 0;
        for s in 2..=100 {
            let mut res = 0;
            for x in 1..s {
                res += cmp::min(c[x], c[s - x]);
            }
            ans = cmp::max(ans, res / 2);
        }
        println!("{}", ans);
    }
}


You are given integer $$$n$$$. You have to arrange numbers from $$$1$$$ to $$$2n$$$, using each of them exactly once, on the circle, so that the following condition would be satisfied:For every $$$n$$$ consecutive numbers on the circle write their sum on the blackboard. Then any two of written on the blackboard $$$2n$$$ numbers differ not more than by $$$1$$$.For example, choose $$$n = 3$$$. On the left you can see an example of a valid arrangement: $$$1 + 4 + 5 = 10$$$, $$$4 + 5 + 2 = 11$$$, $$$5 + 2 + 3 = 10$$$, $$$2 + 3 + 6 = 11$$$, $$$3 + 6 + 1 = 10$$$, $$$6 + 1 + 4 = 11$$$, any two numbers differ by at most $$$1$$$. On the right you can see an invalid arrangement: for example, $$$5 + 1 + 6 = 12$$$, and $$$3 + 2 + 4 = 9$$$, $$$9$$$ and $$$12$$$ differ more than by $$$1$$$.

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let n = input.trim().parse::<usize>().unwrap();

    if n % 2 == 0 {
        println!("NO");
    } else {
        println!("YES");

        print!("1");
        for i in (4..(2 * n)).step_by(4) {
            print!(" {}", i);
            print!(" {}", i + 1);
        }
        for i in (2..(2 * n)).step_by(4) {
            print!(" {}", i);
            print!(" {}", i + 1);
        }
        println!(" {}", 2 * n);
    }
}


Alice has a grid with $$$2$$$ rows and $$$n$$$ columns. She fully covers the grid using $$$n$$$ dominoes of size $$$1 \times 2$$$ — Alice may place them vertically or horizontally, and each cell should be covered by exactly one domino.Now, she decided to show one row of the grid to Bob. Help Bob and figure out what the other row of the grid looks like!

int solution() {
  int tc = 0;
  scanf("%d", &tc);
  getchar();

  for (int i = 0; i < tc; i++) {
    int n = 0;
    scanf("%d", &n);
    getchar();

    char chars[100] = {0};
    for (int j = 0; j < n; j++) {
      scanf("%c", &chars[j]);
    }
    getchar();

    char result[100] = {0};
    for (int j = 0; j < n; j++) {
      if (chars[j] == 'U') {
        result[j] = 'D';
      } else if (chars[j] == 'D') {
        result[j] = 'U';
      } else {
        result[j] = chars[j];
      }
    }

    for (int j = 0; j < n; j++) {
      printf("%c", result[j]);
    }
    puts("");
  }
}

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 s = l
            .unwrap()
            .chars()
            .map(|c| match c {
                'U' => 'D',
                'D' => 'U',
                _ => c,
            })
            .collect::<String>();
        writeln!(o, "{}", s).ok();
    }
}


Score : <var>300</var> points

Problem Statement

Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is YES or NO.

When he checked the detailed status of the submission, there were <var>N</var> test cases in the problem, and the code received TLE in <var>M</var> of those cases.

Then, he rewrote the code to correctly solve each of those <var>M</var> cases with <var>1/2</var> probability in <var>1900</var> milliseconds, and correctly solve each of the other <var>N-M</var> cases without fail in <var>100</var> milliseconds.

Now, he goes through the following process:

Submit the code.

Wait until the code finishes execution on all the cases.

If the code fails to correctly solve some of the <var>M</var> cases, submit it again.

Repeat until the code correctly solve all the cases in one submission.

Let the expected value of the total execution time of the code be <var>X</var> milliseconds. Print <var>X</var> (as an integer).

Constraints

All input values are integers.

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

<var>1 \leq M \leq {\rm min}(N, 5)</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>

Output

Print <var>X</var>, the expected value of the total execution time of the code, as an integer. It can be proved that, under the constraints in this problem, <var>X</var> is an integer not exceeding <var>10^9</var>.

Sample Input 1

1 1

Sample Output 1

3800

In this input, there is only one case. Takahashi will repeatedly submit the code that correctly solves this case with <var>1/2</var> probability in <var>1900</var> milliseconds.

The code will succeed in one attempt with <var>1/2</var> probability, in two attempts with <var>1/4</var> probability, and in three attempts with <var>1/8</var> probability, and so on.

Thus, the answer is <var>1900 \times 1/2 + (2 \times 1900) \times 1/4 + (3 \times 1900) \times 1/8 + ... = 3800</var>.

Sample Input 2

10 2

Sample Output 2

18400

The code will take <var>1900</var> milliseconds in each of the <var>2</var> cases, and <var>100</var> milliseconds in each of the <var>10-2=8</var> cases. The probability of the code correctly solving all the cases is <var>1/2 \times 1/2 = 1/4</var>.

Sample Input 3

100 5

Sample Output 3

608000

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.trim().split(" ").map(|x| x.parse().unwrap()).collect();
    println!("{}", (100 * (v[0] - v[1]) + 1900 * v[1]) << v[1]);
}


ゼッケンの交換 (Swapping Bibs)

  問題

JOI 高校の N 人の生徒が東西に一列に並んでいる．列の西の端から i 番目の生徒が生徒 i である．それぞれの生徒は整数が 1 つ書かれたゼッケンを付けている．最初，生徒 i のゼッケンには整数 Ai が書かれている．

バトンが M 個あり，バトンには 1 から M までの番号が付けられている．k = 1, 2, ..., M に対し，以下の操作を行う．バトン k (2 ≦ k ≦ M) に関する操作は，バトン k - 1 に関する操作が終わってから行う．

先生がバトン k を生徒 1 に渡す．

バトンを受け取った生徒は，以下のルールに従ってバトンを渡す．

ルール：生徒 i がバトン k を受け取ったとする．

 1 ≦ i ≦ N - 1 のとき: 生徒 i のゼッケンの整数を k で割った余りが，生徒 i + 1 のゼッケンの整数を k で割った余りよりも大きいとき，生徒 i と生徒 i + 1 がゼッケンを交換し，生徒 i は生徒 i + 1 にバトンを渡す．そうでないときは，ゼッケンを交換せずに，生徒 i は生徒 i + 1 にバトンを渡す．

 i = N のとき: 生徒 N はバトンを先生に渡す．

先生が生徒 N からバトン k を受け取ったら，バトン k に関する操作は終わりである．

生徒のゼッケンに最初に書かれていた整数とバトンの個数 M が与えられたとき，先生が生徒 N からバトン M を受け取った後の，それぞれの生徒のゼッケンの整数を求めるプログラムを作成せよ．

  入力

入力は 1 + N 行からなる．

1 行目には整数 N, M (1 ≦ N ≦ 100, 1 ≦ M ≦ 100) が空白を区切りとして書かれており，それぞれ生徒の人数とバトンの個数を表す．

続く N 行のうちの i 行目 (1 ≦ i ≦ N) には整数 Ai (1 ≦ Ai ≦ 1000) が書かれており，生徒 i のゼッケンに最初に書かれている整数 Ai を表す．

  出力

出力は N 行からなる．i 行目 (1 ≦ i ≦ N) には，先生が生徒 N からバトン M を受け取った後の，生徒 i のゼッケンの整数を出力せよ．

  入出力例

入力例 1

6 4
3
2
8
3
1
5

出力例 1

2
3
1
8
5
3

入力例 2

10 6
1
2
3
4
5
6
7
8
9
10

出力例 2

6
1
2
3
10
4
8
7
9
5

入出力例 1 では 6 人の生徒がいる．最初，生徒のゼッケンは順に 3， 2， 8， 3， 1， 5 である．バトンは 4 個ある．

バトン 1 に関する操作が終了した時点での生徒のゼッケンは順に 3， 2， 8， 3， 1， 5 である．

バトン 2 に関する操作が終了した時点での生徒のゼッケンは順に 2， 8， 3， 3， 1， 5 である．

バトン 3 に関する操作が終了した時点での生徒のゼッケンは順に 2， 3， 3， 1， 8， 5 である．

バトン 4 に関する操作が終了した時点での生徒のゼッケンは順に 2， 3， 1， 8， 5， 3 である．

情報オリンピック日本委員会作 『第 15 回日本情報オリンピック JOI 2015/2016 予選競技課題』

int solution(void) {
  int n;
  int m;
  int bib[128] = {0};
  int swh;
  int i;
  int j;
  scanf("%d%d", &n, &m);
  for (i = 1; i <= n; i++) {
    scanf("%d", &bib[i]);
  }
  for (i = 1; i <= m; i++) {
    for (j = 1; j < n; j++) {
      if (bib[j] % i > bib[j + 1] % i) {
        swh = bib[j];
        bib[j] = bib[j + 1];
        bib[j + 1] = swh;
      }
    }
  }
  for (i = 1; i <= n; i++) {
    printf("%d\n", bib[i]);
  }
  return 0;
}

fn solution() {
    let input = {
        let mut buf = vec![];
        stdin().read_to_end(&mut buf);
        unsafe { String::from_utf8_unchecked(buf) }
    };
    let mut lines = input.split('\n');

    let (n, m) = {
        let line = lines.next().unwrap();
        let mut iter = line.split(' ').map(|s| s.parse().unwrap());

        (iter.next().unwrap(), iter.next().unwrap())
    };

    let mut vec = Vec::with_capacity(n);
    vec.extend(lines.take(n).map(|l| l.parse::<usize>().unwrap()));

    for k in 2..(m + 1) {
        for i in 0..(n - 1) {
            if vec[i] % k > vec[i + 1] % k {
                vec.swap(i, i + 1);
            }
        }
    }

    let mut result = String::with_capacity(n * 4);
    for a in vec {
        writeln!(result, "{}", a);
    }
    print!("{}", result);
}


Score : <var>300</var> points

Problem Statement

Joisino is planning to open a shop in a shopping street.

Each of the five weekdays is divided into two periods, the morning and the evening. For each of those ten periods, a shop must be either open during the whole period, or closed during the whole period. Naturally, a shop must be open during at least one of those periods.

There are already <var>N</var> stores in the street, numbered <var>1</var> through <var>N</var>.

You are given information of the business hours of those shops, <var>F_{i,j,k}</var>. If <var>F_{i,j,k}=1</var>, Shop <var>i</var> is open during Period <var>k</var> on Day <var>j</var> (this notation is explained below); if <var>F_{i,j,k}=0</var>, Shop <var>i</var> is closed during that period. Here, the days of the week are denoted as follows. Monday: Day <var>1</var>, Tuesday: Day <var>2</var>, Wednesday: Day <var>3</var>, Thursday: Day <var>4</var>, Friday: Day <var>5</var>. Also, the morning is denoted as Period <var>1</var>, and the afternoon is denoted as Period <var>2</var>.

Let <var>c_i</var> be the number of periods during which both Shop <var>i</var> and Joisino's shop are open. Then, the profit of Joisino's shop will be <var>P_{1,c_1}+P_{2,c_2}+...+P_{N,c_N}</var>.

Find the maximum possible profit of Joisino's shop when she decides whether her shop is open during each period, making sure that it is open during at least one period.

Constraints

<var>1≤N≤100</var>

<var>0≤F_{i,j,k}≤1</var>

For every integer <var>i</var> such that <var>1≤i≤N</var>, there exists at least one pair <var>(j,k)</var> such that <var>F_{i,j,k}=1</var>.

<var>-10^7≤P_{i,j}≤10^7</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>F_{1,1,1}</var> <var>F_{1,1,2}</var> <var>...</var> <var>F_{1,5,1}</var> <var>F_{1,5,2}</var>
<var>:</var>
<var>F_{N,1,1}</var> <var>F_{N,1,2}</var> <var>...</var> <var>F_{N,5,1}</var> <var>F_{N,5,2}</var>
<var>P_{1,0}</var> <var>...</var> <var>P_{1,10}</var>
<var>:</var>
<var>P_{N,0}</var> <var>...</var> <var>P_{N,10}</var>

Output

Print the maximum possible profit of Joisino's shop.

Sample Input 1

1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2

Sample Output 1

8

If her shop is open only during the periods when Shop <var>1</var> is opened, the profit will be <var>8</var>, which is the maximum possible profit.

Sample Input 2

2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1

Sample Output 2

-2

Note that a shop must be open during at least one period, and the profit may be negative.

Sample Input 3

3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7

Sample Output 3

23

fn solution() {
    input! {
        N: usize,
        F: [ [usize; 10]; N],
        P: [ [i64; 11]; N],
    }

    let mut max = std::i64::MIN;
    for ind in 1..(1 << 10) {
        let mut c = vec![0_usize; N];
        let mut res = ind;
        let mut count = 0;
        while res > 0 {
            let is = res & 1;
            for i in 0..N {
                c[i] += F[i][count] * is;
            }
            res >>= 1;
            count += 1;
        }
        let mut sum = 0;
        for (ind, cc) in c.iter().enumerate() {
            sum += P[ind][*cc];
        }
        max = cmp::max(max, sum);
    }
    println!("{}", max);
}


The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts $$$h$$$ hours and each hour lasts $$$m$$$ minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows the number of minutes in decimal; the number of minutes and hours is written with leading zeros if needed to form a two-digit number). Hours are numbered from $$$0$$$ to $$$h-1$$$ and minutes are numbered from $$$0$$$ to $$$m-1$$$.  That's how the digits are displayed on the clock. Please note that digit $$$1$$$ is placed in the middle of its position. A standard mirror is in use on the planet Lapituletti. Inhabitants often look at the reflection of the digital clocks in the mirror and feel happy when what you see on the reflected clocks is a valid time (that means that you see valid digits in the reflection and this time can be seen on the normal clocks at some moment of a day).The image of the clocks in the mirror is reflected against a vertical axis.  The reflection is not a valid time.The reflection is a valid time with $$$h=24$$$, $$$m = 60$$$. However, for example, if $$$h=10$$$, $$$m=60$$$, then the reflection is not a valid time. An inhabitant of the planet Lapituletti begins to look at a mirrored image of the clocks at some time moment $$$s$$$ and wants to know the nearest future time moment (which can possibly happen on the next day), when the reflected clock time is valid.It can be shown that with any $$$h$$$, $$$m$$$, $$$s$$$ such a moment exists. If the reflected time is correct at the moment the inhabitant began to look at the clock, that moment is considered the nearest.You are asked to solve the problem for several test cases.

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

    let mut it = input.split_whitespace();

    let _t = it.next().unwrap();

    let a = [
        Some(0),
        Some(1),
        Some(5),
        None,
        None,
        Some(2),
        None,
        None,
        Some(8),
        None,
    ];

    while let Some(h) = it.next().map(|x| x.parse::<usize>().unwrap()) {
        let m = it.next().map(|x| x.parse::<usize>().unwrap()).unwrap();
        let s = it.next().unwrap();

        let mut it = s.split(':').map(|x| x.parse::<usize>().unwrap());
        let mut h0 = it.next().unwrap();
        let mut m0 = it.next().unwrap();

        loop {
            if let Some(d0) = a[m0 % 10]
                && let Some(d1) = a[m0 / 10]
                    && let Some(d2) = a[h0 % 10]
                        && let Some(d3) = a[h0 / 10] {
                            let h1 = d0 * 10 + d1;
                            let m1 = d2 * 10 + d3;

                            if h1 < h && m1 < m {
                                println!("{:02}:{:02}", h0, m0);
                                break;
                            }
                        }

            m0 += 1;
            if m0 == m {
                m0 = 0;
                h0 += 1;
                if h0 == h {
                    h0 = 0;
                }
            }
        }
    }
}


You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.$$$n$$$ reviewers enter the site one by one. Each reviewer is one of the following types:   type $$$1$$$: a reviewer has watched the movie, and they like it — they press the upvote button;  type $$$2$$$: a reviewer has watched the movie, and they dislike it — they press the downvote button;  type $$$3$$$: a reviewer hasn't watched the movie — they look at the current number of upvotes and downvotes of the movie on the server they are in and decide what button to press. If there are more downvotes than upvotes, then a reviewer downvotes the movie. Otherwise, they upvote the movie. Each reviewer votes on the movie exactly once.Since you have two servers, you can actually manipulate the votes so that your movie gets as many upvotes as possible. When a reviewer enters a site, you know their type, and you can send them either to the first server or to the second one.What is the maximum total number of upvotes you can gather over both servers if you decide which server to send each reviewer to?

int solution() {
  int n;
  int count = 0;
  scanf("%d", &n);
  int a[n][51];
  int b[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &b[i]);
    for (int j = 0; j < b[i]; j++) {
      scanf("%d", &a[i][j]);
    }
  }
  for (int i = 0; i < n; i++) {
    count = 0;
    for (int j = 0; j < b[i]; j++) {
      if (a[i][j] != 2) {
        ++count;
      }
    }
    printf("%d\n", count);
  }
  return 0;
}

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 s = l
            .unwrap()
            .split(' ')
            .fold(0, |s, c| if c != "2" { s + 1 } else { s });
        writeln!(o, "{}", s).ok();
    }
}


You are given two arrays $$$a$$$ and $$$b$$$, consisting of $$$n$$$ integers each.Let's define a function $$$f(a, b)$$$ as follows:   let's define an array $$$c$$$ of size $$$n$$$, where $$$c_i = a_i \oplus b_i$$$ ($$$\oplus$$$ denotes bitwise XOR);  the value of the function is $$$c_1 \mathbin{\&} c_2 \mathbin{\&} \cdots \mathbin{\&} c_n$$$ (i.e. bitwise AND of the entire array $$$c$$$). Find the maximum value of the function $$$f(a, b)$$$ if you can reorder the array $$$b$$$ in an arbitrary way (leaving the initial order is also an option).

int solution() {
  int t = 0;
  int n = 0;
  int a[100000] = {};
  int b[100000] = {};

  int res = 0;

  int work_a[100000] = {};
  int work_b[100000] = {};
  int idx[100001] = {};
  int work_idx[100001] = {};

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

  while (t > 0) {
    int ans = 0;
    int idx_num = 1;
    res = scanf("%d", &n);
    for (int i = 0; i < n; i++) {
      res = scanf("%d", a + i);
    }
    for (int i = 0; i < n; i++) {
      res = scanf("%d", b + i);
    }
    idx[0] = 0;
    idx[1] = n;
    idx_num = 1;
    for (int i = 29; i >= 0; i--) {
      int is_ok = 1;
      int work_idx_num = 0;
      for (int j = 0; j < idx_num; j++) {
        int work_a_num = 0;
        int work_b_num = 0;
        for (int k = idx[j]; k < idx[j + 1]; k++) {
          if ((a[k] & (1 << i)) > 0) {
            work_a[work_a_num] = a[k];
            work_a_num++;
          }
          if ((b[k] & (1 << i)) <= 0) {
            work_b[work_b_num] = b[k];
            work_b_num++;
          }
        }
        if (work_a_num == work_b_num) {
          work_idx[work_idx_num] = idx[j];
          work_idx_num++;
          if (work_a_num > 0 && work_a_num < idx[j + 1] - idx[j]) {
            work_idx[work_idx_num] = idx[j] + work_a_num;
            work_idx_num++;
          }
          for (int k = idx[j]; k < idx[j + 1]; k++) {
            if ((a[k] & (1 << i)) <= 0) {
              work_a[work_a_num] = a[k];
              work_a_num++;
            }
            if ((b[k] & (1 << i)) > 0) {
              work_b[work_b_num] = b[k];
              work_b_num++;
            }
          }
          for (int k = idx[j]; k < idx[j + 1]; k++) {
            a[k] = work_a[k - idx[j]];
            b[k] = work_b[k - idx[j]];
          }
        } else {
          is_ok = 0;
        }
      }
      if (is_ok > 0) {
        ans += (1 << i);
        for (int j = 0; j < work_idx_num; j++) {
          idx[j] = work_idx[j];
        }
        idx_num = work_idx_num;
        idx[idx_num] = n;
      }
    }
    printf("%d\n", ans);
    t--;
  }

  return 0;
}

fn solution() {
    let t: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    for _ in 0..t {
        let _n: usize = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        };
        let A: Vec<usize> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.parse().unwrap())
                .collect()
        };
        let B: Vec<usize> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.parse().unwrap())
                .collect()
        };

        let mut ans = 0;
        let mut que = Vec::new();
        que.push((A, B));

        for i in (0..30).rev() {
            let bit = 1 << i;

            let mut que2 = Vec::new();
            let mut ok = true;

            for (a, b) in que.iter() {
                let mut a0 = Vec::new();
                let mut a1 = Vec::new();
                let mut b0 = Vec::new();
                let mut b1 = Vec::new();

                for &aa in a.iter() {
                    if aa & bit != 0 {
                        a1.push(aa);
                    } else {
                        a0.push(aa);
                    }
                }
                for &bb in b.iter() {
                    if bb & bit != 0 {
                        b1.push(bb);
                    } else {
                        b0.push(bb);
                    }
                }
                if a0.len() == b1.len() {
                    if !a0.is_empty() {
                        que2.push((a0, b1));
                    }
                    if !a1.is_empty() {
                        que2.push((a1, b0));
                    }
                } else {
                    ok = false;
                    break;
                }
            }

            if ok {
                ans |= bit;
                que = que2;
            }
        }

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


Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak, i, j; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them.

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

    let mut boards = Vec::new();
    for i in 0..4 {
        let mut input = String::new();
        let mut mini_board = Vec::new();
        if i != 0 {
            io::stdin().read_line(&mut input);
            input = String::new();
        }
        for _j in 0..n {
            let mut input = String::new();
            io::stdin().read_line(&mut input);
            let black_vec: Vec<bool> = input.trim().chars().map(|c| c == '1').collect();
            mini_board.push(black_vec);
        }
        boards.push(mini_board);
    }

    let mut incorrect_vec: Vec<u32> = vec![0; 4];
    for i in 0..4 {
        for x in 0..n {
            for y in 0..n {
                let black_sq = (x + y) % 2 == 0;
                if black_sq != boards[i as usize][x as usize][y as usize] {
                    incorrect_vec[i as usize] += 1;
                }
            }
        }
    }

    incorrect_vec.sort();

    println!(
        "{}",
        incorrect_vec[0] + incorrect_vec[1] + 2 * n * n - incorrect_vec[2] - incorrect_vec[3]
    );
}


Polycarp has an integer $$$n$$$ that doesn't contain the digit 0. He can do the following operation with his number several (possibly zero) times: Reverse the prefix of length $$$l$$$ (in other words, $$$l$$$ leftmost digits) of $$$n$$$. So, the leftmost digit is swapped with the $$$l$$$-th digit from the left, the second digit from the left swapped with ($$$l-1$$$)-th left, etc. For example, if $$$n=123456789$$$ and $$$l=5$$$, then the new value of $$$n$$$ will be $$$543216789$$$.Note that for different operations, the values of $$$l$$$ can be different. The number $$$l$$$ can be equal to the length of the number $$$n$$$ — in this case, the whole number $$$n$$$ is reversed.Polycarp loves even numbers. Therefore, he wants to make his number even. At the same time, Polycarp is very impatient. He wants to do as few operations as possible.Help Polycarp. Determine the minimum number of operations he needs to perform with the number $$$n$$$ to make it even or determine that this is impossible.You need to answer $$$t$$$ independent test cases.

int solution(void) {
  int n;
  int num;
  int exist = 0;
  scanf("%d", &n);

  for (int i = 0; i < n; i++) {
    scanf("%d", &num);
    if (!(num & 1)) {
      printf("0\n");
      continue;
    }
    while (num != 0) {
      if (!(num & 1)) {
        exist = 1;
      }
      if (num / 10 == 0) {
        if (!(num & 1)) {
          printf("1\n");
          break;
        }
        if (exist == 1) {
          printf("2\n");
          break;
        } else
          printf("-1\n");
      }
      num /= 10;
    }
    exist = 0;
  }
  return 0;
}

fn solution() {
    let mut input: String = String::new();
    io::stdin().read_line(&mut input).expect("invalid input");

    let t: i32 = input.trim().parse().unwrap();

    for _ in 0..t {
        let mut input_str: String = String::new();
        io::stdin().read_line(&mut input_str).expect("invalid str");

        let s: String = input_str.trim().parse().unwrap();

        let first_digit: i32 = s.chars().next().unwrap() as i32;
        let last_digit: i32 = s.chars().last().unwrap() as i32;

        if last_digit % 2 == 0 {
            println!("0");
            continue;
        }
        if first_digit % 2 == 0 {
            println!("1");
            continue;
        }

        let count_2 = s.matches('2').count();
        let count_4 = s.matches('4').count();
        let count_6 = s.matches('6').count();
        let count_8 = s.matches('8').count();

        if count_2 > 0 || count_4 > 0 || count_6 > 0 || count_8 > 0 {
            println!("2");
            continue;
        }
        println!("-1");
    }
}


Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy — and after that, she has $$$55$$$ candies too.

int solution() {
  long long n;
  scanf("%lld", &n);
  while (n--) {
    long long a[3];
    long long sum = 0;
    for (int i = 0; i < 3; i++) {
      scanf("%lld", &a[i]);
      sum = sum + a[i];
    }
    printf("%lld\n", sum / 2);
  }
  return 0;
}

fn solution() {
    let n = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        iter.next().unwrap().parse::<usize>().unwrap()
    };

    for _ in 0..n {
        let (a, b, c) = {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                iter.next().unwrap().parse::<u64>().unwrap(),
                iter.next().unwrap().parse::<u64>().unwrap(),
                iter.next().unwrap().parse::<u64>().unwrap(),
            )
        };

        println!("{}", (a + b + c) / 2);
    }
}


Numbers $$$1, 2, 3, \dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal:  choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$;  choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$;  choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    printf("2\n");
    printf("%d %d\n", n - 1, n);
    while (n >= 3) {
      printf("%d %d\n", n - 2, n);
      n--;
    }
  }
  return 0;
}

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let test: i32 = str.trim().parse().unwrap();
    for _ in 0..test {
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        let x: usize = str.trim().parse().unwrap();
        let mut ave = x;
        for i in 1..x {
            ave = (ave + x - i).div_ceil(2);
        }
        println!("{}", ave);
        ave = x;
        for i in 1..x {
            println!("{} {}", ave, x - i);
            ave = (ave + x - i).div_ceil(2);
        }
    }
}


Score : <var>200</var> points

Problem Statement

Find the sum of the integers between <var>1</var> and <var>N</var> (inclusive), whose sum of digits written in base <var>10</var> is between <var>A</var> and <var>B</var> (inclusive).

Constraints

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

<var>1 \leq A \leq B \leq 36</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var>

Output

Print the sum of the integers between <var>1</var> and <var>N</var> (inclusive), whose sum of digits written in base <var>10</var> is between <var>A</var> and <var>B</var> (inclusive).

Sample Input 1

20 2 5

Sample Output 1

84

Among the integers not greater than <var>20</var>, the ones whose sums of digits are between <var>2</var> and <var>5</var>, are: <var>2,3,4,5,11,12,13,14</var> and <var>20</var>. We should print the sum of these, <var>84</var>.

Sample Input 2

10 1 2

Sample Output 2

13

Sample Input 3

100 4 16

Sample Output 3

4554

fn solution() {
    let scan = std::io::stdin();
    let mut line = String::new();
    let _ = scan.read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();

    let mut n: Vec<i32> = Vec::new();

    for x in vec {
        n.push(x.parse().unwrap());
    }

    let mut ans: i32 = 0;
    for x in 1..n[0] + 1 {
        let mut cnt: i32 = 0;
        let mut tmp: i32 = x;
        while tmp != 0 {
            cnt += tmp % 10;
            tmp /= 10;
        }
        if cnt <= n[2] && cnt >= n[1] {
            ans += x
        };
    }

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


You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings.An integer greater than 1 is composite, if it is not prime, i.e. if it has positive divisors not equal to 1 and the integer itself.

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let N: usize = s.trim_end().parse().unwrap();
    s.clear();
    for _i in 0..N {
        io::stdin().read_line(&mut s).unwrap();
        let q: i32 = s.trim_end().parse().unwrap();
        if q < 4 {
            println!("-1");
        } else {
            let rem = q % 4;
            let div = q / 4;
            let ans = match rem {
                0 => div,
                1 => {
                    let mut t = div - 2 + 1;
                    if div < 2 {
                        t = -1;
                    }
                    t
                }
                2 => {
                    let mut t = div - 1 + 1;
                    if div < 1 {
                        t = -1;
                    }
                    t
                }
                3 => {
                    let mut t = div - 3 + 2;
                    if div < 3 {
                        t = -1;
                    }
                    t
                }
                _ => -1,
            };
            println!("{}", ans);
        }
        s.clear();
    }
}


Score : <var>700</var> points

Problem Statement

Takahashi is hosting an sports meet.
There are <var>N</var> people who will participate. These people are conveniently numbered <var>1</var> through <var>N</var>.
Also, there are <var>M</var> options of sports for this event. These sports are numbered <var>1</var> through <var>M</var>.
Among these options, Takahashi will select one or more sports (possibly all) to be played in the event.

Takahashi knows that Person <var>i</var>'s <var>j</var>-th favorite sport is Sport <var>A_{ij}</var>.
Each person will only participate in his/her most favorite sport among the ones that are actually played in the event, and will not participate in the other sports.

Takahashi is worried that one of the sports will attract too many people.
Therefore, he would like to carefully select sports to be played so that the number of the participants in the sport with the largest number of participants is minimized.
Find the minimum possible number of the participants in the sport with the largest number of participants.

Constraints

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

<var>1 \leq M \leq 300</var>

<var>A_{i1}</var> , <var>A_{i2}</var> , <var>...</var> , <var>A_{iM}</var> is a permutation of the integers from <var>1</var> to <var>M</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_{11}</var> <var>A_{12}</var> <var>...</var> <var>A_{1M}</var>
<var>A_{21}</var> <var>A_{22}</var> <var>...</var> <var>A_{2M}</var>
<var>:</var>
<var>A_{N1}</var> <var>A_{N2}</var> <var>...</var> <var>A_{NM}</var>

Output

Print the minimum possible number of the participants in the sport with the largest number of participants.

Sample Input 1

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

Sample Output 1

2

Assume that Sports <var>1</var>, <var>3</var> and <var>4</var> are selected to be played. In this case, Person <var>1</var> will participate in Sport <var>1</var>, Person <var>2</var> in Sport <var>3</var>, Person <var>3</var> in Sport <var>3</var> and Person <var>4</var> in Sport <var>4</var>.
Here, the sport with the largest number of participants is Sport <var>3</var>, with two participants.
There is no way to reduce the number of participants in the sport with the largest number of participants to <var>1</var>. Therefore, the answer is <var>2</var>.

Sample Input 2

3 3
2 1 3
2 1 3
2 1 3

Sample Output 2

3

Since all the people have the same taste in sports, there will be a sport with three participants, no matter what sports are selected.
Therefore, the answer is <var>3</var>.

int solution(void) {
  int N;
  int M;
  scanf("%d %d", &N, &M);
  int A[N][M];
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
      scanf("%d", &A[i][j]);
    }
  }
  int kibousya[M];
  int nozoki[M];
  for (int i = 0; i < M; i++) {
    kibousya[i] = 0;
    nozoki[i] = 0;
  }
  int ans = 114514;
  for (int i = 0; i < M; i++) {
    for (int j = 0; j < N; j++) {
      for (int k = 0; k < M; k++) {
        if (nozoki[A[j][k] - 1] == 0) {
          kibousya[A[j][k] - 1]++;
          break;
        }
      }
    }
    int maxkibou = 0;
    for (int j = 0; j < M; j++) {
      if (nozoki[j] == 0 && kibousya[j] >= kibousya[maxkibou]) {
        maxkibou = j;
      }
    }
    if (ans > kibousya[maxkibou]) {
      ans = kibousya[maxkibou];
    }
    nozoki[maxkibou] = 1;
    for (int i = 0; i < M; i++) {
      kibousya[i] = 0;
    }
  }
  printf("%d", ans);
  return 0;
}

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

    let N = buf_it.next().unwrap().parse::<usize>().unwrap();
    let M = buf_it.next().unwrap().parse::<usize>().unwrap();
    let A = (0..N)
        .map(|_| {
            (0..M)
                .map(|_| buf_it.next().unwrap().parse::<usize>().unwrap() - 1)
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();

    let check = |n: usize| {
        let mut popped = HashSet::new();
        let mut idx = (0..N).map(|_| 0).collect::<Vec<_>>();
        loop {
            let mut cnt = (0..M).map(|_| 0).collect::<Vec<_>>();
            for i in 0..N {
                cnt[A[i][idx[i]]] += 1;
            }
            if *(cnt.iter().max().unwrap()) <= n {
                return true;
            }
            for j in 0..M {
                if cnt[j] > n {
                    popped.insert(j);
                }
            }
            if popped.len() == M {
                break;
            }
            for i in 0..N {
                while popped.contains(&A[i][idx[i]]) {
                    idx[i] += 1;
                }
            }
        }
        false
    };
    let mut l = 0;
    let mut r = N;
    while l + 1 < r {
        let i = (l + r) / 2;
        if check(i) {
            r = i;
        } else {
            l = i;
        }
    }
    println!("{}", r);
}


There are $$$n$$$ kids, numbered from $$$1$$$ to $$$n$$$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (all these numbers are from $$$1$$$ to $$$n$$$ and are distinct, so $$$p$$$ is a permutation). Let the next kid for a kid $$$p_i$$$ be kid $$$p_{i + 1}$$$ if $$$i < n$$$ and $$$p_1$$$ otherwise. After the dance, each kid remembered two kids: the next kid (let's call him $$$x$$$) and the next kid for $$$x$$$. Each kid told you which kids he/she remembered: the kid $$$i$$$ remembered kids $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$. However, the order of $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ can differ from their order in the circle.    Example: 5 kids in a circle, $$$p=[3, 2, 4, 1, 5]$$$ (or any cyclic shift). The information kids remembered is: $$$a_{1,1}=3$$$, $$$a_{1,2}=5$$$; $$$a_{2,1}=1$$$, $$$a_{2,2}=4$$$; $$$a_{3,1}=2$$$, $$$a_{3,2}=4$$$; $$$a_{4,1}=1$$$, $$$a_{4,2}=5$$$; $$$a_{5,1}=2$$$, $$$a_{5,2}=3$$$. You have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

int solution() {

  int n;

  scanf("%d", &n);

  int ans[n + 5];
  int a[n + 5];
  int b[n + 5];

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

  ans[1] = 1;
  ans[2] = a[1];
  ans[3] = b[1];

  if (a[a[1]] != b[1] && b[a[1]] != b[1]) {
    ans[2] = b[1];
    ans[3] = a[1];
  }

  int place = 3;

  while (place < n) {
    if (a[ans[place - 1]] == ans[place]) {
      ans[place + 1] = b[ans[place - 1]];
    } else {
      ans[place + 1] = a[ans[place - 1]];
    }
    place++;
  }

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

  printf("\n");
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut count = line.trim().parse().unwrap();
    line.clear();
    let mut neighbours = Vec::with_capacity(count);
    while count > 0 {
        input.read_line(&mut line).unwrap();
        let mut pair = line.split_whitespace();
        let first = pair.next().unwrap().parse::<usize>().unwrap() - 1;
        let second = pair.next().unwrap().parse::<usize>().unwrap() - 1;
        line.clear();
        neighbours.push((first, second));
        count -= 1;
    }
    line.shrink_to_fit();
    let mut cur;
    let mut next = neighbours[0].0;
    let mut next_next = neighbours[0].1;
    if neighbours[next].0 == next_next || neighbours[next].1 == next_next {
        cur = next;
        next = next_next;
    } else {
        cur = next_next;
    }
    print!("1 {} {}", cur + 1, next + 1);
    count = neighbours.len() - 3;
    while count > 0 {
        if neighbours[cur].0 == next {
            next_next = neighbours[cur].1;
        } else {
            next_next = neighbours[cur].0;
        }
        print!(" {}", next_next + 1);
        cur = next;
        next = next_next;
        count -= 1;
    }
}


Score: <var>100</var> points

Problem Statement

We held two competitions: Coding Contest and Robot Maneuver.

In each competition, the contestants taking the <var>3</var>-rd, <var>2</var>-nd, and <var>1</var>-st places receive <var>100000</var>, <var>200000</var>, and <var>300000</var> yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional <var>400000</var> yen.

DISCO-Kun took the <var>X</var>-th place in Coding Contest and the <var>Y</var>-th place in Robot Maneuver.
Find the total amount of money he earned.

Constraints

<var>1 \leq X \leq 205</var>

<var>1 \leq Y \leq 205</var>

<var>X</var> and <var>Y</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>Y</var>

Output

Print the amount of money DISCO-Kun earned, as an integer.

Sample Input 1

1 1

Sample Output 1

1000000

In this case, he earned <var>300000</var> yen in Coding Contest and another <var>300000</var> yen in Robot Maneuver. Furthermore, as he won both competitions, he got an additional <var>400000</var> yen.
In total, he made <var>300000 + 300000 + 400000 = 1000000</var> yen.

Sample Input 2

3 101

Sample Output 2

100000

In this case, he earned <var>100000</var> yen in Coding Contest.

Sample Input 3

4 4

Sample Output 3

0

In this case, unfortunately, he was the highest-ranked contestant without prize money in both competitions.

fn solution() {
    let (X, Y): (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 x = if X == 1 {
        300000
    } else if X == 2 {
        200000
    } else if X == 3 {
        100000
    } else {
        0
    };
    let y = if Y == 1 {
        300000
    } else if Y == 2 {
        200000
    } else if Y == 3 {
        100000
    } else {
        0
    };

    let ans = if X == 1 && Y == 1 {
        x + y + 400000
    } else {
        x + y
    };

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


Score : <var>200</var> points

Problem Statement

Given <var>N</var> integers <var>A_1, ..., A_N</var>, compute <var>A_1 \times ... \times A_N</var>.

However, if the result exceeds <var>10^{18}</var>, print -1 instead.

Constraints

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

<var>0 \leq A_i \leq 10^{18}</var>

All values in input are integers.

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 value <var>A_1 \times ... \times A_N</var> as an integer, or -1 if the value exceeds <var>10^{18}</var>.

Sample Input 1

2
1000000000 1000000000

Sample Output 1

1000000000000000000

We have <var>1000000000 \times 1000000000 = 1000000000000000000</var>.

Sample Input 2

3
101 9901 999999000001

Sample Output 2

-1

We have <var>101 \times 9901 \times 999999000001 = 1000000000000000001</var>, which exceeds <var>10^{18}</var>, so we should print -1 instead.

Sample Input 3

31
4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0

Sample Output 3

0

int solution(void) {
  int i = 0;
  int N = 0;
  scanf("%d", &N);

  long long A[N];
  long long ans = 1;
  long long x = (pow(10, 18.0));

  if (2 <= N && N <= (pow(10, 5.0))) {
    for (i = 0; i < N; i++) {
      scanf("%lld", &A[i]);
    }
    for (i = 0; i < N; i++) {
      if (A[i] == 0) {
        printf("0");
        return 0;
      }
    }
  } else {
    return 0;
  }

  for (i = 0; i < N; i++) {
    if (A[i] <= x / ans) {

      ans = ans * A[i];

    } else {
      printf("-1\n");
      return 0;
    }
  }

  printf("%lld\n", ans);

  return 0;
}

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    is.clear();
    stdin().read_line(&mut is).ok();
    let itr = is.split_whitespace().map(|e| e.parse::<i128>().unwrap());
    let mut ans = 1;
    let flg = itr.clone().any(|e| e == 0);
    if !flg {
        for e in itr {
            ans *= e;
            if ans > 1000000000000000000 {
                ans = -1;
                break;
            }
        }
    }

    println!("{}", if flg { 0 } else { ans });
}


The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.The main school of the capital is located in $$$(s_x, s_y)$$$. There are $$$n$$$ students attending this school, the $$$i$$$-th of them lives in the house located in $$$(x_i, y_i)$$$. It is possible that some students live in the same house, but no student lives in $$$(s_x, s_y)$$$.After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the $$$i$$$-th student goes from the school to his house is $$$|s_x - x_i| + |s_y - y_i|$$$.The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the $$$i$$$-th student will buy a shawarma if at least one of the shortest paths from the school to the $$$i$$$-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let mut iter = str.split_whitespace();
    let n: i64 = iter.next().unwrap().parse().unwrap();
    let s_x: i64 = iter.next().unwrap().parse().unwrap();
    let s_y: i64 = iter.next().unwrap().parse().unwrap();
    let mut u = 0;
    let mut d = 0;
    let mut l = 0;
    let mut r = 0;

    for _ in 0..n {
        str.clear();
        let _b1 = stdin().read_line(&mut str).unwrap();
        let mut iter = str.split_whitespace();
        let x: i64 = iter.next().unwrap().parse().unwrap();
        let y: i64 = iter.next().unwrap().parse().unwrap();
        if x > s_x {
            r += 1;
        }
        if x < s_x {
            l += 1;
        }
        if y > s_y {
            u += 1;
        }
        if y < s_y {
            d += 1;
        }
    }
    let maxim = max(u, max(d, max(r, l)));
    println!("{}", maxim);
    if maxim == u {
        println!("{} {}", s_x, s_y + 1);
    } else if maxim == d {
        println!("{} {}", s_x, s_y - 1);
    } else if maxim == l {
        println!("{} {}", s_x - 1, s_y);
    } else if maxim == r {
        println!("{} {}", s_x + 1, s_y);
    }
}