Score : <var>200</var> points

Problem Statement

AtCoDeer the deer found two rectangles lying on the table, each with height <var>1</var> and width <var>W</var>.
If we consider the surface of the desk as a two-dimensional plane, the first rectangle covers the vertical range of <var>[0,1]</var> and the horizontal range of <var>[a,a+W]</var>, and the second rectangle covers the vertical range of <var>[1,2]</var> and the horizontal range of <var>[b,b+W]</var>, as shown in the following figure:

AtCoDeer will move the second rectangle horizontally so that it connects with the first rectangle.
Find the minimum distance it needs to be moved.

Constraints

All input values are integers.

<var>1≤W≤10^5</var>

<var>1≤a,b≤10^5</var>

Input

The input is given from Standard Input in the following format:

<var>W</var> <var>a</var> <var>b</var>

Output

Print the minimum distance the second rectangle needs to be moved.

Sample Input 1

3 2 6

Sample Output 1

1

This input corresponds to the figure in the statement. In this case, the second rectangle should be moved to the left by a distance of <var>1</var>.

Sample Input 2

3 1 3

Sample Output 2

0

The rectangles are already connected, and thus no move is needed.

Sample Input 3

5 10 1

Sample Output 3

4

int solution() {

  int W = 0;
  int A = 0;
  int B = 0;
  int save = 0;
  int length = 0;

  scanf("%d %d %d", &W, &A, &B);
  if (A > B) {
    save = A;
    A = B;
    B = save;
  }

  if ((A + W) >= B) {
    length = 0;
  }
  if ((A + W) < B) {
    length = B - (A + W);
  }

  printf("%d", length);

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<isize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
    println!(
        "{}",
        cmp::max(0, cmp::max(v[1], v[2]) - (cmp::min(v[1], v[2]) + v[0]))
    );
}


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int x = 0;
    scanf("%d", &n);
    int a[n + 10];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      if (i >= 1 && a[i] < a[i - 1]) {
        x = 1;
      }
    }
    if (x == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let (r, mut lc) = (BufReader::new(io::stdin()), 0);
    for l in r.lines() {
        let v = l
            .unwrap()
            .split(" ")
            .map(i32::from_str)
            .collect::<Result<Vec<_>, _>>();
        let (mut m, mut pf) = (0, false);
        for x in v.unwrap() {
            if lc > 0 && lc & 1 == 0 {
                m = cmp::max(m, x);
                if x < m {
                    pf = true;
                    break;
                }
            }
        }
        if lc > 0 && lc & 1 == 0 {
            println!("{}", if pf { "YES" } else { "NO" })
        }
        lc += 1;
    }
}


The Smallest Window I

  For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $S$, find the smallest sub-array size (smallest window length) where the sum of the sub-array is greater than or equal to $S$. If there is not such sub-array, report 0.

Constraints

 $1 \leq N \leq 10^5$

 $1 \leq S \leq 10^9$

 $1 \leq a_i \leq 10^4$

Input

The input is given in the following format.

$N$ $S$

$a_1$ $a_2$ ... $a_N$

Output

  Print the smallest sub-array size in a line.

Sample Input 1

6 4
1 2 1 2 3 2

Sample Output 1

2

Sample Input 2

6 6
1 2 1 2 3 2

Sample Output 2

3

Sample Input 3

3 7
1 2 3

Sample Output 3

0

int solution() {
  int length;
  int sum;
  int i;
  int left = 0;
  int right = 0;
  int currentSmallest = 1000000;
  scanf(" %d %d", &length, &sum);
  int *array = (int *)malloc(sizeof(int[length]));
  for (i = 0; i < length; i++) {
    scanf(" %d", array + i);
  }
  int currentSum = array[0];

  while (1) {
    if (currentSmallest == 1) {
      printf("%d\n", 1);
      return 0;
    }
    int subLength = right - left + 1;
    if (subLength >= currentSmallest) {

      currentSum -= array[left++];
      continue;
    }

    if (currentSum >= sum) {
      currentSmallest = subLength;
      currentSum -= array[left++];
      continue;
    }
    if (right == length - 1) {

      if (left == 0) {
        printf("%d\n", 0);
        return 0;
      }
      printf("%d\n", currentSmallest);
      return 0;
    }

    currentSum += array[++right];
  }
  return 0;
}

fn solution() {
    let mut stdin = io::stdin();
    let mut buf = String::new();
    let _ = stdin.read_to_string(&mut buf);
    let mut iter = buf.split_whitespace();

    let n: usize = iter.next().unwrap().parse().unwrap();
    let s = iter.next().unwrap().parse().unwrap();
    let a: Vec<usize> = iter.map(|nstr| nstr.parse().unwrap()).collect();

    let mut i = 0;
    let mut j = 0;
    let mut sum = 0;
    let mut ans = std::usize::MAX;
    while j <= n {
        if sum < s {
            if j == n {
                break;
            }
            sum += a[j];
            j += 1;
        } else {
            ans = min(ans, j - i);
            sum -= a[i];
            i += 1;
        }
    }
    if ans == std::usize::MAX {
        ans = 0;
    }

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


Given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. You can perform the following operation on them:  select any element $$$a_i$$$ ($$$1 \le i \le n$$$) and divide it by $$$2$$$ (round down). In other words, you can replace any selected element $$$a_i$$$ with the value $$$\left \lfloor \frac{a_i}{2}\right\rfloor$$$ (where $$$\left \lfloor x \right\rfloor$$$ is – round down the real number $$$x$$$). Output the minimum number of operations that must be done for a sequence of integers to become strictly increasing (that is, for the condition $$$a_1 \lt a_2 \lt \dots \lt a_n$$$ to be satisfied). Or determine that it is impossible to obtain such a sequence. Note that elements cannot be swapped. The only possible operation is described above.For example, let $$$n = 3$$$ and a sequence of numbers $$$[3, 6, 5]$$$ be given. Then it is enough to perform two operations on it:   Write the number $$$\left \lfloor \frac{6}{2}\right\rfloor = 3$$$ instead of the number $$$a_2=6$$$ and get the sequence $$$[3, 3, 5]$$$;  Then replace $$$a_1=3$$$ with $$$\left \lfloor \frac{3}{2}\right\rfloor = 1$$$ and get the sequence $$$[1, 3, 5]$$$. The resulting sequence is strictly increasing because $$$1 \lt 3 \lt 5$$$.

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

    for _ in 0..t {
        let mut buf = String::new();
        stdin().read_line(&mut buf);

        let mut v: Vec<f64> = Vec::with_capacity(buf.trim().parse::<usize>().unwrap());
        buf = String::new();
        stdin().read_line(&mut buf);
        for i in buf.split_whitespace() {
            v.push(i.parse().unwrap());
        }

        let mut c = 0;
        let mut solvable = true;

        'qwe: for i in (0..v.len() - 1).rev() {
            loop {
                if v[i + 1] == 0_f64 {
                    solvable = false;
                    break 'qwe;
                }

                if v[i + 1] > v[i] {
                    break;
                }

                v[i] = f64::floor(v[i] / 2_f64);
                c += 1;
            }
        }

        if solvable {
            println!("{}", c);
        } else {
            println!("-1");
        }
    }
}


There are $$$n$$$ participants in a competition, participant $$$i$$$ having a strength of $$$s_i$$$. Every participant wonders how much of an advantage they have over the other best participant. In other words, each participant $$$i$$$ wants to know the difference between $$$s_i$$$ and $$$s_j$$$, where $$$j$$$ is the strongest participant in the competition, not counting $$$i$$$ (a difference can be negative).So, they ask you for your help! For each $$$i$$$ ($$$1 \leq i \leq n$$$) output the difference between $$$s_i$$$ and the maximum strength of any participant other than participant $$$i$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int max = 0;
    int smax = 0;
    int a[n];

    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      if (a[i] >= max) {
        smax = max;
        max = a[i];
      } else if (a[i] > smax && a[i] != max) {
        smax = a[i];
      }
    }
    for (int i = 0; i < n; i++) {

      if (a[i] == max) {
        printf("%d ", (max - smax));
      } else if (a[i] < max) {
        printf("%d ", (a[i] - max));
      }
    }
  }
  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("");
    let t: i32 = line.trim().parse().expect("");
    let reader = io::stdin();
    for _ in 0..t {
        reader.lock().lines().next();
        let numbers: Vec<i32> = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|s| s.parse().unwrap())
            .collect();
        let mut max_value: i32 = 0;
        let mut second_max: i32 = 0;
        for c in &numbers {
            if c > &max_value {
                second_max = max_value;
                max_value = *c;
            } else if c > &second_max {
                second_max = *c;
            }
        }
        for c in &numbers {
            if c == &max_value {
                print!("{:?} ", c - second_max);
            } else {
                print!("{:?} ", c - max_value);
            }
        }
        println!();
    }
}


You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters. Suitability of string s is calculated by following metric:Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulting strings s, you choose the one with the largest number of non-intersecting occurrences of string t. Suitability is this number of occurrences.You should replace all '?' characters with small Latin letters in such a way that the suitability of string s is maximal.

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

    use std::io::stdin;
    stdin().read_line(&mut s).unwrap();
    stdin().read_line(&mut t).unwrap();

    let mut arr = [0u32; 26];

    for ltr in t.trim().chars().filter(|l| l.is_alphabetic()) {
        let a = ltr.to_digit(36).unwrap() as usize;
        let b = 'a'.to_digit(36).unwrap() as usize;
        arr[a - b] += 1;
    }

    let mut brr = [0u32; 26];

    for ltr in s.trim().chars().filter(|l| l.is_alphabetic()) {
        let a = ltr.to_digit(36).unwrap() as usize;
        let b = 'a'.to_digit(36).unwrap() as usize;
        brr[a - b] += 1;
    }

    use std::char::from_digit;

    let ans: String = s
        .chars()
        .map(|c| {
            if c == '?' {
                if let Some(i) = (0usize..26)
                    .filter(|&i| arr[i] != 0)
                    .min_by_key(|&i| brr[i] / arr[i])
                {
                    brr[i] += 1;
                    from_digit(i as u32 + 'a'.to_digit(36).unwrap(), 36).unwrap()
                } else {
                    'a'
                }
            } else {
                c
            }
        })
        .collect();

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


A PIN code is a string that consists of exactly $$$4$$$ digits. Examples of possible PIN codes: 7013, 0000 and 0990. Please note that the PIN code can begin with any digit, even with 0.Polycarp has $$$n$$$ ($$$2 \le n \le 10$$$) bank cards, the PIN code of the $$$i$$$-th card is $$$p_i$$$.Polycarp has recently read a recommendation that it is better to set different PIN codes on different cards. Thus he wants to change the minimal number of digits in the PIN codes of his cards so that all $$$n$$$ codes would become different.Formally, in one step, Polycarp picks $$$i$$$-th card ($$$1 \le i \le n$$$), then in its PIN code $$$p_i$$$ selects one position (from $$$1$$$ to $$$4$$$), and changes the digit in this position to any other. He needs to change the minimum number of digits so that all PIN codes become different.Polycarp quickly solved this problem. Can you solve it?

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

    let t = get!();

    for _ in 0..t {
        let n = get!(usize);
        let mut vs = vec![];
        let mut count = vec![0; 10000];
        for _i in 0..n {
            let pin = get!(usize);
            count[pin] += 1;
            vs.push(pin);
        }
        let mut changes = 0;
        for pin in vs.iter_mut() {
            if count[*pin] == 1 {
                continue;
            }
            changes += 1;
            count[*pin] -= 1;
            let mut w = 1;
            'outer: for _i in 0..4 {
                let tmp = *pin - (*pin / w % 10) * w;
                for x in 0..9 {
                    let new_pin = tmp + x * w;
                    if count[new_pin] == 0 {
                        *pin = new_pin;
                        count[new_pin] += 1;
                        break 'outer;
                    }
                }
                w *= 10;
            }
        }

        println!("{}", changes);
        for pin in vs {
            println!("{:04}", pin);
        }
    }
}


You are living on an infinite plane with the Cartesian coordinate system on it. In one move you can go to any of the four adjacent points (left, right, up, down).More formally, if you are standing at the point $$$(x, y)$$$, you can:   go left, and move to $$$(x - 1, y)$$$, or  go right, and move to $$$(x + 1, y)$$$, or  go up, and move to $$$(x, y + 1)$$$, or  go down, and move to $$$(x, y - 1)$$$. There are $$$n$$$ boxes on this plane. The $$$i$$$-th box has coordinates $$$(x_i,y_i)$$$. It is guaranteed that the boxes are either on the $$$x$$$-axis or the $$$y$$$-axis. That is, either $$$x_i=0$$$ or $$$y_i=0$$$.You can collect a box if you and the box are at the same point. Find the minimum number of moves you have to perform to collect all of these boxes if you have to start and finish at the point $$$(0,0)$$$.

int solution() {

  int i = 0;
  int j = 0;
  int t = 0;
  int n = 0;
  int x = 0;
  int y = 0;
  int ans = 0;
  int x_right = 0;
  int x_left = 0;
  int y_top = 0;
  int y_bottom = 0;

  scanf("%d\n", &t);
  i = t;
  while (i > 0) {
    scanf("%d\n", &n);

    for (j = 0; j < n; j++) {
      scanf("%d %d\n", &x, &y);
      if (x > x_right && x != 0) {
        x_right = x;
      }
      if (x < x_left && x != 0) {
        x_left = x;
      }
      if (y > y_top && y != 0) {
        y_top = y;
      }
      if (y < y_bottom && y != 0) {
        y_bottom = y;
      }
    }
    ans = 2 * (x_right - x_left) + 2 * (y_top - y_bottom);
    printf("%d\n", ans);
    x_right = 0, x_left = 0, y_top = 0, y_bottom = 0;
    i--;
  }
}

fn solution() {
    let mut input = String::new();
    stdin().read_line(&mut input).unwrap();
    let t: usize = input.trim().parse().unwrap();
    for _ in 0..t {
        input = String::new();
        stdin().read_line(&mut input).unwrap();
        let n: usize = input.trim().parse().unwrap();
        let mut v: Vec<(i32, i32)> = Vec::new();
        for _ in 0..n {
            input = String::new();
            stdin().read_line(&mut input).unwrap();
            let tmp = input
                .trim()
                .split(" ")
                .map(|x| x.parse::<i32>().unwrap())
                .collect::<Vec<i32>>();
            let [x, y] = [tmp[0], tmp[1]];
            v.push((x, y));
        }
        let mut xp = 0;
        let mut xn = 0;
        let mut yp = 0;
        let mut yn = 0;

        for (x, y) in v {
            if x < 0 {
                xn = xn.min(x);
            } else {
                xp = xp.max(x);
            }

            if y < 0 {
                yn = yn.min(y);
            } else {
                yp = yp.max(y);
            }
        }

        let mut ans = xp;
        let mut prev = xp;
        if yp > 0 {
            ans += prev + yp;
            prev = yp;
        }

        if yn < 0 {
            ans += prev + yn.abs();
            prev = yn.abs();
        }

        if xn < 0 {
            ans += prev + xn.abs();
            prev = xn.abs();
        }

        ans += prev;

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


Score : <var>400</var> points

Problem Statement

You are going out for a walk, when you suddenly encounter <var>N</var> monsters. Each monster has a parameter called health, and the health of the <var>i</var>-th monster is <var>h_i</var> at the moment of encounter. A monster will vanish immediately when its health drops to <var>0</var> or below.

Fortunately, you are a skilled magician, capable of causing explosions that damage monsters. In one explosion, you can damage monsters as follows:

Select an alive monster, and cause an explosion centered at that monster. The health of the monster at the center of the explosion will decrease by <var>A</var>, and the health of each of the other monsters will decrease by <var>B</var>. Here, <var>A</var> and <var>B</var> are predetermined parameters, and <var>A > B</var> holds.

At least how many explosions do you need to cause in order to vanish all the monsters?

Constraints

All input values are integers.

<var>1 ≤ N ≤ 10^5</var>

<var>1 ≤ B < A ≤ 10^9</var>

<var>1 ≤ h_i ≤ 10^9</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var>
<var>h_1</var>
<var>h_2</var>
<var>:</var>
<var>h_N</var>

Output

Print the minimum number of explosions that needs to be caused in order to vanish all the monsters.

Sample Input 1

4 5 3
8
7
4
2

Sample Output 1

2

You can vanish all the monsters in two explosion, as follows:

First, cause an explosion centered at the monster with <var>8</var> health. The healths of the four monsters become <var>3</var>, <var>4</var>, <var>1</var> and <var>-1</var>, respectively, and the last monster vanishes.

Second, cause an explosion centered at the monster with <var>4</var> health remaining. The healths of the three remaining monsters become <var>0</var>, <var>-1</var> and <var>-2</var>, respectively, and all the monsters are now vanished.

Sample Input 2

2 10 4
20
20

Sample Output 2

4

You need to cause two explosions centered at each monster, for a total of four.

Sample Input 3

5 2 1
900000000
900000000
1000000000
1000000000
1000000000

Sample Output 3

800000000

int solution(void) {
  long long n;
  long long a;
  long long b;
  long long max = 0;
  scanf("%lld%lld%lld", &n, &a, &b);
  long long h[n];
  long long p[n];
  for (int i = 0; i < n; i++) {
    scanf("%lld", &h[i]);
    if (max < h[i]) {
      max = h[i];
    }
  }

  long long small = 0;
  long long big = (max + b - 1) / b;
  while (small != big) {
    long long t = small + ((big - small) / 2);
    long long count = 0;
    for (int i = 0; i < n; i++) {
      p[i] = h[i];
      p[i] -= t * b;
      if (p[i] > 0) {
        count += (p[i] + (a - b) - 1) / (a - b);
      }
    }
    if (count > t) {
      small = t + 1;
    } else {
      big = t;
    }
  }
  printf("%lld\n", big);
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let a: i64 = itr.next().unwrap().parse().unwrap();
    let b: i64 = itr.next().unwrap().parse().unwrap();
    let h: Vec<i64> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();

    let c = |x: i64| {
        let mut cnt = 0;
        for i in 0..h.len() {
            cnt += std::cmp::max(0, h[i] - b * x + a - b - 1) / (a - b);
        }
        cnt <= x
    };

    let mut ok = 1i64 << 30;
    let mut ng = 0;
    while ok - ng > 1 {
        let mid = (ok + ng) >> 1;
        if c(mid) {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    println!("{}", ok);
}


Score : <var>600</var> points

Problem Statement

There is a game that involves three variables, denoted <var>A</var>, <var>B</var>, and <var>C</var>.

As the game progresses, there will be <var>N</var> events where you are asked to make a choice.
Each of these choices is represented by a string <var>s_i</var>. If <var>s_i</var> is AB, you must add <var>1</var> to <var>A</var> or <var>B</var> then subtract <var>1</var> from the other; if <var>s_i</var> is AC, you must add <var>1</var> to <var>A</var> or <var>C</var> then subtract <var>1</var> from the other; if <var>s_i</var> is BC, you must add <var>1</var> to <var>B</var> or <var>C</var> then subtract <var>1</var> from the other.

After each choice, none of <var>A</var>, <var>B</var>, and <var>C</var> should be negative.

Determine whether it is possible to make <var>N</var> choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

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

<var>0 \leq A,B,C \leq 10^9</var>

<var>N, A, B, C</var> are integers.

<var>s_i</var> is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var> <var>C</var>
<var>s_1</var>
<var>s_2</var>
<var>:</var>
<var>s_N</var>

Output

If it is possible to make <var>N</var> choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent <var>N</var> lines. The <var>(i+1)</var>-th line should contain the name of the variable (A, B, or C) to which you add <var>1</var> in the <var>i</var>-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add <var>1</var> to <var>A</var> and subtract <var>1</var> from <var>B</var>. <var>A</var> becomes <var>2</var>, and <var>B</var> becomes <var>2</var>.

In the second choice, add <var>1</var> to <var>C</var> and subtract <var>1</var> from <var>A</var>. <var>C</var> becomes <var>1</var>, and <var>A</var> becomes <var>1</var>.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A

fn solution() {
    let mut line = String::new();
    std::io::stdin().read_to_string(&mut line).unwrap();
    let mut it = line.split_whitespace();
    let n: usize = it.next().unwrap().parse().unwrap();
    let mut a: usize = it.next().unwrap().parse().unwrap();
    let mut b: usize = it.next().unwrap().parse().unwrap();
    let mut c: usize = it.next().unwrap().parse().unwrap();
    let s: Vec<i32> = it
        .map(|a| match a {
            "AB" => 1,
            "BC" => 2,
            _ => 3,
        })
        .collect();

    a = min(a, 9);
    b = min(b, 9);
    c = min(c, 9);
    let sum = a + b + c;
    let orig_a = a;
    let orig_b = b;

    let mut dp = vec![vec![vec![0; sum + 1]; sum + 1]; n + 1];
    dp[0][a][b] = 1;
    for i in 0..n {
        for a in 0..=sum {
            for b in 0..=sum {
                if dp[i][a][b] == 0 {
                    continue;
                }
                let c = sum - a - b;
                if s[i] == 1 {
                    if a > 0 {
                        dp[i + 1][a - 1][b + 1] = 2;
                    }
                    if b > 0 {
                        dp[i + 1][a + 1][b - 1] = 1;
                    }
                } else if s[i] == 2 {
                    if b > 0 {
                        dp[i + 1][a][b - 1] = 3;
                    }
                    if c > 0 {
                        dp[i + 1][a][b + 1] = 2;
                    }
                } else {
                    if c > 0 {
                        dp[i + 1][a + 1][b] = 1;
                    }
                    if a > 0 {
                        dp[i + 1][a - 1][b] = 3;
                    }
                }
            }
        }
    }

    for a in 0..=sum {
        for b in 0..=sum {
            if dp[n][a][b] != 0 {
                println!("Yes");
                let mut cur_a = a;
                let mut cur_b = b;
                let mut cur_n = n;
                let mut ans = vec![0; n];
                for _i in 0..n {
                    ans[cur_n - 1] = dp[cur_n][cur_a][cur_b];
                    if s[cur_n - 1] == 1 {
                        if dp[cur_n][cur_a][cur_b] == 1 {
                            cur_a -= 1;
                            cur_b += 1;
                        } else {
                            cur_a += 1;
                            cur_b -= 1;
                        }
                    } else if s[cur_n - 1] == 2 {
                        if dp[cur_n][cur_a][cur_b] == 2 {
                            cur_b -= 1;
                        } else {
                            cur_b += 1;
                        }
                    } else {
                        if dp[cur_n][cur_a][cur_b] == 3 {
                            cur_a += 1;
                        } else {
                            cur_a -= 1;
                        }
                    }
                    cur_n -= 1;
                }
                for a in &ans {
                    match a {
                        1 => println!("A"),
                        2 => println!("B"),
                        _ => println!("C"),
                    }
                }
                assert_eq!(cur_a, orig_a);
                assert_eq!(cur_b, orig_b);
                return;
            }
        }
    }
    println!("No");
}


While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $$$a_1, a_2, \ldots, a_n$$$ to $$$-a_1, -a_2, \ldots, -a_n$$$. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $$$5\,000$$$ and after every operation no variable can have an absolute value greater than $$$10^{18}$$$. William can perform actions of two types for two chosen variables with indices $$$i$$$ and $$$j$$$, where $$$i < j$$$:  Perform assignment $$$a_i = a_i + a_j$$$  Perform assignment $$$a_j = a_j - a_i$$$  William wants you to develop a strategy that will get all the internal variables to the desired values.

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

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

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

    let t = lines.next().unwrap().parse::<usize>().unwrap();

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

        let mut a = Vec::with_capacity(n);

        let s = lines.next().unwrap();
        let it = s.split_whitespace().map(|s| s.parse::<i64>().unwrap());

        a.extend(it);

        writeln!(&mut output, "{}", 3 * n).unwrap();

        for i in 0..n / 2 {
            writeln!(&mut output, "{} {} {}", 2, 2 * i + 1, 2 * i + 2).unwrap();
            writeln!(&mut output, "{} {} {}", 1, 2 * i + 1, 2 * i + 2).unwrap();
            writeln!(&mut output, "{} {} {}", 1, 2 * i + 1, 2 * i + 2).unwrap();
            writeln!(&mut output, "{} {} {}", 2, 2 * i + 1, 2 * i + 2).unwrap();
            writeln!(&mut output, "{} {} {}", 1, 2 * i + 1, 2 * i + 2).unwrap();
            writeln!(&mut output, "{} {} {}", 1, 2 * i + 1, 2 * i + 2).unwrap();
        }
    }
}


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

int solution() {
  long long int n;
  long long int m;
  long long int q = 0;
  scanf("%lld", &n);
  scanf("%lld", &m);
  long long int x[m];
  long long int i;
  long long int b = 0;
  for (i = 0; i < m; i++) {
    scanf("%lld", &x[i]);
  }
  b += x[q];
  q++;
  if (q >= m) {
    b--;
    printf("%lld", b);
    return 0;
  }
  while (1) {
    if (x[q] > x[q - 1] && q != 0) {
      b += x[q] - x[q - 1];
    }
    if (x[q] < x[q - 1] && q != 0) {
      b += n - x[q - 1];
      b += x[q];
    }
    if (x[q] == x[q + 1] && q + 1 < m) {
      q++;
    }
    q++;
    if (q >= m) {
      break;
    }
  }
  b--;
  printf("%lld", b);
}

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

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

    let words: Vec<i64> = line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = words[0];

    let mut line = String::new();

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

    let a: Vec<i64> = line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let mut last = 1;
    let mut answer = 0;

    for house in a {
        answer += (n + house - last) % n;
        last = house;
    }

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


Score : <var>100</var> points

Problem Statement

There is a hotel with the following accommodation fee:

<var>X</var> yen (the currency of Japan) per night, for the first <var>K</var> nights

<var>Y</var> yen per night, for the <var>(K+1)</var>-th and subsequent nights

Tak is staying at this hotel for <var>N</var> consecutive nights.
Find his total accommodation fee.

Constraints

<var>1 \leq N, K \leq 10000</var>

<var>1 \leq Y < X \leq 10000</var>

<var>N,\,K,\,X,\,Y</var> are integers.

Input

The input is given from Standard Input in the following format:

<var>N</var>
<var>K</var>
<var>X</var>
<var>Y</var>

Output

Print Tak's total accommodation fee.

Sample Input 1

5
3
10000
9000

Sample Output 1

48000

The accommodation fee is as follows:

<var>10000</var> yen for the <var>1</var>-st night

<var>10000</var> yen for the <var>2</var>-nd night

<var>10000</var> yen for the <var>3</var>-rd night

<var>9000</var> yen for the <var>4</var>-th night

<var>9000</var> yen for the <var>5</var>-th night

Thus, the total is <var>48000</var> yen.

Sample Input 2

2
3
10000
9000

Sample Output 2

20000

int solution(void) {
  int N = 0;
  int K = 0;
  int X = 0;
  int Y = 0;
  int A = 0;

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

  if (N > K) {
    A = K * X + (N - K) * Y;
  } else {
    A = N * X;
  }

  printf("%d\n", A);
}

fn solution() {
    let mut n_str = String::new();
    let mut k_str = String::new();
    let mut x_str = String::new();
    let mut y_str = String::new();

    io::stdin().read_line(&mut n_str).expect("");
    io::stdin().read_line(&mut k_str).expect("");
    io::stdin().read_line(&mut x_str).expect("");
    io::stdin().read_line(&mut y_str).expect("");

    let n: u32 = n_str.trim().parse().expect("");
    let k: u32 = k_str.trim().parse().expect("");
    let x: u32 = x_str.trim().parse().expect("");
    let y: u32 = y_str.trim().parse().expect("");

    let to_k = x * if n > k { k } else { n };
    let from_k = y * n.saturating_sub(k);

    println!("{}", to_k + from_k);
}


Polycarp has $$$x$$$ of red and $$$y$$$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $$$a$$$ red candies and $$$b$$$ blue candies, or $$$a$$$ blue candies and $$$b$$$ red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$, and $$$b = 2$$$, then Polycarp can make three gift sets:   In the first set there will be $$$5$$$ red candies and $$$2$$$ blue candies;  In the second set there will be $$$5$$$ blue candies and $$$2$$$ red candies;  In the third set will be $$$5$$$ blue candies and $$$2$$$ red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.

int solution() {
  int t;

  scanf("%d", &t);
  while (t--) {
    int x;
    int y;
    int a;
    int b;
    int lower;
    int upper;
    int tmp;

    scanf("%d%d%d%d", &x, &y, &a, &b);
    if (a > b) {
      tmp = a, a = b, b = tmp;
    }
    lower = 0, upper = 0x3f3f3f3f;
    while (upper - lower > 1) {
      int k = (lower + upper) / 2;
      long long x_ = x - (long long)a * k;
      long long y_ = y - (long long)a * k;

      if (x_ < 0 || y_ < 0) {
        upper = k;
        continue;
      }
      if (a == b) {
        lower = k;
        continue;
      }
      if (x_ / (b - a) + y_ / (b - a) >= k) {
        lower = k;
      } else {
        upper = k;
      }
    }
    printf("%d\n", lower);
  }
  return 0;
}

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

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

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

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

    'cases: for case_index in 1..=t {
        let log = case_index == 5;

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

        let x = it.next().unwrap();
        let y = it.next().unwrap();
        let a = it.next().unwrap();
        let b = it.next().unwrap();

        let ans = if a == b {
            std::cmp::min(x, y) / a
        } else {
            let (a, b) = if a < b { (a, b) } else { (b, a) };
            let mut l = 0;
            let mut r = std::cmp::min(x, y) + 1;

            while l < r {
                let n = (l + r) / 2;

                let xb = (n * b - x - 1).div_euclid(b - a) + 1;
                let lb = std::cmp::max(0, xb);

                let yb = (y - n * a).div_euclid(b - a);
                let ub = std::cmp::min(n, yb);

                if lb <= ub {
                    l = n + 1;
                } else {
                    r = n;
                }
            }

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


未熟者の数式

博士 : ピーター君、ついにやったよ。

ピーター : またですか。今度はどんなくだらない発明ですか。

博士 : ついに数式を計算機で処理する画期的な方法を思いついたんだ。この表をみてごらん。

通常の記法	博士の「画期的な」記法

1 + 2	1 2 +

3 * 4 + 7	3 4 * 7 +

10 / ( 2 - 12 )		10 2 12 - /

( 3 - 4 ) * ( 7 + 2 * 3 )	3 4 - 7 2 3 * + *

ピーター : はぁ。

博士 : ふっふっふ。これだけでは、未熟者の君には何のことだかわからないだろうねえ。ここからが肝心なんじゃ。

ピーター : っていうか・・・。

博士 : 計算機にはスタックというデータ構造があることは君も知っているね。ほれ、「先入れ後出し」のあれじゃよ。

ピーター : はい。知ってますが、あの・・・。

博士 : この画期的な記法はあのスタックを使うんじゃ。例えばこの 10 2 12 - / だが、次のように処理する。

処理対象	10	2	12	-	/

        	↓	↓	↓	↓2-12	↓10/-10

スタック

.

.

10

.

2

10

12

2

10

.

-10

10

.

.

-1

博士 : どうじゃな。括弧も演算子の優先順位も気にする必要がないじゃろう？語順も「10 を 2 から 12 を引いたもので割る。」となり、何となく彼の極東の島国の言葉、日本語と似ておるじゃろうて。
       この画期的な発明さえあれば、我が研究室は安泰じゃて。ファファファ。

ピーター : っていうか博士。これって日本にいたとき会津大学の基礎コースで習いましたよ。「逆ポーランド記法」とかいって、みんな簡単にプログラムしてました。

博士 : ・・・。

ということで、ピーター君に変わって博士に、このプログラムを教える事になりました。「逆ポーランド記法」で書かれた数式を入力とし、計算結果を出力するプログラムを作成してください。

入力

複数のデータセットが与えられます。各データセットでは、逆ポーランド記法による数式（整数と演算記号が空白文字１文字（半角）で区切られた80文字以内の文字列）が １ 行に与えられます。
ある値を 0 や 0 に限りなく近い値で割るような数式は与えられません。

データセットの数は 50 を超えません。

出力

各データセットごとに、計算結果（実数）を１行に出力してください。なお、計算結果は 0.00001 以下の誤差を含んでもよい。

Sample Input

10 2 12 - /
3 4 - 7 2 3 * + *
-1 -2 3 + +

Output for the Sample Input

-1.000000
-13.000000
0.000000

int solution(void) {
  double stack[200];
  char temp[100];
  int stackptr = 0;
  while (1) {
    if (scanf("%s", temp) == -1) {
      break;
    }
    if (strcmp(temp, "+") == 0) {
      if (stackptr < 2) {
        return 1;
      }
      stack[stackptr - 2] += stack[stackptr - 1];
      stackptr--;
    } else if (strcmp(temp, "-") == 0) {
      if (stackptr < 2) {
        return 1;
      }
      stack[stackptr - 2] -= stack[stackptr - 1];
      stackptr--;
    } else if (strcmp(temp, "*") == 0) {
      if (stackptr < 2) {
        return 1;
      }
      stack[stackptr - 2] *= stack[stackptr - 1];
      stackptr--;
    } else if (strcmp(temp, "/") == 0) {
      if (stackptr < 2) {
        return 1;
      }
      if (stack[stackptr - 1] == 0) {
        return 1;
      }
      stack[stackptr - 2] /= stack[stackptr - 1];
      stackptr--;
    } else {
      stack[stackptr] = atof(temp);
      stackptr++;
    }
    if (getchar() == '\n') {
      if (stackptr != 1) {
        return 1;
      }
      printf("%f\n", stack[0]);
      stackptr = 0;
    }
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();

    for l in stdin.lock().lines() {
        let mut stack: Vec<f64> = vec![];
        for token in l.unwrap().split_whitespace() {
            match token.parse::<f64>() {
                Ok(x) => stack.push(x),
                _ => {
                    let y = stack.pop().unwrap();
                    let x = stack.pop().unwrap();
                    stack.push(match token {
                        "+" => x + y,
                        "-" => x - y,
                        "*" => x * y,
                        _ => x / y,
                    })
                }
            }
        }
        println!("{}", stack[0]);
    }
}


In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch, which bottom is pi-th inflorescence and pi < i.Once tree starts fruiting, there appears exactly one apple in each inflorescence. The same moment as apples appear, they start to roll down along branches to the very base of tree. Each second all apples, except ones in first inflorescence simultaneously roll down one branch closer to tree base, e.g. apple in a-th inflorescence gets to pa-th inflorescence. Apples that end up in first inflorescence are gathered by Arcady in exactly the same moment. Second peculiarity of this tree is that once two apples are in same inflorescence they annihilate. This happens with each pair of apples, e.g. if there are 5 apples in same inflorescence in same time, only one will not be annihilated and if there are 8 apples, all apples will be annihilated. Thus, there can be no more than one apple in each inflorescence in each moment of time.Help Arcady with counting number of apples he will be able to collect from first inflorescence during one harvest.

int solution(void) {
  int n;
  int sum = 0;
  int maxlvl = 0;
  int parent;

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

  int p[n];
  int lvl[n];
  int c[n];
  lvl[0] = 0;
  for (int i = 1; i < n; i++) {
    scanf("%d", &parent);
    p[i] = parent - 1;
    c[i] = 0;
    lvl[i] = lvl[p[i]] + 1;
    if (lvl[i] > maxlvl) {
      maxlvl = lvl[i];
    }
  }
  int ranges[maxlvl + 1];
  for (int i = 0; i <= maxlvl; i++) {
    ranges[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    ranges[lvl[i]] += 1;
  }
  for (int i = 0; i <= maxlvl; i++) {
    sum += ranges[i] % 2;
  }

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

  return 0;
}

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

    let mut input = String::new();

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

    let mut it = input.split_whitespace();

    let n: usize = it.next().unwrap().parse().unwrap();

    let cll = it.map(|x| x.parse::<usize>().unwrap()).enumerate().fold(
        vec![Vec::new(); n],
        |mut acc, (i, x)| {
            acc[x - 1].push(i + 1);
            acc
        },
    );

    use std::collections::VecDeque;

    let mut queue = VecDeque::new();
    queue.push_back(0);

    let mut dl = vec![0; n];

    while let Some(cur) = queue.pop_front() {
        for &c in &cll[cur] {
            dl[c] = dl[cur] + 1;
            queue.push_back(c);
        }
    }

    let dcl = dl.into_iter().fold(vec![0; n], |mut acc, x| {
        acc[x] += 1;
        acc
    });

    let ans = dcl.into_iter().map(|x| x % 2).sum::<usize>();

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


The city of Fishtopia can be imagined as a grid of $$$4$$$ rows and an odd number of columns. It has two main villages; the first is located at the top-left cell $$$(1,1)$$$, people who stay there love fishing at the Tuna pond at the bottom-right cell $$$(4, n)$$$. The second village is located at $$$(4, 1)$$$ and its people love the Salmon pond at $$$(1, n)$$$.The mayor of Fishtopia wants to place $$$k$$$ hotels in the city, each one occupying one cell. To allow people to enter the city from anywhere, hotels should not be placed on the border cells.A person can move from one cell to another if those cells are not occupied by hotels and share a side.Can you help the mayor place the hotels in a way such that there are equal number of shortest paths from each village to its preferred pond?

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

    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();

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

    let k_even = |k| {
        println!("YES");
        let mut grid = String::new();
        for y in 0..4 {
            for x in 0..n {
                if 0 < y && y < 3 && 0 < x && x <= k / 2 {
                    grid.push('#');
                } else {
                    grid.push('.');
                }
            }
            grid.push('\n');
        }
        print!("{}", grid);
    };

    let k_odd = |k| {
        if k < n - 2 {
            let mut grid = String::new();

            for _ in 0..n {
                grid.push('.');
            }
            grid.push('\n');

            let t = n - 2 - k;
            let t0 = t / 2;
            grid.push('.');
            for _ in 0..t0 {
                grid.push('.');
            }
            for _ in t0..n - 2 - t0 {
                grid.push('#');
            }
            for _ in 0..t0 {
                grid.push('.');
            }
            grid.push('.');
            grid.push('\n');

            for _ in 0..n {
                grid.push('.');
            }
            grid.push('\n');

            for _ in 0..n {
                grid.push('.');
            }
            grid.push('\n');
            print!("YES\n{}", grid);
            std::process::exit(0);
        }

        let mut grid = String::new();

        for _ in 0..n {
            grid.push('.');
        }
        grid.push('\n');

        grid.push('.');
        for _ in 0..n - 2 {
            grid.push('#');
        }
        grid.push('.');
        grid.push('\n');

        grid.push('.');
        let t = k + 2 - n;
        let t0 = t / 2;
        for _ in 0..t0 {
            grid.push('#');
        }
        for _ in t0..n - 2 - t0 {
            grid.push('.');
        }
        for _ in 0..t0 {
            grid.push('#');
        }
        grid.push('.');
        grid.push('\n');

        for _ in 0..n {
            grid.push('.');
        }
        grid.push('\n');

        print!("YES\n{}", grid);
    };

    match k % 2 {
        0 => k_even(k),
        1 => k_odd(k),
        _ => unreachable!(),
    }
}


Score : <var>100</var> points

Problem Statement

Given is a string <var>S</var> representing the day of the week today.

<var>S</var> is SUN, MON, TUE, WED, THU, FRI, or SAT, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.

After how many days is the next Sunday (tomorrow or later)?

Constraints

<var>S</var> is SUN, MON, TUE, WED, THU, FRI, or SAT.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the number of days before the next Sunday.

Sample Input 1

SAT

Sample Output 1

1

It is Saturday today, and tomorrow will be Sunday.

Sample Input 2

SUN

Sample Output 2

7

It is Sunday today, and seven days later, it will be Sunday again.

fn solution() {
    let mut s = String::new();
    let days = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
    std::io::stdin().read_line(&mut s).ok();
    s = s.trim().to_string();
    for (i, d) in days.iter().enumerate() {
        if s == d.to_string() {
            println!("{}", 7 - i);
        }
    }
}


Score : <var>100</var> points

Problem Statement

Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.

The vacation consists of <var>N</var> days.
For each <var>i</var> (<var>1 \leq i \leq N</var>), Taro will choose one of the following activities and do it on the <var>i</var>-th day:

A: Swim in the sea. Gain <var>a_i</var> points of happiness.

B: Catch bugs in the mountains. Gain <var>b_i</var> points of happiness.

C: Do homework at home. Gain <var>c_i</var> points of happiness.

As Taro gets bored easily, he cannot do the same activities for two or more consecutive days.

Find the maximum possible total points of happiness that Taro gains.

Constraints

All values in input are integers.

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

<var>1 \leq a_i, b_i, c_i \leq 10^4</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>b_1</var> <var>c_1</var>
<var>a_2</var> <var>b_2</var> <var>c_2</var>
<var>:</var>
<var>a_N</var> <var>b_N</var> <var>c_N</var>

Output

Print the maximum possible total points of happiness that Taro gains.

Sample Input 1

3
10 40 70
20 50 80
30 60 90

Sample Output 1

210

If Taro does activities in the order C, B, C, he will gain <var>70 + 50 + 90 = 210</var> points of happiness.

Sample Input 2

1
100 10 1

Sample Output 2

100

Sample Input 3

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

Sample Output 3

46

Taro should do activities in the order C, A, B, A, C, B, A.

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let n: usize = input.trim().parse().unwrap();
    let costs: Vec<Vec<usize>> = (0..n)
        .map(|_| {
            input.clear();
            io::stdin().read_line(&mut input).unwrap();
            input
                .split_whitespace()
                .map(|e| e.parse().unwrap())
                .collect()
        })
        .collect();

    let mut tmp = vec![[0; 3]; n];
    tmp[0][0] = costs[0][0];
    tmp[0][1] = costs[0][1];
    tmp[0][2] = costs[0][2];
    for i in 1..n {
        tmp[i][0] = costs[i][0] + cmp::max(tmp[i - 1][1], tmp[i - 1][2]);
        tmp[i][1] = costs[i][1] + cmp::max(tmp[i - 1][2], tmp[i - 1][0]);
        tmp[i][2] = costs[i][2] + cmp::max(tmp[i - 1][0], tmp[i - 1][1]);
    }
    println!("{}", tmp[n - 1].into_iter().max().unwrap());
}


Score : <var>400</var> points

Problem Statement

Given is a positive integer <var>N</var>.

Find the number of pairs <var>(A, B)</var> of positive integers not greater than <var>N</var> that satisfy the following condition:

When <var>A</var> and <var>B</var> are written in base ten without leading zeros, the last digit of <var>A</var> is equal to the first digit of <var>B</var>, and the first digit of <var>A</var> is equal to the last digit of <var>B</var>.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer.

Sample Input 1

25

Sample Output 1

17

The following <var>17</var> pairs satisfy the condition: <var>(1,1)</var>, <var>(1,11)</var>, <var>(2,2)</var>, <var>(2,22)</var>, <var>(3,3)</var>, <var>(4,4)</var>, <var>(5,5)</var>, <var>(6,6)</var>, <var>(7,7)</var>, <var>(8,8)</var>, <var>(9,9)</var>, <var>(11,1)</var>, <var>(11,11)</var>, <var>(12,21)</var>, <var>(21,12)</var>, <var>(22,2)</var>, and <var>(22,22)</var>.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

100

Sample Output 3

108

Sample Input 4

2020

Sample Output 4

40812

Sample Input 5

200000

Sample Output 5

400000008

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let n: usize = s.trim().parse().unwrap();
    let mut mp = std::collections::HashMap::<(usize, usize), u64>::new();
    let mut ans = 0u64;
    for i in 1..n + 1 {
        let k2 = i % 10;
        let mut k1 = i;
        while k1 >= 10 {
            k1 /= 10;
        }
        let cnt = mp.entry((k1, k2)).or_insert(0);
        *cnt += 1;
    }
    for i in 1..10 {
        for j in 1..10 {
            if let (Some(val1), Some(val2)) = (mp.get(&(i, j)), mp.get(&(j, i))) {
                ans += val1 * val2
            }
        }
    }
    println!("{}", ans);
}


There are $$$n$$$ bags with candies, initially the $$$i$$$-th bag contains $$$i$$$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $$$m$$$ such that $$$1 \le m \le 1000$$$Perform $$$m$$$ operations. In the $$$j$$$-th operation, you will pick one bag and add $$$j$$$ candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize $$$m$$$.If there are several valid sequences, you can output any.

fn solution() {
    let reader = io::stdin();

    let mut line = String::new();
    reader.read_line(&mut line).expect("Missing t");
    let t: i32 = line.trim().parse().expect("t is not a number");

    for _n in 0..t {
        let mut test_case_line = String::new();
        reader
            .read_line(&mut test_case_line)
            .expect("Missing number");
        let n: i32 = test_case_line.trim().parse().expect("n_i in not a number");

        println!("{}", n);
        for i in 0..n {
            print!("{} ", i + 1);
        }
        println!();
    }
}


Score : <var>500</var> points

Problem Statement

On a two-dimensional plane, there are <var>m</var> lines drawn parallel to the <var>x</var> axis, and <var>n</var> lines drawn parallel to the <var>y</var> axis.
Among the lines parallel to the <var>x</var> axis, the <var>i</var>-th from the bottom is represented by <var>y = y_i</var>.
Similarly, among the lines parallel to the <var>y</var> axis, the <var>i</var>-th from the left is represented by <var>x = x_i</var>.

For every rectangle that is formed by these lines, find its area, and print the total area modulo <var>10^9+7</var>.

That is, for every quadruple <var>(i,j,k,l)</var> satisfying <var>1\leq i < j\leq n</var> and <var>1\leq k < l\leq m</var>, find the area of the rectangle formed by the lines <var>x=x_i</var>, <var>x=x_j</var>, <var>y=y_k</var> and <var>y=y_l</var>, and print the sum of these areas modulo <var>10^9+7</var>.

Constraints

<var>2 \leq n,m \leq 10^5</var>

<var>-10^9 \leq x_1 < ... < x_n \leq 10^9</var>

<var>-10^9 \leq y_1 < ... < y_m \leq 10^9</var>

<var>x_i</var> and <var>y_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>n</var> <var>m</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_n</var>
<var>y_1</var> <var>y_2</var> <var>...</var> <var>y_m</var>

Output

Print the total area of the rectangles, modulo <var>10^9+7</var>.

Sample Input 1

3 3
1 3 4
1 3 6

Sample Output 1

60

The following figure illustrates this input:

The total area of the nine rectangles A, B, ..., I shown in the following figure, is <var>60</var>.

Sample Input 2

6 5
-790013317 -192321079 95834122 418379342 586260100 802780784
-253230108 193944314 363756450 712662868 735867677

Sample Output 2

835067060

int solution(void) {
  int numx;
  int numy;
  scanf("%d %d", &numx, &numy);
  int zahyou_x[numx];
  int zahyou_y[numy];
  for (int i = 0; i < numx; i++) {
    scanf("%d", &zahyou_x[i]);
  }
  for (int i = 0; i < numy; i++) {
    scanf("%d", &zahyou_y[i]);
  }
  long long int x_sum = 0;
  long long int y_sum = 0;
  for (int i = 0; i < numx; i++) {
    x_sum = (x_sum + (long)zahyou_x[i] * (i * 2 - numx + 1)) % 1000000007;
  }
  for (int i = 0; i < numy; i++) {
    y_sum = (y_sum + (long)zahyou_y[i] * (i * 2 - numy + 1)) % 1000000007;
  }
  printf("%lld\n", (x_sum * y_sum) % 1000000007);
  return 0;
}

fn solution() {
    input! {
        N: usize,
        M: usize,
        X: [i64; N],
        Y: [i64; M],
    }
    let mut x = 0;
    let mut y = 0;
    let modulo = 1_000_000_007;
    for i in 0..N {
        x += X[i] * i as i64 - X[i] * (N - i - 1) as i64;
    }
    for i in 0..M {
        y += Y[i] * i as i64 - Y[i] * (M - i - 1) as i64;
    }
    x %= modulo;
    y %= modulo;
    println!("{}", x * y % modulo);
}


Score : <var>200</var> points

Problem Statement

La Confiserie d'ABC sells cakes at <var>4</var> dollars each and doughnuts at <var>7</var> dollars each.
Determine if there is a way to buy some of them for exactly <var>N</var> dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.

Constraints

<var>N</var> is an integer between <var>1</var> and <var>100</var>, inclusive.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If there is a way to buy some cakes and some doughnuts for exactly <var>N</var> dollars, print Yes; otherwise, print No.

Sample Input 1

11

Sample Output 1

Yes

If you buy one cake and one doughnut, the total will be <var>4 + 7 = 11</var> dollars.

Sample Input 2

40

Sample Output 2

Yes

If you buy ten cakes, the total will be <var>4 \times 10 = 40</var> dollars.

Sample Input 3

3

Sample Output 3

No

The prices of cakes (<var>4</var> dollars) and doughnuts (<var>7</var> dollars) are both higher than <var>3</var> dollars, so there is no such way.

int solution() {
  int n = 0;
  scanf("%d", &n);
  for (int i = 0; i <= n / 4; i++) {
    int buf = n - (i * 4);
    if (buf % 7 == 0) {
      printf("Yes\n");
      return 0;
    }
  }
  printf("No\n");
  return 0;
}

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

    let N: i32 = buf.trim_end().parse().unwrap();

    let mut ok = false;
    'a: for x in 0..100 {
        for y in 0..100 {
            if N == 7 * x + 4 * y {
                ok = true;
                break 'a;
            }
        }
    }

    if ok {
        println!("Yes")
    } else {
        println!("No")
    }
}


Lord Omkar would like to have a tree with $$$n$$$ nodes ($$$3 \le n \le 10^5$$$) and has asked his disciples to construct the tree. However, Lord Omkar has created $$$m$$$ ($$$\mathbf{1 \le m < n}$$$) restrictions to ensure that the tree will be as heavenly as possible. A tree with $$$n$$$ nodes is an connected undirected graph with $$$n$$$ nodes and $$$n-1$$$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree:   A restriction consists of $$$3$$$ pairwise distinct integers, $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a,b,c \le n$$$). It signifies that node $$$b$$$ cannot lie on the simple path between node $$$a$$$ and node $$$c$$$. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int m;
    int arr[100001] = {0};
    scanf("%d%d", &n, &m);
    int a[m];
    int b[m];
    int c[m];
    for (int i = 0; i < m; i++) {
      scanf("%d %d %d", &a[i], &b[i], &c[i]);
      arr[b[i]] = 1;
    }
    int index = 0;
    for (int i = 1; i <= n; i++) {
      if (arr[i] == 0) {
        index = i;
        break;
      }
    }
    for (int i = 1; i <= n; i++) {
      if (i != index) {
        printf("%d %d\n", i, index);
      }
    }
  }
  return 0;
}

fn solution() -> io::Result<()> {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s)?;
    let mut it = s.split_whitespace().map(|s| s.to_string());
    let t: usize = it.next().unwrap().parse().unwrap();
    let mut out = String::new();
    for _case in 1..=t {
        let n: usize = it.next().unwrap().parse().unwrap();
        let m: usize = it.next().unwrap().parse().unwrap();
        let mut free = vec![true; n];
        for _ in 0..m {
            let _a: usize = it.next().unwrap().parse().unwrap();
            let b: usize = it.next().unwrap().parse().unwrap();
            let _c: usize = it.next().unwrap().parse().unwrap();
            free[b - 1] = false;
        }
        for i in 0..n {
            if free[i] {
                for j in 0..n {
                    if j != i {
                        let ans = format!("{} {}\n", i + 1, j + 1);
                        out.push_str(ans.as_str());
                    }
                }
                break;
            }
        }
    }
    print!("{}", out);
    Ok(())
}


Score : <var>300</var> points

Problem Statement

There is an empty array.
The following <var>N</var> operations will be performed to insert integers into the array.
In the <var>i</var>-th operation <var>(1≤i≤N)</var>, <var>b_i</var> copies of an integer <var>a_i</var> are inserted into the array.
Find the <var>K</var>-th smallest integer in the array after the <var>N</var> operations.
For example, the <var>4</var>-th smallest integer in the array <var>\{1,2,2,3,3,3\}</var> is <var>3</var>.

Constraints

<var>1≤N≤10^5</var>

<var>1≤a_i,b_i≤10^5</var>

<var>1≤K≤b_1…+…b_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>b_1</var>
<var>:</var>
<var>a_N</var> <var>b_N</var>

Output

Print the <var>K</var>-th smallest integer in the array after the <var>N</var> operations.

Sample Input 1

3 4
1 1
2 2
3 3

Sample Output 1

3

The resulting array is the same as the one in the problem statement.

Sample Input 2

10 500000
1 100000
1 100000
1 100000
1 100000
1 100000
100000 100000
100000 100000
100000 100000
100000 100000
100000 100000

Sample Output 2

1

int solution() {
  long long N;
  long long K;
  long long sum = 0;
  long long ans = -1;
  scanf("%lld%lld", &N, &K);
  long long a[N];
  long long b[N];
  for (long long i = 0; i < N; i++) {
    scanf("%lld%lld", &a[i], &b[i]);
  }

  long long h = N;
  long long swapped = 0;
  while (h > 1 || swapped == 1) {
    if (h > 1) {
      h = h * 10 / 13;
    }
    swapped = 0;
    for (long long i = 0; i < N - h; i++) {
      if (a[i] > a[i + h]) {
        long long tmp = a[i];
        a[i] = a[i + h];
        a[i + h] = tmp;
        tmp = b[i];
        b[i] = b[i + h];
        b[i + h] = tmp;
        swapped = 1;
      }
    }
  }

  for (long long i = 0; i < N; i++) {
    sum += b[i];
    if (sum >= K && ans == -1) {
      ans = i;
    }
  }
  printf("%lld\n", a[ans]);
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let mut h: HashMap<usize, usize> = HashMap::new();
    for _ in 0..v[0] {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let u: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
        let x = match h.get(&u[0]) {
            Some(x) => *x,
            None => 0,
        };
        h.insert(u[0], x + u[1]);
    }
    let mut k = h.keys().collect::<Vec<&usize>>();
    k.sort();
    let mut x = 0;
    for i in &k {
        x += *h.get(*i).unwrap();
        if x >= v[1] {
            println!("{}", *i);
            return;
        }
    }
}


お財布メタボ診断

４月に消費税が８％になってから、お財布が硬貨でパンパンになっていませんか。同じ金額を持ち歩くなら硬貨の枚数を少なくしたいですよね。硬貨の合計が１０００円以上なら、硬貨をお札に両替して、お財布のメタボ状態を解消できます。

お財布の中の硬貨の枚数が種類ごとに与えられたとき、硬貨をお札に両替できるかどうかを判定するプログラムを作成してください。

入力

入力は以下の形式で与えられる。

<var>c1</var> <var>c5</var> <var>c10</var> <var>c50</var> <var>c100</var> <var>c500</var>

入力は１行からなる。<var>c1</var>、<var>c5</var>、<var>c10</var>、<var>c50</var>、<var>c100</var>、<var>c500</var> (0 ≤ <var>c1, c5, c10, c50, c100, c500</var> ≤ 50) は、それぞれ、1円、5円、10円、50円、100円、500円硬貨の枚数を表す。

出力

硬貨をお札に両替できるなら1 を、そうでなければ 0 を１行に出力する。

入出力例

入力例１

3 1 4 0 4 1

 出力例１

0

入力例２

2 1 4 3 2 3

 出力例２

1

入力例３

21 5 9 3 1 1

出力例３

0

入力例４

2 4 3 3 3 1

 出力例４

1

入力例５

50 50 50 4 0 0

 出力例５

1

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

    let (c1, c5, c10, c50, c100, c500) = {
        let mut iter = input.split(' ').map(|s| s.parse::<u32>().unwrap());

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

    let c = c1 + c5 * 5 + c10 * 10 + c50 * 50 + c100 * 100 + c500 * 500;

    if c >= 1000 {
        println!("1");
    } else {
        println!("0");
    }
}


There is a graph of $$$n$$$ rows and $$$10^6 + 2$$$ columns, where rows are numbered from $$$1$$$ to $$$n$$$ and columns from $$$0$$$ to $$$10^6 + 1$$$:  Let's denote the node in the row $$$i$$$ and column $$$j$$$ by $$$(i, j)$$$.Initially for each $$$i$$$ the $$$i$$$-th row has exactly one obstacle — at node $$$(i, a_i)$$$. You want to move some obstacles so that you can reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph (you can't pass through obstacles). Moving one obstacle to an adjacent by edge free node costs $$$u$$$ or $$$v$$$ coins, as below:  If there is an obstacle in the node $$$(i, j)$$$, you can use $$$u$$$ coins to move it to $$$(i-1, j)$$$ or $$$(i+1, j)$$$, if such node exists and if there is no obstacle in that node currently.  If there is an obstacle in the node $$$(i, j)$$$, you can use $$$v$$$ coins to move it to $$$(i, j-1)$$$ or $$$(i, j+1)$$$, if such node exists and if there is no obstacle in that node currently.  Note that you can't move obstacles outside the grid. For example, you can't move an obstacle from $$$(1,1)$$$ to $$$(0,1)$$$. Refer to the picture above for a better understanding. Now you need to calculate the minimal number of coins you need to spend to be able to reach node $$$(n, 10^6+1)$$$ from node $$$(1, 0)$$$ by moving through edges of this graph without passing through obstacles.

int solution() {
  int t;
  scanf("%d", &t);

  for (int x = 0; x < t; ++x) {
    int n;
    int u;
    int v;
    scanf("%d %d %d", &n, &u, &v);

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

    short flag_2 = 0;
    short flag_1 = 0;

    for (int i = 1; i < n; ++i) {
      if (ar[i] - ar[i - 1] == -1 || ar[i] - ar[i - 1] == 1) {
        flag_1 = 1;
      } else if (ar[i] - ar[i - 1] <= -2 || ar[i] - ar[i - 1] >= 2) {
        flag_2 = 1;
        printf("0\n");
        break;
      }
    }

    if (flag_2 == 0 && flag_1 == 1) {
      if (u <= v) {
        printf("%d\n", u);
      } else {
        printf("%d\n", v);
      }
    } else if (flag_2 == 0 && flag_1 == 0) {
      if (u <= v) {
        printf("%lld\n", (long long int)(u + v));
      } else {
        printf("%lld\n", (long long int)(2 * v));
      }
    }
  }

  return 0;
}

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

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

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

    let t = lines.next().unwrap().parse::<usize>().unwrap();

    for _ in 0..t {
        let s = lines.next().unwrap();
        let mut it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());

        let _n = it.next().unwrap();
        let u = it.next().unwrap();
        let v = it.next().unwrap();

        let s = lines.next().unwrap();
        let mut it = s.split_whitespace().map(|s| s.parse::<i32>().unwrap());
        let mut a0 = it.next().unwrap();

        let mut m = 0;

        for a1 in it {
            let x = (a1 - a0).abs();
            if m < x {
                m = x;
            }
            a0 = a1;
        }

        use std::cmp::min;
        let x = min(u, v);
        let ans = match m {
            0 => x + v,
            1 => x,
            _ => 0,
        };

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


Alperen has two strings, $$$s$$$ and $$$t$$$ which are both initially equal to "a". He will perform $$$q$$$ operations of two types on the given strings:  $$$1 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$s$$$. In other words, $$$s := s + \underbrace{x + \dots + x}_{k \text{ times}}$$$.  $$$2 \;\; k \;\; x$$$ — Append the string $$$x$$$ exactly $$$k$$$ times at the end of string $$$t$$$. In other words, $$$t := t + \underbrace{x + \dots + x}_{k \text{ times}}$$$. After each operation, determine if it is possible to rearrange the characters of $$$s$$$ and $$$t$$$ such that $$$s$$$ is lexicographically smaller$$$^{\dagger}$$$ than $$$t$$$.Note that the strings change after performing each operation and don't go back to their initial states.$$$^{\dagger}$$$ Simply speaking, the lexicographical order is the order in which words are listed in a dictionary. A formal definition is as follows: string $$$p$$$ is lexicographically smaller than string $$$q$$$ if there exists a position $$$i$$$ such that $$$p_i < q_i$$$, and for all $$$j < i$$$, $$$p_j = q_j$$$. If no such $$$i$$$ exists, then $$$p$$$ is lexicographically smaller than $$$q$$$ if the length of $$$p$$$ is less than the length of $$$q$$$. For example, $$$\texttt{abdc} < \texttt{abe}$$$ and $$$\texttt{abc} < \texttt{abcd}$$$, where we write $$$p < q$$$ if $$$p$$$ is lexicographically smaller than $$$q$$$.

int solution() {
  int x;
  int y;
  int z;
  int i;
  int j;
  int k;
  int q;
  int a;
  int b;
  int c;
  int d;
  int n;
  int m;
  int t;
  char s[500001];

  scanf("%d", &t);
  while (t--) {
    long long cont[2][26] = {};
    cont[0][0] = cont[1][0] = 1;
    scanf("%d", &q);
    for (x = 0; x < q; x++) {
      scanf("%d %d %s", &d, &k, s), d--;
      m = strlen(s);
      for (y = 0; y < m; y++) {
        cont[d][s[y] - 'a'] += k;
      }

      for (z = 1; z < 26; z++) {
        if (cont[1][z]) {
          puts("YES");
          goto end;
        }
      }

      for (y = 1; y < 26; y++) {
        if (cont[0][y]) {
          puts("NO");
          goto end;
        }
      }

      printf(cont[0][0] < cont[1][0] ? "YES\n" : "NO\n");
    end:;
    }
  }
  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 q: usize = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        };

        let mut s_noa = 0;
        let mut t_noa = 0;
        let mut s_size = 1_i64;
        let mut t_size = 1_i64;

        for _ in 0..q {
            let (d, k, x): (usize, i64, Vec<char>) = {
                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(),
                    iter.next().unwrap().chars().collect(),
                )
            };

            let x_size = x.len() as i64;

            let mut noa = 0;
            for ss in x {
                if ss != 'a' {
                    noa = 1;
                }
            }

            if noa == 1 {
                if d == 1 {
                    s_noa = 1;
                } else {
                    t_noa = 1;
                }
            } else {
                if d == 1 {
                    s_size += x_size * k;
                } else {
                    t_size += x_size * k;
                }
            }

            if s_noa == 0 && t_noa == 0 {
                if s_size < t_size {
                    println!("YES");
                } else {
                    println!("NO");
                }
            } else if t_noa == 1 {
                println!("YES");
            } else {
                println!("NO");
            }
        }
    }
}


You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases.

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

    for _ in 0..q {
        input_line.clear();
        stdin.read_line(&mut input_line).unwrap();
        let splited = input_line.split_whitespace().collect::<Vec<_>>();
        let a = splited[0].parse::<i32>().unwrap();
        let b = splited[1].parse::<i32>().unwrap();
        let n = splited[2].parse::<i32>().unwrap();
        let s = splited[3].parse::<i32>().unwrap();

        if (s / n <= a && s % n <= b) || (s / n > a && s - a * n <= b) {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.

int solution(void) {
  int t;
  scanf("%d\n", &t);
  while (t--) {
    int n;
    int k;
    scanf("%d %d\n", &n, &k);
    char a[n + 1];
    scanf("%s\n", a);
    int arr[26] = {0};
    for (int i = 0; i < n; i++) {
      arr[a[i] - 'a']++;
    }
    int count = 0;
    for (int i = 0; i < 26; i++) {
      count += arr[i] / 2;
    }
    int m = (count / k);
    if (n >= (2 * m + 1) * k) {
      printf("%d\n", (2 * m) + 1);
    } else {
      printf("%d\n", 2 * m);
    }
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let mut s = input.split_whitespace();
    let t: u32 = s.next().unwrap().parse().unwrap();
    for _x in 0..t {
        input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        s = input.split_whitespace();
        let n: u32 = s.next().unwrap().parse().unwrap();
        let k: u32 = s.next().unwrap().parse().unwrap();
        let mut S = String::new();
        let mut cnt: [u32; 30] = [0; 30];
        io::stdin().read_line(&mut S).unwrap();
        for i in S.bytes() {
            let b: i32 = i as i32 - 97;
            if b < 0 {
                break;
            }
            cnt[b as usize] += 1;
        }
        let mut tot: u32 = 0;
        for i in 0..26 {
            tot += cnt[i] / 2;
        }
        let mut ans = tot / k * 2;
        if n - ans * k >= k {
            ans += 1;
        }
        println!("{}", ans);
    }
}


There is an array $$$a$$$ with $$$n-1$$$ integers. Let $$$x$$$ be the bitwise XOR of all elements of the array. The number $$$x$$$ is added to the end of the array $$$a$$$ (now it has length $$$n$$$), and then the elements are shuffled.You are given the newly formed array $$$a$$$. What is $$$x$$$? If there are multiple possible values of $$$x$$$, you can output any of them.

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

    printf("%d\n", a[0]);
  }
}

fn solution() {
    let mut content = String::new();
    io::stdin()
        .read_to_string(&mut content)
        .expect("Unable to read from stdin");

    let mut lines = content.lines();
    let num_tests: usize = lines.next().unwrap().parse().unwrap();
    for _ in 0..num_tests {
        let _n: usize = lines.next().unwrap().parse().unwrap();
        let arr: Vec<usize> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse::<usize>().unwrap())
            .collect();
        println!("{}", arr[0]);
    }
}


Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

int solution() {
  int x1 = 0;
  int y1 = 0;
  int x2 = 0;
  int y2 = 0;
  int side = 0;
  scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
  if (y1 == y2) {
    side = (x1 - x2);
    printf("%d %d %d %d", x1, y1 + side, x2, y2 + side);
  } else if (x1 == x2) {
    side = (y1 - y2);
    printf("%d %d %d %d", x2 + side, y2, x1 + side, y1);
  } else if ((abs(x1 - x2)) == (abs(y1 - y2))) {
    printf("%d %d %d %d", x2, y1, x1, y2);
  } else {
    printf("-1");
  }
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut s = buf.split_whitespace();
    let x1: i32 = s.next().unwrap().trim().parse().unwrap();
    let y1: i32 = s.next().unwrap().trim().parse().unwrap();
    let x2: i32 = s.next().unwrap().trim().parse().unwrap();
    let y2: i32 = s.next().unwrap().trim().parse().unwrap();
    if x1 == x2 {
        let a = y2 - y1;
        println!("{} {} {} {}", x1 + a, y1, x2 + a, y2);
    } else if y1 == y2 {
        let a = x2 - x1;
        println!("{} {} {} {}", x1, y1 + a, x2, y2 + a);
    } else if (x2 - x1).abs() == (y2 - y1).abs() {
        println!("{} {} {} {}", x1, y2, x2, y1);
    } else {
        println!("-1");
    }
}


Alice and Bob play the following game. Alice has a set $$$S$$$ of disjoint ranges of integers, initially containing only one range $$$[1, n]$$$. In one turn, Alice picks a range $$$[l, r]$$$ from the set $$$S$$$ and asks Bob to pick a number in the range. Bob chooses a number $$$d$$$ ($$$l \le d \le r$$$). Then Alice removes $$$[l, r]$$$ from $$$S$$$ and puts into the set $$$S$$$ the range $$$[l, d - 1]$$$ (if $$$l \le d - 1$$$) and the range $$$[d + 1, r]$$$ (if $$$d + 1 \le r$$$). The game ends when the set $$$S$$$ is empty. We can show that the number of turns in each game is exactly $$$n$$$.After playing the game, Alice remembers all the ranges $$$[l, r]$$$ she picked from the set $$$S$$$, but Bob does not remember any of the numbers that he picked. But Bob is smart, and he knows he can find out his numbers $$$d$$$ from Alice's ranges, and so he asks you for help with your programming skill.Given the list of ranges that Alice has picked ($$$[l, r]$$$), for each range, help Bob find the number $$$d$$$ that Bob has picked.We can show that there is always a unique way for Bob to choose his number for a list of valid ranges picked by Alice.

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).unwrap();
    let mut input = input.split_ascii_whitespace().flat_map(str::parse);
    let t = input.next().unwrap();
    let mut output = String::new();
    for _ in 0..t {
        let n = input.next().unwrap();
        let mut ivs = vec![];
        for _ in 0..n {
            let l = input.next().unwrap();
            let r = input.next().unwrap();
            ivs.push((l, r));
        }
        ivs.sort_unstable_by_key(|&(l, r)| r - l);
        let mut set: BTreeSet<_> = (1..=n).collect();
        for (l, r) in ivs {
            let d = *set.range(l..=r).next().unwrap();
            set.remove(&d);
            writeln!(output, "{} {} {}", l, r, d).unwrap();
        }
    }
    print!("{}", output);
}


Given a positive integer $$$k$$$, two arrays are called $$$k$$$-similar if:  they are strictly increasing;  they have the same length;  all their elements are positive integers between $$$1$$$ and $$$k$$$ (inclusive);  they differ in exactly one position. You are given an integer $$$k$$$, a strictly increasing array $$$a$$$ and $$$q$$$ queries. For each query, you are given two integers $$$l_i \leq r_i$$$. Your task is to find how many arrays $$$b$$$ exist, such that $$$b$$$ is $$$k$$$-similar to array $$$[a_{l_i},a_{l_i+1}\ldots,a_{r_i}]$$$.

int solution() {
  long long int n;
  long long int q;
  long long int k;
  scanf("%lld %lld %lld", &n, &q, &k);
  long long int a[n];
  long long int j;
  long long int l[q];
  long long int r[q];
  long long int ans = 0;
  for (j = 0; j < n; j++) {
    scanf("%lld", &a[j]);
  }
  for (j = 0; j < q; j++) {
    scanf("%lld %lld", &l[j], &r[j]);
    printf("%lld\n",
           1 + k - (2 * (r[j] - l[j] + 1)) + a[r[j] - 1] - a[l[j] - 1]);
  }
}

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

    let (n, q, k): (usize, i32, i32) = (sc.next(), sc.next(), sc.next());
    let mut arr: Vec<i32> = vec![0; n + 1];
    for i in 1..=n {
        arr[i] = sc.next();
    }
    let mut changes: Vec<i32> = vec![0; n + 1];
    for i in 2..n {
        changes[i] = changes[i - 1] + arr[i + 1] - arr[i - 1] - 2;
    }
    for _ in 0..q {
        let (l, r): (usize, usize) = (sc.next(), sc.next());
        let ans = if l == r {
            k - 1
        } else {
            changes[r - 1] - changes[l] + arr[l + 1] - 2 + k + 1 - arr[r - 1] - 2
        };
        writeln!(out, "{}", ans).unwrap();
    }
}


You still have partial information about the score during the historic football match. You are given a set of pairs $$$(a_i, b_i)$$$, indicating that at some point during the match the score was "$$$a_i$$$: $$$b_i$$$". It is known that if the current score is «$$$x$$$:$$$y$$$», then after the goal it will change to "$$$x+1$$$:$$$y$$$" or "$$$x$$$:$$$y+1$$$". What is the largest number of times a draw could appear on the scoreboard?The pairs "$$$a_i$$$:$$$b_i$$$" are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.

int solution() {
  int maxDraw = -1;
  int lastl = 0;
  int lastr = 0;
  int number = 0;
  scanf("%d", &number);
  int answer = 0;
  for (int i = 0; i < number; i++) {
    int maxLast = (lastl <= lastr) ? lastr : lastl;
    int left;
    int right;
    scanf("%d%d", &left, &right);
    int minCurrent = (left <= right) ? left : right;
    if (minCurrent < maxLast) {
      lastl = left;
      lastr = right;
      continue;
    }
    for (int i = maxLast; i <= minCurrent; i++) {
      if (i <= maxDraw) {
        continue;
      }
      answer += 1;
      maxDraw = i;
    }
    lastl = left;
    lastr = right;
  }
  printf("%d", answer);
  return 0;
}

fn solution() {
    let mut sin = String::new();
    std::io::stdin().read_line(&mut sin).expect("read error");
    let n = sin.trim().parse::<i32>().unwrap();

    let mut ret = 1;
    let (mut a, mut b) = (0, 0);
    let mut c;
    let mut d;
    for _ in 1..=n {
        sin.clear();
        std::io::stdin().read_line(&mut sin).expect("read error");
        let vi32: Vec<i32> = sin.split_whitespace().map(|c| c.parse().unwrap()).collect();
        c = vi32[0];
        d = vi32[1];
        ret += match min(c, d) - max(a, b) {
            x if x >= 0 => {
                if a == b {
                    x
                } else {
                    x + 1
                }
            }
            _ => 0,
        };
        a = c;
        b = d;
    }
    println!("{}", ret);
}


The 2050 volunteers are organizing the "Run! Chase the Rising Sun" activity. Starting on Apr 25 at 7:30 am, runners will complete the 6km trail around the Yunqi town.There are $$$n+1$$$ checkpoints on the trail. They are numbered by $$$0$$$, $$$1$$$, ..., $$$n$$$. A runner must start at checkpoint $$$0$$$ and finish at checkpoint $$$n$$$. No checkpoint is skippable — he must run from checkpoint $$$0$$$ to checkpoint $$$1$$$, then from checkpoint $$$1$$$ to checkpoint $$$2$$$ and so on. Look at the picture in notes section for clarification.Between any two adjacent checkpoints, there are $$$m$$$ different paths to choose. For any $$$1\le i\le n$$$, to run from checkpoint $$$i-1$$$ to checkpoint $$$i$$$, a runner can choose exactly one from the $$$m$$$ possible paths. The length of the $$$j$$$-th path between checkpoint $$$i-1$$$ and $$$i$$$ is $$$b_{i,j}$$$ for any $$$1\le j\le m$$$ and $$$1\le i\le n$$$.To test the trail, we have $$$m$$$ runners. Each runner must run from the checkpoint $$$0$$$ to the checkpoint $$$n$$$ once, visiting all the checkpoints. Every path between every pair of adjacent checkpoints needs to be ran by exactly one runner. If a runner chooses the path of length $$$l_i$$$ between checkpoint $$$i-1$$$ and $$$i$$$ ($$$1\le i\le n$$$), his tiredness is $$$$$$\min_{i=1}^n l_i,$$$$$$ i. e. the minimum length of the paths he takes.Please arrange the paths of the $$$m$$$ runners to minimize the sum of tiredness of them.

int solution(void) {
  int T;
  scanf("%d", &T);
  while (T--) {
    int n;
    int m;
    int M;
    int i;
    int j;
    int k;
    int l;
    int J;
    scanf("%d %d", &n, &m);
    M = m;
    long long int a[n][m];
    long long int b[n][m];
    long long int summin = 0;
    long long int t;
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        scanf("%lld", &a[i][j]);
      }
    }
    for (i = 0; i < n; i++) {
      for (j = 0; j < m - 1; j++) {
        int hmin = a[i][j];
        int lindex = j;
        for (k = j + 1; k < m; k++) {
          if (a[i][k] <= hmin) {
            hmin = a[i][k];
            lindex = k;
          }
        }
        a[i][lindex] = a[i][j];
        a[i][j] = hmin;
      }
    }
    for (j = 0; j < m; j++) {
      int min = 1000000001;
      int hindex = 0;
      for (i = 0; i < n; i++) {
        if (a[i][j] <= min) {
          min = a[i][j];
          hindex = i;
        }
      }
      for (i = 0; i < n; i++) {
        if (i != hindex) {
          t = a[i][j];
          a[i][j] = a[i][m - 1];
          a[i][m - 1] = t;
        }
      }
      for (i = 0; i < n; i++) {
        b[i][j] = a[i][j];
      }
      for (i = 0; i < n; i++) {
        for (J = j + 1; J < m - 1; J++) {
          int hmin = a[i][J];
          int lindex = J;
          for (k = J + 1; k < m; k++) {
            if (a[i][k] <= hmin) {
              hmin = a[i][k];
              lindex = k;
            }
          }
          a[i][lindex] = a[i][J];
          a[i][J] = hmin;
        }
      }
    }

    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        printf("%lld ", b[i][j]);
        if (j == m - 1) {
          printf("\n");
        }
      }
    }
  }
  return 0;
}

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

    use std::io::Write;
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    let t: usize = scan!(usize);
    for _ in 1..=t {
        let (n, m) = scan!(usize, usize);
        let mut edg = scan!([[i64; m]; n]);
        edg.iter_mut().for_each(|v| v.sort());

        use std::collections::BinaryHeap;

        let mut tri = BinaryHeap::<(i64, usize)>::new();
        for i in 0..m {
            tri.push((10i64.pow(18), i));
        }

        let mut ans = vec![vec![]; m];

        for v in edg {
            let mut nxt = BinaryHeap::<(i64, usize)>::new();
            for l in v {
                if let Some((c, i)) = tri.pop() {
                    nxt.push((c.min(l), i));
                    ans[i].push(l);
                }
            }
            tri = nxt;
        }

        for i in 0..n {
            for j in 0..m {
                print!("{} ", ans[j][i]);
            }
            print!("\n");
        }
    }
}


Score : <var>300</var> points

Problem Statement

Gotou just received a dictionary. However, he doesn't recognize the language used in the dictionary. He did some analysis on the dictionary and realizes that the dictionary contains all possible diverse words in lexicographical order.

A word is called diverse if and only if it is a nonempty string of English lowercase letters and all letters in the word are distinct. For example, atcoder, zscoder and agc are diverse words while gotou and connect aren't diverse words.

Given a diverse word <var>S</var>, determine the next word that appears after <var>S</var> in the dictionary, i.e. the lexicographically smallest diverse word that is lexicographically larger than <var>S</var>, or determine that it doesn't exist.

Let <var>X = x_{1}x_{2}...x_{n}</var> and <var>Y = y_{1}y_{2}...y_{m}</var> be two distinct strings. <var>X</var> is lexicographically larger than <var>Y</var> if and only if <var>Y</var> is a prefix of <var>X</var> or <var>x_{j} > y_{j}</var> where <var>j</var> is the smallest integer such that <var>x_{j} \neq y_{j}</var>.

Constraints

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

<var>S</var> is a diverse word.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the next word that appears after <var>S</var> in the dictionary, or -1 if it doesn't exist.

Sample Input 1

atcoder

Sample Output 1

atcoderb

atcoderb is the lexicographically smallest diverse word that is lexicographically larger than atcoder. Note that atcoderb is lexicographically smaller than b.

Sample Input 2

abc

Sample Output 2

abcd

Sample Input 3

zyxwvutsrqponmlkjihgfedcba

Sample Output 3

-1

This is the lexicographically largest diverse word, so the answer is -1.

Sample Input 4

abcdefghijklmnopqrstuvwzyx

Sample Output 4

abcdefghijklmnopqrstuvx

int solution() {
  char s[27];
  scanf("%s", s);
  int l = strlen(s);
  int alp[26] = {0};
  if (strcmp(s, "zyxwvutsrqponmlkjihgfedcba") == 0) {
    printf("-1");
    return 0;
  }

  if (l < 26) {
    for (int i = 0; i < l; i++) {
      alp[s[i] - 'a']++;
    }
    printf("%s", s);
    for (int i = 0; i < 26; i++) {
      if (alp[i] == 0) {
        printf("%c", 'a' + i);
        return 0;
      }
    }
  }
  int p;
  for (int i = 25; i > 0; i--) {
    if (s[i] - 'a' > s[i - 1] - 'a') {
      p = i - 1;
      break;
    }
  }
  for (int i = 0; i < p; i++) {
    alp[s[i] - 'a']++;
    printf("%c", s[i]);
  }
  for (int i = 0; i < 26; i++) {
    if (alp[i] == 0 && s[p] - 'a' < i) {
      printf("%c", 'a' + i);
      return 0;
    }
  }
  return 0;
}

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

    let ans = if S.len() < 26 {
        format!(
            "{}{}",
            S.iter().copied().collect::<String>(),
            (0..26)
                .map(|i| (b'a' + i) as char)
                .find(|c| !S.contains(c))
                .unwrap()
        )
    } else if let Some(i) = (0..25).rev().find(|&i| S[i] < S[i + 1]) {
        format!(
            "{}{}",
            S[..i].iter().copied().collect::<String>(),
            S.iter().rev().find(|&&c| S[i] < c).unwrap()
        )
    } else {
        "-1".to_string()
    };

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


You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.So the team is considered perfect if it includes at least one coder, at least one mathematician and it consists of exactly three members.You are a coach at a very large university and you know that $$$c$$$ of your students are coders, $$$m$$$ are mathematicians and $$$x$$$ have no specialization.What is the maximum number of full perfect teams you can distribute them into? Note that some students can be left without a team and each student can be a part of no more than one team.You are also asked to answer $$$q$$$ independent queries.

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

    for _ in 0..q {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");

        let mut input_iter = input.split_whitespace();
        let c = input_iter.next().unwrap().parse::<u32>().unwrap();
        let m = input_iter.next().unwrap().parse::<u32>().unwrap();
        let x = input_iter.next().unwrap().parse::<u32>().unwrap();

        let mean = (c + m + x) / 3;

        println!("{}", c.min(m).min(mean));
    }
}


Grading

  Write a program which reads a list of student test scores and evaluates the performance for each student.

  The test scores for a student include scores of the midterm examination <var>m</var> (out of 50), the final examination <var>f</var> (out of 50) and the makeup examination <var>r</var> (out of 100). If the student does not take the examination, the score is indicated by -1.

  The final performance of a student is evaluated by the following procedure:

If the student does not take the midterm or final examination, the student's grade shall be F.

If the total score of the midterm and final examination is greater than or equal to 80, the student's grade shall be A.

If the total score of the midterm and final examination is greater than or equal to 65 and less than 80, the student's grade shall be B.

If the total score of the midterm and final examination is greater than or equal to 50 and less than 65, the student's grade shall be C.

If the total score of the midterm and final examination is greater than or equal to 30 and less than 50, the student's grade shall be D. However, if the score of the makeup examination is greater than or equal to 50, the grade shall be C.

If the total score of the midterm and final examination is less than 30, the student's grade shall be F.

Input

  The input consists of multiple datasets. For each dataset, three integers <var>m</var>, <var>f</var> and <var>r</var> are given in a line.

  The input ends with three -1 for <var>m</var>, <var>f</var> and <var>r</var> respectively. Your program should not process for the terminal symbols.

The number of datasets (the number of students) does not exceed 50.

Output

  For each dataset, print the grade (A, B, C, D or F) in a line.

Sample Input

40 42 -1
20 30 -1
0 2 -1
-1 -1 -1

Sample Output

A
C
F

int solution(void) {
  student exam;
  while (1) {
    scanf("%d %d %d", &exam.midterm, &exam.final, &exam.make_up);
    if (exam.midterm == -1 && exam.final == -1 && exam.make_up == -1) {
      break;
    }
    if (exam.midterm == -1 || exam.final == -1 ||
        exam.midterm + exam.final < 30) {
      printf("F\n");
    } else if (exam.midterm + exam.final >= 80) {
      printf("A\n");
    } else if (exam.midterm + exam.final >= 65) {
      printf("B\n");
    } else if (exam.midterm + exam.final >= 50 ||
               (exam.midterm + exam.final >= 30 && exam.make_up >= 50)) {
      printf("C\n");
    } else {
      printf("D\n");
    }
  }
  return 0;
}

fn solution() {
    let scan = io::stdin();
    for line in scan.lock().lines() {
        let uline = line.unwrap();
        let vec: Vec<&str> = uline.split_whitespace().collect();
        let md: i32 = vec[0].parse().unwrap_or(0);
        let fi: i32 = vec[1].parse().unwrap_or(0);
        let mu: i32 = vec[2].parse().unwrap_or(0);
        if md == -1 && fi == -1 && mu == -1 {
            break;
        } else if md == -1 || fi == -1 {
            println!("F");
        } else {
            let sum = md + fi;
            if sum >= 80 {
                println!("A");
            } else if sum >= 65 {
                println!("B");
            } else if sum >= 50 {
                println!("C");
            } else if sum >= 30 {
                if mu >= 50 {
                    println!("C");
                } else {
                    println!("D");
                }
            } else {
                println!("F");
            }
        }
    }
}


There are n Imperial stormtroopers on the field. The battle field is a plane with Cartesian coordinate system. Each stormtrooper is associated with his coordinates (x, y) on this plane. Han Solo has the newest duplex lazer gun to fight these stormtroopers. It is situated at the point (x0, y0). In one shot it can can destroy all the stormtroopers, situated on some line that crosses point (x0, y0).Your task is to determine what minimum number of shots Han Solo needs to defeat all the stormtroopers.The gun is the newest invention, it shoots very quickly and even after a very large number of shots the stormtroopers don't have enough time to realize what's happening and change their location.

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

    let mut troopers = Vec::new();
    for _ in 0..n {
        troopers.push({
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                iter.next().unwrap().parse::<isize>().unwrap(),
                iter.next().unwrap().parse::<isize>().unwrap(),
            )
        });
    }

    let mut count: usize = 0;
    while let Some(trooper) = troopers.pop() {
        count += 1;

        let x1 = c0.0;
        let x2 = trooper.0;
        let y1 = c0.1;
        let y2 = trooper.1;

        let difx = x2 - x1;
        let dify = y2 - y1;

        troopers.retain(|(x, y)| (*x - x1) * dify != (*y - y1) * difx);
    }

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


You are given $$$n$$$ rectangles, each of height $$$1$$$. Each rectangle's width is a power of $$$2$$$ (i. e. it can be represented as $$$2^x$$$ for some non-negative integer $$$x$$$). You are also given a two-dimensional box of width $$$W$$$. Note that $$$W$$$ may or may not be a power of $$$2$$$. Moreover, $$$W$$$ is at least as large as the width of the largest rectangle.You have to find the smallest height of this box, such that it is able to fit all the given rectangles. It is allowed to have some empty space left in this box after fitting all the rectangles.You cannot rotate the given rectangles to make them fit into the box. Moreover, any two distinct rectangles must not overlap, i. e., any two distinct rectangles must have zero intersection area.See notes for visual explanation of sample input.

int solution() {
  int x;
  int y;
  int z;
  int w;
  int i;
  int j;
  int k;
  int a;
  int b;
  int c;
  int n;
  int m;
  int t;
  int mat[25];
  int res;
  scanf("%d", &t);
  while (t--) {
    scanf("%d %d", &n, &w);
    memset(mat, 0, sizeof(mat));
    res = 0;

    for (x = 0; x < n; x++) {
      scanf("%d", &a);
      for (y = 0; y <= 20; y++) {
        if (a & (1 << y)) {
          mat[y]++;
          break;
        }
      }
    }
    for (x = 20; x >= 0; x--) {
      while (mat[x]) {
        c = 0;
        res++;
        c += 1 << x;
        mat[x]--;
        y = x;
        while (y >= 0) {
          if (mat[y] && c + (1 << y) <= w) {
            c += 1 << y;
            mat[y]--;
          } else {
            y--;
          }
        }
      }
    }
    printf("%d\n", res);
  }
  return 0;
}

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

    use std::io::Write;
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    let t: usize = scan!(usize);
    for _ in 1..=t {
        let (n, w) = scan!(usize, u64);
        let a = scan!([u64; n]);
        let h = 20;
        let mut f = vec![0; h + 1];
        for &a in &a {
            for i in 0..=h {
                if (a >> i) & 1 == 1 {
                    f[i] += 1;
                }
            }
        }

        let mut r = n;
        let mut ans = 1;
        let mut avl = w;
        while r > 0 {
            let mut flag = false;
            for i in (0..=h).rev() {
                if f[i] > 0 && avl >= (1 << i) {
                    f[i] -= 1;
                    r -= 1;
                    avl -= 1 << i;
                    flag = true;
                    break;
                }
            }

            if !flag {
                ans += 1;
                avl = w;
            }
        }
        print!("{}", ans);
        print!("\n");
    }
}