Score : <var>100</var> points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is <var>D</var> meters away from Takahashi's house in <var>T</var> minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of <var>S</var> meters per minute.

Will he arrive in time?

Constraints

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

<var>1 \leq T \leq 10000</var>

<var>1 \leq S \leq 10000</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>D</var> <var>T</var> <var>S</var>

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes <var>12.5</var> minutes to go <var>1000</var> meters to the place at a speed of <var>80</var> meters per minute. They have planned to meet in <var>15</var> minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes <var>20</var> minutes to go <var>2000</var> meters to the place at a speed of <var>100</var> meters per minute. They have planned to meet in <var>20</var> minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.

int solution(void) {
  int D = 0;
  int T = 0;
  int S = 0;
  scanf("%d %d %d", &D, &T, &S);
  if (S * T < D) {
    printf("No");
  } else if (S * T >= D) {
    printf("Yes");
  }
}

fn solution() -> Result<()> {
    let mut s = String::new();
    let _ls = io::stdin().read_line(&mut s)? - 1;
    let input: Vec<u32> = s
        .split_whitespace()
        .map(|x| x.parse::<u32>().unwrap())
        .collect();
    if input[1] * input[2] >= input[0] {
        println!("Yes");
    } else {
        println!("No");
    }

    Ok(())
}


Score : <var>900</var> points

Problem Statement

Takahashi has decided to give a string to his mother.

The value of a string <var>T</var> is the length of the longest common subsequence of <var>T</var> and <var>T'</var>, where <var>T'</var> is the string obtained by reversing <var>T</var>.
That is, the value is the longest length of the following two strings that are equal: a subsequence of <var>T</var> (possibly non-contiguous), and a subsequence of <var>T'</var> (possibly non-contiguous).

Takahashi has a string <var>S</var>. He wants to give her mother a string of the highest possible value, so he would like to change at most <var>K</var> characters in <var>S</var> to any other characters in order to obtain a string of the highest possible value.
Find the highest possible value achievable.

Constraints

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

<var>0 \leq K \leq |S|</var>

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

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

Input

Input is given from Standard Input in the following format:

<var>S</var>
<var>K</var>

Output

Print the highest possible value achievable.

Sample Input 1

abcabcabc
1

Sample Output 1

7

Changing the first character to c results in cbcabcabc.
Let this tring be <var>T</var>, then one longest common subsequence of <var>T</var> and <var>T'</var> is cbabcbc, whose length is <var>7</var>.

Sample Input 2

atcodergrandcontest
3

Sample Output 2

15

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let s = it.next().unwrap().as_bytes();
    let n = s.len();
    let k = it.next().unwrap().parse::<usize>().unwrap();
    let mut dp = vec![vec![vec![0; n]; n]; k + 1];
    for d in (1..n).rev() {
        for i in 0..k + 1 {
            for j in 0..n - d {
                dp[i][j + 1][j + d] = std::cmp::max(dp[i][j + 1][j + d], dp[i][j][j + d]);
                dp[i][j][j + d - 1] = std::cmp::max(dp[i][j][j + d - 1], dp[i][j][j + d]);
                let next_i = i + if s[j] == s[j + d] { 0 } else { 1 };
                if next_i > k {
                    continue;
                }
                dp[next_i][j + 1][j + d - 1] =
                    std::cmp::max(dp[next_i][j + 1][j + d - 1], dp[i][j][j + d] + 2);
            }
        }
    }
    let mut res = 0;
    for i in 0..k + 1 {
        for j in 0..n {
            for l in 0..n {
                res = std::cmp::max(res, dp[i][j][l] + if j == l { 1 } else { 0 });
            }
        }
    }
    println!("{}", res);
}


William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \,\cdots\, \,.\,a_k$$$ and can be one of two types:   Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, a_k \,.\, 1$$$ (starting a list of a deeper level), or  Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, (a_k + 1)$$$ (continuing the current level).  Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the "Notes" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the "Ctrl-S" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.

int solution(int argc, const char *argv[]) {
  int tests;
  scanf("%d", &tests);
  while (tests--) {
    int n;
    static int a[1005];
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
      scanf("%d", a + i);
    }
    static int stk[1005];
    int top = 0;
    for (int i = 1; i <= n; ++i) {
      if (a[i] == 1) {
        stk[++top] = 1;
      } else {
        for (; top != 0 && stk[top] != a[i] - 1; --top) {
          ;
        }
        stk[top += !top] = a[i];
      }
      for (int j = 1; j <= top; ++j) {
        printf("%d%c", stk[j], ".\n"[j == top]);
      }
    }
  }
  exit(EXIT_SUCCESS);
}

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 _it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());

        let mut stack = Vec::new();

        for _ in 0..n {
            let x: usize = lines.next().unwrap().parse().unwrap();

            if x == 1 {
                stack.push(1);
            } else {
                while *stack.last().unwrap() != x - 1 {
                    stack.pop();
                }
                *stack.last_mut().unwrap() += 1;
            }

            let a = *stack.first().unwrap();
            write!(&mut output, "{}", a).unwrap();
            for &a in &stack[1..] {
                write!(&mut output, ".{}", a).unwrap();
            }
            writeln!(&mut output).unwrap();
        }
    }
}


Score : <var>200</var> points

Problem Statement

We have a string <var>S</var> consisting of uppercase English letters. Additionally, an integer <var>N</var> will be given.

Shift each character of <var>S</var> by <var>N</var> in alphabetical order (see below), and print the resulting string.

We assume that A follows Z. For example, shifting A by <var>2</var> results in C (A <var>\to</var> B <var>\to</var> C), and shifting Y by <var>3</var> results in B (Y <var>\to</var> Z <var>\to</var> A <var>\to</var> B).

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S</var>

Output

Print the string resulting from shifting each character of <var>S</var> by <var>N</var> in alphabetical order.

Sample Input 1

2
ABCXYZ

Sample Output 1

CDEZAB

Note that A follows Z.

Sample Input 2

0
ABCXYZ

Sample Output 2

ABCXYZ

Sample Input 3

13
ABCDEFGHIJKLMNOPQRSTUVWXYZ

Sample Output 3

NOPQRSTUVWXYZABCDEFGHIJKLM

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: u8 = iter.next().unwrap().parse().unwrap();
    let s = iter.next().unwrap();
    for c in s.bytes() {
        print!("{}", (((c - b'A') + n) % 26 + b'A') as char)
    }
    println!();
}


Score : <var>100</var> points

Problem Statement

Snuke built an online judge to hold a programming contest.

When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string <var>S</var> as a contiguous substring.
(The judge can return any two-character substring of <var>S</var>.)

Determine whether the judge can return the string AC as the verdict to a program.

Constraints

<var>2 \leq |S| \leq 5</var>

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If the judge can return the string AC as a verdict to a program, print Yes; if it cannot, print No.

Sample Input 1

BACD

Sample Output 1

Yes

The string AC appears in BACD as a contiguous substring (the second and third characters).

Sample Input 2

ABCD

Sample Output 2

No

Although the string ABCD contains both A and C (the first and third characters), the string AC does not appear in ABCD as a contiguous substring.

Sample Input 3

CABD

Sample Output 3

No

Sample Input 4

ACACA

Sample Output 4

Yes

Sample Input 5

XX

Sample Output 5

No

int solution(void) {
  char s[6];
  scanf("%s", s);
  int ans = 0;
  int p = 0;
  while (ans == 0 && p < 6) {
    if (s[p] == 0x41 && s[p + 1] == 0x43) {
      printf("Yes");
      ans = 1;
    }
    p++;
  }
  if (ans == 0) {
    printf("No");
  }
}

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

    let ans = if S.find("AC").is_some() { "Yes" } else { "No" };

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


The enchanted forest got its name from the magical mushrooms growing here. They may cause illusions and generally should not be approached.—Perfect Memento in Strict SenseMarisa comes to pick mushrooms in the Enchanted Forest. The Enchanted forest can be represented by $$$n$$$ points on the $$$X$$$-axis numbered $$$1$$$ through $$$n$$$. Before Marisa started, her friend, Patchouli, used magic to detect the initial number of mushroom on each point, represented by $$$a_1,a_2,\ldots,a_n$$$.Marisa can start out at any point in the forest on minute $$$0$$$. Each minute, the followings happen in order:  She moves from point $$$x$$$ to $$$y$$$ ($$$|x-y|\le 1$$$, possibly $$$y=x$$$).  She collects all mushrooms on point $$$y$$$.  A new mushroom appears on each point in the forest. Note that she cannot collect mushrooms on minute $$$0$$$.Now, Marisa wants to know the maximum number of mushrooms she can pick after $$$k$$$ minutes.

int solution() {
  int t = 0;
  int n = 0;
  long long k = 0LL;
  long long a[200000] = {};

  int res = 0;

  long long sum[200001] = {};

  res = scanf("%d", &t);
  while (t > 0) {
    long long ans = 0LL;
    res = scanf("%d", &n);
    res = scanf("%lld", &k);
    for (int i = 0; i < n; i++) {
      res = scanf("%lld", a + i);
      sum[i + 1] = sum[i] + a[i];
    }
    if (k < ((long long)n)) {
      for (int i = (int)k; i <= n; i++) {
        long long tmp = sum[i] - sum[i - ((int)k)];
        if (tmp > ans) {
          ans = tmp;
        }
      }
      ans += (k * (k - 1LL)) / 2LL;
    } else {
      ans = sum[n] + k * ((long long)n);
      ans -= (((long long)n) * ((long long)(n + 1))) / 2LL;
    }
    printf("%lld\n", ans);
    t--;
  }

  return 0;
}

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

    let mut lines = content.lines();
    let num_tests: i32 = lines.next().unwrap().parse().unwrap();
    for _ in 0..num_tests {
        let arr: Vec<i64> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse().unwrap())
            .collect();
        let n = arr[0];
        let k = arr[1];
        let a: Vec<i64> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse().unwrap())
            .collect();

        if k < n {
            let mut prefix: Vec<i64> = vec![0; a.len() + 1];
            prefix[0] = 0;
            for i in 1..=a.len() {
                prefix[i] = prefix[i - 1] + a[i - 1];
            }
            let mut max_sum = 0;
            let mut max_idx = 0;
            for i in 0..=a.len() - k as usize {
                if prefix[i + k as usize] - prefix[i] > max_sum {
                    max_sum = prefix[i + k as usize] - prefix[i];
                    max_idx = i;
                }
            }
            let mut result = k * (k - 1) / 2;
            for &x in &a[max_idx..max_idx + k as usize] {
                result += x;
            }
            println!("{result}");
        } else {
            let mut result = k * (k - 1) / 2 - (k - n) * (k - n - 1) / 2;
            for &x in &a {
                result += x;
            }
            println!("{result}");
        }
    }
}


In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states:  If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \bmod n$$$.  If it is anticlockwise, snakes can only go from room $$$(i+1) \bmod n$$$ to $$$i$$$.  If it is off, snakes can travel in either direction.   Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let test: i64 = str.trim().parse().unwrap();
    for _ in 0..test {
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        let n: usize = str.trim().len();
        let mut l = true;
        let mut r = true;
        let mut acc = 0;
        let s: Vec<char> = str.trim().chars().collect();
        for i in 0..n {
            if s[i] == '-' || s[(i + 1) % n] == '-' {
                acc += 1;
            }
            if s[i] == '>' {
                l = false;
            }
            if s[i] == '<' {
                r = false;
            }
        }
        if l || r {
            println!("{}", n);
        } else {
            println!("{}", acc);
        }
    }
}


Score : <var>300</var> points

Problem Statement

Fennec is fighting with <var>N</var> monsters.

The health of the <var>i</var>-th monster is <var>H_i</var>.

Fennec can do the following two actions:

Attack: Fennec chooses one monster. That monster's health will decrease by <var>1</var>.

Special Move: Fennec chooses one monster. That monster's health will become <var>0</var>.

There is no way other than Attack and Special Move to decrease the monsters' health.

Fennec wins when all the monsters' healths become <var>0</var> or below.

Find the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning when she can use Special Move at most <var>K</var> times.

Constraints

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>H_1</var> <var>...</var> <var>H_N</var>

Output

Print the minimum number of times Fennec needs to do Attack (not counting Special Move) before winning.

Sample Input 1

3 1
4 1 5

Sample Output 1

5

By using Special Move on the third monster, and doing Attack four times on the first monster and once on the second monster, Fennec can win with five Attacks.

Sample Input 2

8 9
7 9 3 2 3 8 4 6

Sample Output 2

0

She can use Special Move on all the monsters.

Sample Input 3

3 0
1000000000 1000000000 1000000000

Sample Output 3

3000000000

Watch out for overflow.

int solution() {
  int n;
  int j;
  int temp;
  int prev;
  int k;
  int data[200005];
  int order[200005][2];
  int i;
  int f = 1;
  int b;
  int start = 0;
  int s;
  int a;
  long m = 0;
  scanf("%d", &n);
  scanf("%d", &s);
  for (i = 0; i < n; i++) {
    scanf("%d", &data[i]);
    order[i][0] = -1;
    order[i][1] = i + 1;
  }
  order[n - 1][1] = -1;
  while (order[start][1] != -1) {
    i = start;
    prev = -1;
    while (i != -1) {
      j = i;
      k = order[j][1];
      if (k == -1) {
        break;
      }
      i = order[k][1];
      if (data[j] < data[k]) {
        if (prev == -1) {
          start = k;
        } else {
          order[prev][1] = k;
        }
        temp = j;
        j = k;
        k = temp;
      }
      order[j][1] = i;
      prev = j;
      while (k != -1) {
        if ((j == -1) | (data[j] < data[k])) {
          temp = order[k][0];
          order[k][0] = order[a][0];
          order[a][0] = k;
          a = k;
          k = temp;
        } else {
          a = j;
          j = order[a][0];
        }
      }
    }
  }
  for (i = start, j = 0; i != -1; i = order[i][0], j++) {
    if (j >= s) {
      m += data[i];
    }
  }
  printf("%ld", m);
  return 0;
}

fn solution() {
    let (n, k): (usize, usize) = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace();
        (
            it.next().unwrap().parse().unwrap(),
            it.next().unwrap().parse().unwrap(),
        )
    };
    let mut h = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input
            .split_whitespace()
            .map(|x| x.parse::<i64>().unwrap())
            .collect::<Vec<i64>>()
    };
    h.sort_by(|a, b| b.cmp(a));
    if n <= k {
        println!("0");
    } else {
        println!("{}", h.iter().skip(k).sum::<i64>());
    }
}


Pak Chanek has $$$n$$$ two-dimensional slices of cheese. The $$$i$$$-th slice of cheese can be represented as a rectangle of dimensions $$$a_i \times b_i$$$. We want to arrange them on the two-dimensional plane such that:  Each edge of each cheese is parallel to either the x-axis or the y-axis.  The bottom edge of each cheese is a segment of the x-axis.  No two slices of cheese overlap, but their sides can touch.  They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long int small = 0;
    long long int big = 0;

    long long int n;
    scanf("%lld", &n);

    long long int a;
    long long int b;

    while (n--) {
      scanf("%lld %lld", &a, &b);
      small += a > b ? b : a;
      if (a > big) {
        big = a;
      }
      if (b > big) {
        big = b;
      }
    }
    printf("%lld\n", ((small * 2) + (big * 2)));
  }
  return 0;
}

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

    let mut reader = Scanner::new(stdin.lock());
    let mut writer = io::BufWriter::new(stdout.lock());

    let tests_number = reader.token::<i64>();
    for _ in 0..tests_number {
        let slices = reader.token::<i64>();
        let mut l = 0;
        let mut h = 0;
        for _ in 0..slices {
            let n = reader.token::<i64>();
            let m = reader.token::<i64>();
            let a_i = n.max(m);
            let b_i = n.min(m);

            l += b_i;
            h = h.max(a_i);
        }
        let perimeter = 2 * l + 2 * h;
        writeln!(writer, "{}", perimeter).unwrap();
    }
}


int solution(int l, int r, int key, int ar[]) {
  if (r >= l) {

    int mid1 = l + ((r - l) / 3);
    int mid2 = r - ((r - l) / 3);

    if (ar[mid1] == key) {
      return mid1;
    }
    if (ar[mid2] == key) {
      return mid2;
    }

    if (key < ar[mid1]) {

      return ternarySearch(l, mid1 - 1, key, ar);
    }
    if (key > ar[mid2]) {

      return ternarySearch(mid2 + 1, r, key, ar);
    } else {

      return ternarySearch(mid1 + 1, mid2 - 1, key, ar);
    }
  }

  return -1;
}

fn solution<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
    if arr.is_empty() {
        return None;
    }

    let is_asc = arr.len() > 1 && arr[0] < arr[arr.len() - 1];

    let mut left = 0;
    let mut right = arr.len() - 1;

    while left <= right {
        let first_mid = left + (right - left) / 3;
        let second_mid = right - (right - left) / 3;

        if first_mid == second_mid && first_mid == left {
            if &arr[left] == item {
                return Some(left);
            } else {
                left += 1;
                continue;
            }
        }

        let cmp_first_mid = item.cmp(&arr[first_mid]);
        let cmp_second_mid = item.cmp(&arr[second_mid]);

        match (is_asc, cmp_first_mid, cmp_second_mid) {
            (_, Ordering::Equal, _) => return Some(first_mid),
            (_, _, Ordering::Equal) => return Some(second_mid),

            (true, Ordering::Less, _) | (false, Ordering::Greater, _) => {
                if first_mid == 0 {
                    break;
                }
                right = first_mid - 1;
            }

            (true, _, Ordering::Greater) | (false, _, Ordering::Less) => {
                left = second_mid + 1;
            }

            (_, _, _) => {
                left = first_mid + 1;
                if second_mid == 0 {
                    break;
                }
                right = second_mid - 1;
            }
        }
    }

    None
}


You have a board represented as a grid with $$$2 \times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically?

int solution() {
  int T = 0;
  scanf("%d", &T);
  for (int i = T; i--;) {
    int n;
    int k1;
    int k2;
    scanf("%d %d %d", &n, &k1, &k2);
    int w;
    int b;
    scanf("%d %d", &w, &b);

    if (w == 0 && b == 0) {
      printf("YES\n");
      continue;
    }

    if (w * 2 <= (k1 + k2) && b * 2 <= 2 * n - (k1 + k2)) {
      printf("YES\n");
      continue;
    }
    printf("NO\n");
    continue;
  }
  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, k1, k2) = scan!(usize, usize, usize);
        let (w, b) = scan!(usize, usize);

        let solve = |k1: usize, k2, x: usize| -> bool {
            let (k1, k2) = (k1.min(k2), k1.max(k2));
            x <= k1 + (k2 - k1) / 2
        };

        if solve(k1, k2, w) && solve(n - k1, n - k2, b) {
            print!("YES");
        } else {
            print!("NO");
        }
        print!("\n");
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> candles placed on a number line.
The <var>i</var>-th candle from the left is placed on coordinate <var>x_i</var>.
Here, <var>x_1 < x_2 < ... < x_N</var> holds.

Initially, no candles are burning.
Snuke decides to light <var>K</var> of the <var>N</var> candles.

Now, he is at coordinate <var>0</var>.
He can move left and right along the line with speed <var>1</var>.
He can also light a candle when he is at the same position as the candle, in negligible time.

Find the minimum time required to light <var>K</var> candles.

Constraints

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

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

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

<var>|x_i| \leq 10^8</var>

<var>x_1 < x_2 < ... < x_N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_N</var>

Output

Print the minimum time required to light <var>K</var> candles.

Sample Input 1

5 3
-30 -10 10 20 50

Sample Output 1

40

He should move and light candles as follows:

Move from coordinate <var>0</var> to <var>-10</var>.

Light the second candle from the left.

Move from coordinate <var>-10</var> to <var>10</var>.

Light the third candle from the left.

Move from coordinate <var>10</var> to <var>20</var>.

Light the fourth candle from the left.

Sample Input 2

3 2
10 20 30

Sample Output 2

20

Sample Input 3

1 1
0

Sample Output 3

0

There may be a candle placed at coordinate <var>0</var>.

Sample Input 4

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

Sample Output 4

10

int solution(void) {
  int n;
  int k;
  scanf("%d%d", &n, &k);
  long long x[n];
  for (int i = 0; i < n; i++) {
    scanf("%lld", &x[i]);
  }

  long long tmp;
  long long ans = LLONG_MAX;
  for (int i = 0; i + k - 1 < n; i++) {

    if (x[i] * x[i + k - 1] >= 0) {
      tmp = fmax(llabs(x[i]), llabs(x[i + k - 1]));

    } else if (x[i] * x[i + k - 1] < 0) {
      if (x[i] * -2 + x[i + k - 1] > x[i] * -1 + x[i + k - 1] * 2) {
        tmp = x[i] * -1 + x[i + k - 1] * 2;
      } else {
        tmp = x[i] * -2 + x[i + k - 1];
      }
    }

    if (ans > tmp) {
      ans = tmp;
    }
  }
  printf("%lld\n", ans);
  return 0;
}

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

    let mut x = String::new();
    std::io::stdin().read_line(&mut x).unwrap();
    let x: Vec<isize> = x.split_whitespace().flat_map(str::parse).collect();

    println!(
        "{}",
        (0..(n - k + 1))
            .map(|s| {
                let start = x[s];
                let end = x[s + k - 1];
                if start >= 0 {
                    end
                } else if end > 0 {
                    let a = -start * 2 + end;
                    let b = -start + end * 2;
                    if a < b {
                        a
                    } else {
                        b
                    }
                } else {
                    -start
                }
            })
            .min()
            .unwrap()
    );
}


The only difference between the two versions is that this version asks the maximal possible answer.Homer likes arrays a lot. Today he is painting an array $$$a_1, a_2, \dots, a_n$$$ with two kinds of colors, white and black. A painting assignment for $$$a_1, a_2, \dots, a_n$$$ is described by an array $$$b_1, b_2, \dots, b_n$$$ that $$$b_i$$$ indicates the color of $$$a_i$$$ ($$$0$$$ for white and $$$1$$$ for black).According to a painting assignment $$$b_1, b_2, \dots, b_n$$$, the array $$$a$$$ is split into two new arrays $$$a^{(0)}$$$ and $$$a^{(1)}$$$, where $$$a^{(0)}$$$ is the sub-sequence of all white elements in $$$a$$$ and $$$a^{(1)}$$$ is the sub-sequence of all black elements in $$$a$$$. For example, if $$$a = [1,2,3,4,5,6]$$$ and $$$b = [0,1,0,1,0,0]$$$, then $$$a^{(0)} = [1,3,5,6]$$$ and $$$a^{(1)} = [2,4]$$$.The number of segments in an array $$$c_1, c_2, \dots, c_k$$$, denoted $$$\mathit{seg}(c)$$$, is the number of elements if we merge all adjacent elements with the same value in $$$c$$$. For example, the number of segments in $$$[1,1,2,2,3,3,3,2]$$$ is $$$4$$$, because the array will become $$$[1,2,3,2]$$$ after merging adjacent elements with the same value. Especially, the number of segments in an empty array is $$$0$$$.Homer wants to find a painting assignment $$$b$$$, according to which the number of segments in both $$$a^{(0)}$$$ and $$$a^{(1)}$$$, i.e. $$$\mathit{seg}(a^{(0)})+\mathit{seg}(a^{(1)})$$$, is as large as possible. Find this number.

int solution() {
  int n;
  scanf("%d", &n);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  int last1 = -1;
  int last2 = -1;
  int ans = n;
  for (int i = 0; i < n - 1; i++) {
    if (a[i] != last1 && a[i] != last2) {
      if (a[i + 1] == last1) {
        last1 = a[i];
      } else {
        last2 = a[i];
      }
    } else if (a[i] != last1 && a[i] == last2) {
      last1 = a[i];
    } else if (a[i] == last1 && a[i] != last2) {
      last2 = a[i];
    } else {
      last1 = a[i];
      ans -= 1;
    }
  }
  if (last1 == a[n - 1] && last2 == a[n - 1]) {
    ans -= 1;
  }
  printf("%d", ans);
}

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: usize = sc.next();
    let mut array: Vec<usize> = vec![0; n + 1];
    for i in 1..=n {
        array[i] = sc.next();
    }
    let mut next: Vec<usize> = vec![n + 1; n + 1];
    let mut dp: Vec<usize> = vec![n + 1; n + 1];
    for i in (1..=n).rev() {
        next[i] = dp[array[i]];
        dp[array[i]] = i;
    }
    let (mut l, mut r, mut ans) = (0, 0, 0);
    for i in 1..=n {
        if array[i] == array[l] {
            ans += (array[i] != array[r]) as i32;
            r = i;
        } else if array[i] == array[r] {
            ans += (array[i] != array[l]) as i32;
            l = i;
        } else if next[l] < next[r] {
            ans += (array[l] != array[i]) as i32;
            l = i;
        } else {
            ans += (array[r] != array[i]) as i32;
            r = i;
        }
    }
    writeln!(out, "{}", ans).unwrap();
}


Score : <var>100</var> points

Problem Statement

A balance scale tips to the left if <var>L>R</var>, where <var>L</var> is the total weight of the masses on the left pan and <var>R</var> is the total weight of the masses on the right pan. Similarly, it balances if <var>L=R</var>, and tips to the right if <var>L<R</var>.

Takahashi placed a mass of weight <var>A</var> and a mass of weight <var>B</var> on the left pan of a balance scale, and placed a mass of weight <var>C</var> and a mass of weight <var>D</var> on the right pan.

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Constraints

<var>1\leq A,B,C,D \leq 10</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var> <var>C</var> <var>D</var>

Output

Print Left if the balance scale tips to the left; print Balanced if it balances; print Right if it tips to the right.

Sample Input 1

3 8 7 1

Sample Output 1

Left

The total weight of the masses on the left pan is <var>11</var>, and the total weight of the masses on the right pan is <var>8</var>. Since <var>11>8</var>, we should print Left.

Sample Input 2

3 4 5 2

Sample Output 2

Balanced

The total weight of the masses on the left pan is <var>7</var>, and the total weight of the masses on the right pan is <var>7</var>. Since <var>7=7</var>, we should print Balanced.

Sample Input 3

1 7 6 4

Sample Output 3

Right

The total weight of the masses on the left pan is <var>8</var>, and the total weight of the masses on the right pan is <var>10</var>. Since <var>8<10</var>, we should print Right.

int solution() {

  int A = 0;
  int B = 0;
  int C = 0;
  int D = 0;
  scanf("%d %d %d %d\n", &A, &B, &C, &D);

  if (A + B > C + D) {
    printf("Left");
  } else if (A + B == C + D) {
    printf("Balanced");
  } else {
    printf("Right");
  }

  return 0;
}

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

    let q: Vec<i32> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();

    match (q[0] + q[1]).cmp(&(q[2] + q[3])) {
        Ordering::Greater => println!("Left"),
        Ordering::Equal => println!("Balanced"),
        Ordering::Less => println!("Right"),
    }
}


Two T-shirt sizes are given: $$$a$$$ and $$$b$$$. The T-shirt size is either a string M or a string consisting of several (possibly zero) characters X and one of the characters S or L.For example, strings M, XXL, S, XXXXXXXS could be the size of some T-shirts. And the strings XM, LL, SX are not sizes.The letter M stands for medium, S for small, L for large. The letter X refers to the degree of size (from eXtra). For example, XXL is extra-extra-large (bigger than XL, and smaller than XXXL).You need to compare two given sizes of T-shirts $$$a$$$ and $$$b$$$.The T-shirts are compared as follows:   any small size (no matter how many letters X) is smaller than the medium size and any large size;  any large size (regardless of the number of letters X) is larger than the medium size and any small size;  the more letters X before S, the smaller the size;  the more letters X in front of L, the larger the size. For example:   XXXS < XS  XXXL > XL  XL > M  XXL = XXL  XXXXXS < M  XL > XXXS

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 (a, b): (Vec<char>, 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().chars().collect(),
                iter.next().unwrap().chars().collect(),
            )
        };

        if a == b {
            println!("=");
            continue;
        }

        if a[a.len() - 1] == 'S' {
            if b[b.len() - 1] == 'S' {
                if a.len() > b.len() {
                    println!("<");
                } else {
                    println!(">");
                }
            } else {
                println!("<")
            }
        } else if a[a.len() - 1] == 'L' {
            if b[b.len() - 1] == 'L' {
                if a.len() > b.len() {
                    println!(">");
                } else {
                    println!("<");
                }
            } else {
                println!(">")
            }
        } else {
            if b[b.len() - 1] == 'L' {
                println!("<");
            } else {
                println!(">")
            }
        }
    }
}


Score: <var>800</var> points

Problem Statement

This is an interactive task.

We have <var>2N</var> balls arranged in a row, numbered <var>1, 2, 3, ..., 2N</var> from left to right, where <var>N</var> is an odd number. Among them, there are <var>N</var> red balls and <var>N</var> blue balls.

While blindfolded, you are challenged to guess the color of every ball correctly, by asking at most <var>210</var> questions of the following form:

You choose any <var>N</var> of the <var>2N</var> balls and ask whether there are more red balls than blue balls or not among those <var>N</var> balls.

Now, let us begin.

Constraints

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

<var>N</var> is an odd number.

Input and Output

First, receive the number of balls of each color, <var>N</var>, from Standard Input:

<var>N</var>

Then, ask questions until you find out the color of every ball.
A question should be printed to Standard Output in the following format:

? <var>A_1</var> <var>A_2</var> <var>A_3</var> <var>...</var> <var>A_N</var>

This means that you are asking about the <var>N</var> balls <var>A_1, A_2, A_3, ..., A_N</var>, where <var>1 \leq A_i \leq 2N</var> and <var>A_i \neq A_j (i \neq j)</var> must hold.

The response <var>T</var> to this question will be given from Standard Input in the following format:

<var>T</var>

Here <var>T</var> is one of the following strings:

Red: Among the <var>N</var> balls chosen, there are more red balls than blue balls.

Blue: Among the <var>N</var> balls chosen, there are more blue balls than red balls.

-1: You printed an invalid question (including the case you asked more than <var>210</var> questions), or something else that was invalid.

If the judge returns -1, your submission is already judged as incorrect. The program should immediately quit in this case.

When you find out the color of every ball, print your guess to Standard Output in the following format:

! <var>c_1</var><var>c_2</var><var>c_3</var><var>...</var><var>c_{2N}</var>

Here <var>c_i</var> should be the character representing the color of Ball <var>i</var>; use R for red and B for blue.

Notice

Flush Standard Output each time you print something. Failure to do so may result in TLE.

Immediately terminate your program after printing your guess (or receiving the -1 response). Otherwise, the verdict will be indeterminate.

If your program prints something invalid, the verdict will be indeterminate.

Sample Input and Output

Input
Output

3

? 1 2 3

Red

? 2 4 6

Blue

! RRBBRB

In this sample, <var>N = 3</var>, and the colors of Ball <var>1, 2, 3, 4, 5, 6</var> are red, red, blue, blue, red, blue, respectively.

In the first question, there are two red balls and one blue ball among the balls <var>1, 2, 3</var>, so the judge returns Red.

In the second question, there are one red ball and two blue balls among the balls <var>2, 4, 6</var>, so the judge returns Blue.

int solution() {
  int n;
  scanf("%d", &n);
  char ans[102];
  int i;
  int j;
  for (i = 0; i < 2 * n; i++) {
    ans[i] = '?';
  }
  int r;
  int b;
  int c;
  int min;
  int mid;
  int max;
  char minc;
  char res[16];
  printf("?");
  for (i = 0; i < n; i++) {
    printf(" %d", i + 1);
  }
  printf("\n");
  fflush(stdout);
  scanf("%s", res);
  minc = res[0];
  min = 0;
  max = n;
  while (max - min > 1) {
    mid = (max + min) / 2;
    printf("?");
    for (i = 0; i < n; i++) {
      printf(" %d", i + mid + 1);
    }
    printf("\n");
    fflush(stdout);
    scanf("%s", res);
    if (res[0] == minc) {
      min = mid;
    } else {
      max = mid;
    }
  }
  ans[min] = minc;
  if (minc == 'R') {
    ans[max + n - 1] = 'B';
  } else {
    ans[max + n - 1] = 'R';
  }
  for (j = max; j < min + n; j++) {
    printf("?");
    for (i = min; i < max + n; i++) {
      if (i != j) {
        printf(" %d", i + 1);
      }
    }
    printf("\n");
    fflush(stdout);
    scanf("%s", res);
    if (res[0] == 'B') {
      ans[j] = 'R';
    } else {
      ans[j] = 'B';
    }
  }
  for (;;) {
    c = -1;
    for (i = 0; i < 2 * n; i++) {
      if (ans[i] == '?') {
        c = i;
      }
    }
    if (c < 0) {
      break;
    }
    printf("?");
    for (i = max; i < min + n; i++) {
      printf(" %d", i + 1);
    }
    printf(" %d\n", c + 1);
    fflush(stdout);
    scanf("%s", res);
    if (res[0] == 'B') {
      ans[c] = 'B';
    } else {
      ans[c] = 'R';
    }
  }
  printf("! ");
  for (i = 0; i < 2 * n; i++) {
    printf("%c", ans[i]);
  }
  return 0;
}

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

    println!(
        "? {}",
        (1..(N + 1))
            .map(|i| i.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    );
    let s: String = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    };

    let mut ok = N + 1;
    let mut ng = 1;

    while ok - ng > 1 {
        let mid = (ok + ng) / 2;
        let query = (mid..(mid + N))
            .map(|i| i.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        println!("? {}", query);
        let T: String = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().to_string()
        };
        if T == s {
            ng = mid;
        } else {
            ok = mid;
        }
    }
    let mut q = vec![0; N];
    for i in 0..(N - 1) {
        q[i] = ok + i;
    }

    let mut res = vec!['?'; 2 * N];
    for i in 1..(2 * N + 1) {
        if !q.contains(&i) {
            q[N - 1] = i;
            let query = q
                .iter()
                .map(|&x| x.to_string())
                .collect::<Vec<_>>()
                .join(" ");
            println!("? {}", query);
            let T: String = {
                let mut line: String = String::new();
                std::io::stdin().read_line(&mut line).unwrap();
                line.trim().to_string()
            };
            res[i - 1] = if T.as_str() == "Red" { 'R' } else { 'B' };
        }
    }
    let mut r = 0;
    let mut b = 0;
    for i in 0..(2 * N) {
        if res[i] == 'R' && r < N / 2 {
            q[r + b] = i + 1;
            r += 1;
        } else if res[i] == 'B' && b < N / 2 {
            q[r + b] = i + 1;
            b += 1;
        }
    }
    for i in ok..(ok + N - 1) {
        q[N - 1] = i;
        let query = q
            .iter()
            .map(|&x| x.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        println!("? {}", query);
        let T: String = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().to_string()
        };
        res[i - 1] = if T.as_str() == "Red" { 'R' } else { 'B' };
    }

    let ans = res
        .iter()
        .map(|&c| c.to_string())
        .collect::<Vec<_>>()
        .join("");
    println!("! {}", ans);
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> points in a <var>D</var>-dimensional space.

The coordinates of the <var>i</var>-th point are <var>(X_{i1}, X_{i2}, ..., X_{iD})</var>.

The distance between two points with coordinates <var>(y_1, y_2, ..., y_D)</var> and <var>(z_1, z_2, ..., z_D)</var> is <var>\sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}</var>.

How many pairs <var>(i, j)</var> <var>(i < j)</var> are there such that the distance between the <var>i</var>-th point and the <var>j</var>-th point is an integer?

Constraints

All values in input are integers.

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

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

<var>-20 \leq X_{ij} \leq 20</var>

No two given points have the same coordinates. That is, if <var>i \neq j</var>, there exists <var>k</var> such that <var>X_{ik} \neq X_{jk}</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>D</var>
<var>X_{11}</var> <var>X_{12}</var> <var>...</var> <var>X_{1D}</var>
<var>X_{21}</var> <var>X_{22}</var> <var>...</var> <var>X_{2D}</var>
<var>\vdots</var>
<var>X_{N1}</var> <var>X_{N2}</var> <var>...</var> <var>X_{ND}</var>

Output

Print the number of pairs <var>(i, j)</var> <var>(i < j)</var> such that the distance between the <var>i</var>-th point and the <var>j</var>-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is <var>\sqrt{|1-5|^2 + |2-5|^2} = 5</var>, which is an integer.

The distance between the second point and the third point is <var>\sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}</var>, which is not an integer.

The distance between the third point and the first point is <var>\sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}</var>, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10

int solution() {
  int N = 0;
  int D = 0;
  int i = 0;
  int j = 0;
  int ans = 0;
  int count = 0;
  double ansd = 0.0;
  int X[11][10] = {0};
  scanf("%d %d", &N, &D);
  for (i = 0; i < N; i++) {
    for (j = 0; j < D; j++) {
      scanf("%d", &X[i][j]);
    }
  }

  for (j = 0; j < D; j++) {
    X[N][j] = X[0][j];
  }

  int k = 0;
  for (k = 0; k < N; k++) {
    for (i = k + 1; i < N; i++) {
      ans = 0;
      for (j = 0; j < D; j++) {
        ans += abs(X[k][j] - X[i][j]) * abs(X[k][j] - X[i][j]);
      }

      ansd = sqrt((double)ans);
      if (ceil(ansd) != floor(ansd)) {

      } else {
        count++;
      }
    }
  }
  printf("%d\n", count);
  return 0;
}

fn solution() {
    let (N, D): (usize, usize) = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };
    let X: Vec<Vec<i64>> = {
        let mut X = vec![];
        for _ in 0..N {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            X.push(
                line.split_whitespace()
                    .map(|x| x.parse().unwrap())
                    .collect(),
            );
        }
        X
    };

    let sq = (0..1000)
        .map(|i| i * i)
        .collect::<std::collections::HashSet<i64>>();
    let ans = (0..(N - 1))
        .map(|i| {
            ((i + 1)..N)
                .map(|j| (0..D).map(|k| (X[i][k] - X[j][k]).pow(2)).sum::<i64>())
                .filter(|&d| sq.contains(&d))
                .count()
        })
        .sum::<usize>();

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


Score : <var>100</var> points

Problem Statement

We will buy a product for <var>N</var> yen (the currency of Japan) at a shop.

If we use only <var>1000</var>-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two <var>1000</var>-yen bills to pay the price and receive <var>100</var> yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.

fn solution() {
    let mut line = String::new();
    stdin().read_line(&mut line).ok();
    let n: i32 = line.trim().parse().ok().unwrap();
    println!(
        "{}",
        if n % 1000 == 0 {
            0
        } else {
            (n / 1000 + 1) * 1000 - n
        }
    );
}


Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito's strength equals s.If Kirito starts duelling with the i-th (1 ≤ i ≤ n) dragon and Kirito's strength is not greater than the dragon's strength xi, then Kirito loses the duel and dies. But if Kirito's strength is greater than the dragon's strength, then he defeats the dragon and gets a bonus strength increase by yi.Kirito can fight the dragons in any order. Determine whether he can move on to the next level of the game, that is, defeat all dragons without a single loss.

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

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

    let mut s = words[0];
    let n = words[1];

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

    for _ in 0..n {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();

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

        let mut dragon = Vec::new();
        dragon.push(words[0]);
        dragon.push(words[1]);
        dragons.push(dragon);
    }

    dragons.sort_by(|a, b| {
        if a.first().unwrap() > b.first().unwrap() {
            Ordering::Greater
        } else if a.first().unwrap() < b.first().unwrap() {
            Ordering::Less
        } else {
            Ordering::Equal
        }
    });

    let mut answer = "YES";

    for i in dragons {
        if s - i.first().unwrap() > 0 {
            s += i.get(1).unwrap();
        } else {
            answer = "NO";
        }
    }

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


Score : <var>100</var> points

Problem Statement

In K-city, there are <var>n</var> streets running east-west, and <var>m</var> streets running north-south. Each street running east-west and each street running north-south cross each other. We will call the smallest area that is surrounded by four streets a block. How many blocks there are in K-city?

Constraints

<var>2 ≤ n, m ≤ 100</var>

Input

Input is given from Standard Input in the following format:

<var>n</var> <var>m</var>

Output

Print the number of blocks in K-city.

Sample Input 1

3 4

Sample Output 1

6

There are six blocks, as shown below:

Sample Input 2

2 2

Sample Output 2

1

There are one block, as shown below:

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).ok();
    let v: Vec<u16> = line
        .split_whitespace()
        .map(|n| n.parse().unwrap())
        .collect();
    let n = v[0];
    let m = v[1];
    println!("{}", (n - 1) * (m - 1));
}


In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).A group of soldiers is effective if and only if their names are different. For example, a group (John, Bob, Limak) would be effective, while groups (Gary, Bob, Gary) and (Alice, Alice) wouldn't.You are a spy in the enemy's camp. You noticed n soldiers standing in a row, numbered 1 through n. The general wants to choose a group of k consecutive soldiers. For every k consecutive soldiers, the general wrote down whether they would be an effective group or not.You managed to steal the general's notes, with n - k + 1 strings s1, s2, ..., sn - k + 1, each either "YES" or "NO".   The string s1 describes a group of soldiers 1 through k ("YES" if the group is effective, and "NO" otherwise).  The string s2 describes a group of soldiers 2 through k + 1.  And so on, till the string sn - k + 1 that describes a group of soldiers n - k + 1 through n. Your task is to find possible names of n soldiers. Names should match the stolen notes. Each name should be a string that consists of between 1 and 10 English letters, inclusive. The first letter should be uppercase, and all other letters should be lowercase. Names don't have to be existing names — it's allowed to print "Xyzzzdj" or "T" for example.Find and print any solution. It can be proved that there always exists at least one solution.

int solution() {
  int n;
  int k;
  unsigned char str[4];
  unsigned char ans[51];
  scanf("%d %d", &n, &k);
  for (int i = 0; i < n; ++i) {
    ans[i] = i + 1;
  }
  for (int i = 0; i < n - k + 1; ++i) {
    scanf("%s", str);
    if (str[0] == 'N') {
      ans[i + k - 1] = ans[i];
    }
  }
  for (int i = 0; i < n; ++i) {
    if (ans[i] < 27) {
      printf("%c ", 'A' + ans[i] - 1);
    } else {
      printf("A%c ", 'a' + ans[i] - 27);
    }
  }
  puts("");
  return 0;
}

fn solution() {
    let mut soldiers = vec![];

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

    let n = input.next().unwrap().parse::<usize>().unwrap();
    let k = input.next().unwrap().parse::<usize>().unwrap();

    let mut input = String::new();
    std::io::stdin().read_line(&mut input).unwrap();
    let mut effective = input.split_whitespace().map(|s| s == "YES");

    for i in 1..k {
        soldiers.push(i);
    }

    for i in k..n + 1 {
        if effective.next().unwrap() {
            soldiers.push(i);
        } else {
            let id = soldiers[i - k];
            soldiers.push(id);
        }
    }

    let mut emit_space = false;
    for mut id in soldiers {
        if emit_space {
            print!(" ");
        }
        let mut first = true;
        while id > 0 {
            let base = if first { b'A' } else { b'a' };
            print!("{}", ((id % 26) as u8 + base) as char);
            id /= 26;
            first = false;
        }
        emit_space = true;
    }
    println!();
}


Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

int solution() {
  int t;
  long long int d;
  long long int e;
  scanf("%d", &t);
  long long int hc[t];
  long long int dc[t];
  long long int hm[t];
  long long int dm[t];
  long long int k[t];
  long long int w[t];
  long long int a[t];

  int i;
  int j;
  int flag[t];
  for (i = 0; i < t; i++) {
    flag[i] = 0;
  }
  int m = 0;
  while (m < t) {
    scanf("%lld %lld %lld %lld %lld %lld %lld", &hc[m], &dc[m], &hm[m], &dm[m],
          &k[m], &w[m], &a[m]);

    for (i = 0; i <= k[m]; i++) {
      d = dc[m] + w[m] * i;
      e = hc[m] + a[m] * (k[m] - i);
      if (((hm[m] + d - 1) / d) <= ((e + dm[m] - 1) / dm[m])) {
        flag[m] = 1;
      }
    }

    m++;
  }
  for (i = 0; i < t; i++) {
    if (flag[i] == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

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

    let stdout = io::stdout();
    let handle = stdout.lock();
    let mut buffer = BufWriter::with_capacity(65536, handle);
    'test_case: for _t in 0..t {
        line.clear();
        stdin.read_line(&mut line).unwrap();
        let mut character = line.split_ascii_whitespace();
        let character_health: u64 = character.next().unwrap().parse().unwrap();
        let character_damage: u64 = character.next().unwrap().parse().unwrap();

        line.clear();
        stdin.read_line(&mut line).unwrap();
        let mut monster = line.split_ascii_whitespace();
        let monster_health: u64 = monster.next().unwrap().parse().unwrap();
        let monster_damage: u64 = monster.next().unwrap().parse().unwrap();

        line.clear();
        stdin.read_line(&mut line).unwrap();
        let mut upgrades = line.split_ascii_whitespace();
        let coins: u64 = upgrades.next().unwrap().parse().unwrap();
        let damage_upgrade: u64 = upgrades.next().unwrap().parse().unwrap();
        let health_upgrade: u64 = upgrades.next().unwrap().parse().unwrap();

        for i in 0..=coins {
            let new_health = character_health + i * health_upgrade;
            let new_damage = character_damage + (coins - i) * damage_upgrade;
            let turns_to_win_monster =
                new_health / monster_damage + (!new_health.is_multiple_of(monster_damage) as u64);
            let turns_to_win_character =
                monster_health / new_damage + (!monster_health.is_multiple_of(new_damage) as u64);
            if turns_to_win_character <= turns_to_win_monster {
                writeln!(&mut buffer, "YES").unwrap();
                continue 'test_case;
            }
        }
        writeln!(&mut buffer, "NO").unwrap();
    }
    buffer.flush().unwrap();
}


You are given a positive integer $$$x$$$. Check whether the number $$$x$$$ is representable as the sum of the cubes of two positive integers.Formally, you need to check if there are two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b$$$) such that $$$a^3+b^3=x$$$.For example, if $$$x = 35$$$, then the numbers $$$a=2$$$ and $$$b=3$$$ are suitable ($$$2^3+3^3=8+27=35$$$). If $$$x=4$$$, then no pair of numbers $$$a$$$ and $$$b$$$ is suitable.

int solution() {
  int t = 0;
  int yes = 0;
  long long int k = 0;
  long long int j = 0;
  long long int s = 0;
  long long int n = 0;
  long long int i = 0;
  long long int last = 0;
  scanf("%d", &t);

  while (t-- > 0) {
    i = 1;
    yes = 0;
    scanf("%lld", &n);
    while ((i * i * i) < n) {
      i++;
    }
    last = i - 1;
    for (j = 1; j <= last; j++) {
      for (k = last; k >= j; k--) {
        s = (j * j * j) + (k * k * k);
        if (s == n) {
          printf("YES\n");
          yes = 1;
          break;
        }
        if (s < n) {
          last = k;
          break;
        }
      }
      if (yes == 1) {
        break;
      }
    }
    if (yes == 0) {
      printf("NO\n");
    }
  }
  return 0;
}

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 cubes: BTreeSet<i64> = (1..10001_i64).map(|i| i * i * i).collect();
    let tc: usize = sc.next();
    for _ in 0..tc {
        let x: i64 = sc.next();
        let mut contains = false;
        for a in cubes.clone() {
            if cubes.contains(&(x - a)) {
                contains = true;
                break;
            }
        }
        writeln!(out, "{}", if contains { "YES" } else { "NO" }).unwrap();
    }
}


Today, Marin is at a cosplay exhibition and is preparing for a group photoshoot!For the group picture, the cosplayers form a horizontal line. A group picture is considered beautiful if for every contiguous segment of at least $$$2$$$ cosplayers, the number of males does not exceed the number of females (obviously).Currently, the line has $$$n$$$ cosplayers which can be described by a binary string $$$s$$$. The $$$i$$$-th cosplayer is male if $$$s_i = 0$$$ and female if $$$s_i = 1$$$. To ensure that the line is beautiful, you can invite some additional cosplayers (possibly zero) to join the line at any position. You can't remove any cosplayer from the line.Marin wants to know the minimum number of cosplayers you need to invite so that the group picture of all the cosplayers is beautiful. She can't do this on her own, so she's asking you for help. Can you help her?

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

    io::stdin().read_line(&mut qntcasos).unwrap();
    let qntcasos: u32 = qntcasos.trim().parse().unwrap();

    for _i in 0..qntcasos {
        let mut casoatual = String::new();
        let mut casoatualnumero = String::new();
        io::stdin().read_line(&mut casoatualnumero).unwrap();
        let _casoatualnumero: u32 = casoatualnumero.trim().parse().unwrap();

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

        let mut qnt = 0;

        for x in 1..casoatual.len() {
            if &casoatual[x - 1..x + 1] == "00" {
                qnt += 2;
            }

            if x != casoatual.len() - 1 && &casoatual[x - 1..x + 2] == "010" {
                qnt += 1;
            }
        }

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


問題 1: 平均点 (Average Score)

問題

JOI 高校の授業には，太郎君，次郎君，三郎君，四郎君，花子さんの 5 人の生徒が参加した．

この授業では，期末試験を実施した．期末試験は，5 人全員が受験した．期末試験の点数が 40 点以上の生徒は，期末試験の点数がそのまま成績になった．期末試験の点数が 40 点未満の生徒は全員，補習を受け，成績が 40 点になった．

5 人の生徒の期末試験の点数が与えられたとき，5 人の成績の平均点を計算するプログラムを作成せよ．

 入力

入力は 5 行からなり，1 行に 1 つずつ整数が書かれている．

1 行目には 太郎君の期末試験の点数が書かれている．

2 行目には 次郎君の期末試験の点数が書かれている．

3 行目には 三郎君の期末試験の点数が書かれている．

4 行目には 四郎君の期末試験の点数が書かれている．

5 行目には 花子さんの期末試験の点数が書かれている．

生徒の期末試験の点数はすべて 0 点以上 100 点以下の整数である．

生徒の期末試験の点数はすべて 5 の倍数である．

5 人の生徒の成績の平均点は必ず整数になる．

 出力

5 人の生徒の成績の平均点をあらわす整数を 1 行で出力せよ．

 入出力例

入力例 1

10
65
100
30
95

出力例 1

68

入出力例 1 では，太郎君と四郎君の期末試験の点数は 40 点未満なので，太郎君と四郎君の成績は 40 点になる．次郎君と三郎君と花子さんの期末試験の点数は 40 点以上なので，次郎君の成績は 65 点，三郎君の成績は 100 点，花子さんの成績は 95 点となる．5 人の成績の合計は 340 なので，平均点は 68 点となる．

入力例 2

40
95
0
95
50

出力例 2

64

問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。

int solution() {
  int a = 0;
  int ans = 0;
  int i = 0;
  for (i = 0; i < 5; i++) {

    scanf("%d", &a);
    if (a <= 40) {
      a = 40;
    }
    ans += a;
  }
  printf("%d\n", ans / 5);

  return 0;
}

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

    let avg = lines
        .take(5)
        .map(|l| {
            let score = l.parse().unwrap();
            if score < 40 {
                40
            } else {
                score
            }
        })
        .sum::<u32>()
        / 5;

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


Mishka wants to buy some food in the nearby shop. Initially, he has $$$s$$$ burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number $$$1 \le x \le s$$$, buy food that costs exactly $$$x$$$ burles and obtain $$$\lfloor\frac{x}{10}\rfloor$$$ burles as a cashback (in other words, Mishka spends $$$x$$$ burles and obtains $$$\lfloor\frac{x}{10}\rfloor$$$ back). The operation $$$\lfloor\frac{a}{b}\rfloor$$$ means $$$a$$$ divided by $$$b$$$ rounded down.It is guaranteed that you can always buy some food that costs $$$x$$$ for any possible value of $$$x$$$.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has $$$s=19$$$ burles then the maximum number of burles he can spend is $$$21$$$. Firstly, he can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback. Now he has $$$s=10$$$ burles, so can spend $$$x=10$$$ burles, obtain $$$1$$$ burle as a cashback and spend it too.You have to answer $$$t$$$ independent test cases.

int solution() {

  int snum;

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

    do {
      x = x + s[i] / 10;
      s[i] = s[i] - s[i] / 10 * 10 + s[i] / 10;
    } while (s[i] / 10 > 0);

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

  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let t: u32 = line.trim().parse().unwrap();
    for _ in 0..t {
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();
        let mut coins: u32 = line.trim().parse().unwrap();
        let mut spent = 0;
        while coins >= 10 {
            let to_spend = coins - (coins % 10);
            spent += to_spend;
            coins = coins - to_spend + (to_spend / 10);
        }
        spent += coins;

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


Score : <var>200</var> points

Problem Statement

Given are <var>1</var>-digit positive integers <var>a</var> and <var>b</var>. Consider these two strings: the concatenation of <var>b</var> copies of the digit <var>a</var>, and the concatenation of <var>a</var> copies of the digit <var>b</var>. Which of these is lexicographically smaller?

Constraints

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

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

<var>a</var> and <var>b</var> are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the lexicographically smaller of the two strings. (If the two strings are equal, print one of them.)

Sample Input 1

4 3

Sample Output 1

3333

We have two strings 444 and 3333. Between them, 3333 is the lexicographically smaller.

Sample Input 2

7 7

Sample Output 2

7777777

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

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

  int ans = 0;

  if (a <= b) {
    for (int i = 0; i < b; i++) {
      ans = ans + a * pow(10, i);
    }
    printf("%d", ans);
  } else {
    for (int i = 0; i < a; i++) {
      ans = ans + b * pow(10, i);
    }
    printf("%d", ans);
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let ab: Vec<i32> = s.split_whitespace().map(|w| w.parse().unwrap()).collect();
    if ab[0] < ab[1] {
        for _ in 0..ab[1] {
            print!("{}", ab[0]);
        }
    } else {
        for _ in 0..ab[0] {
            print!("{}", ab[1]);
        }
    }
    println!();
}


Score : <var>300</var> points

Problem Statement

There is an integer sequence <var>A</var> of length <var>N</var> whose values are unknown.

Given is an integer sequence <var>B</var> of length <var>N-1</var> which is known to satisfy the following:

<var> B_i \geq \max(A_i, A_{i+1}) </var>

Find the maximum possible sum of the elements of <var>A</var>.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>B_1</var> <var>B_2</var> <var>...</var> <var>B_{N-1}</var>

Output

Print the maximum possible sum of the elements of <var>A</var>.

Sample Input 1

3
2 5

Sample Output 1

9

<var>A</var> can be, for example, ( <var>2</var> , <var>1</var> , <var>5</var> ), ( <var>-1</var> , <var>-2</var> , <var>-3</var> ), or ( <var>2</var> , <var>2</var> , <var>5</var> ). Among those candidates, <var>A</var> = ( <var>2</var> , <var>2</var> , <var>5</var> ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53

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

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

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let mut b: Vec<usize> = vec![];
    for _ in 0..(n - 1) {
        b.push(iter.next().unwrap().parse().unwrap());
    }

    let mut a: Vec<usize> = vec![];

    for i in 0..n {
        if i == 0 {
            a.push(b[0]);
            continue;
        } else if i == n - 1 {
            a.push(b[i - 1]);
            break;
        }
        a.push(std::cmp::min(b[i], b[i - 1]));
    }

    let mut ans = 0;
    for a in a.into_iter() {
        ans += a;
    }

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


There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $$$n$$$ packets with inflatable balloons, where $$$i$$$-th of them has exactly $$$a_i$$$ balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold:  Do not rip the packets (both Grigory and Andrew should get unbroken packets);  Distribute all packets (every packet should be given to someone);  Give both Grigory and Andrew at least one packet;  To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.

fn solution() {
    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

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

    let _n = input_strs.first().unwrap();

    let _possible = true;

    if input_strs.iter().skip(1).count() == 1 {
        println!("-1");
        return;
    }

    let total = input_strs.iter().skip(1).sum::<i64>();

    let mut found_min = 2000;
    let found_idx = input_strs
        .iter()
        .skip(1)
        .enumerate()
        .fold(0, |acc, (e, v)| {
            if *v < found_min {
                found_min = *v;
                e
            } else {
                acc
            }
        });

    if found_min == total - found_min {
        println!("-1");
        return;
    }

    println!("1");
    println!("{}", found_idx + 1);
}


Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened:  if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing;  if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\rightarrow$$$ abb $$$\rightarrow$$$ abba $$$\rightarrow$$$ abbac $$$\rightarrow$$$ abbaca $$$\rightarrow$$$ abbacabb $$$\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

int solution(void) {
  unsigned short test_cases;
  scanf("%hu\n", &test_cases);
  const unsigned short SIZE = 26;
  bool button_states[SIZE];

  for (unsigned short i = 0; i < test_cases; ++i) {
    memset(button_states, false, sizeof(button_states));

    const unsigned short MAX_LENGTH = 500;
    char str[MAX_LENGTH];
    scanf("%s", str);

    char *c = str;
    do {
      if (*c != *(c + 1)) {
        button_states[*c - 'a'] = true;
        ++c;
      } else {
        c += 2;
      }
    } while (*c != '\0');

    for (unsigned short j = 0; j < SIZE; ++j) {
      if (button_states[j]) {
        putchar('a' + j);
      }
    }

    putchar('\n');
  }

  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let t = input.trim().parse::<u8>().unwrap();
    for _ in 0..t {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");

        let letters = input.trim();
        let mut working = [false; 26];

        let mut letters_iter = letters.chars();
        let mut current = letters_iter.next().unwrap();
        let mut counter = 1;
        for c in letters_iter {
            if c == current {
                counter += 1;
            } else {
                if counter % 2 != 0 {
                    working[current as usize - 'a' as usize] = true;
                }

                counter = 1;
                current = c;
            }
        }
        if counter % 2 != 0 {
            working[current as usize - 'a' as usize] = true;
        }

        for i in 0..26 {
            if working[i] {
                print!("{}", (i as u8 + b'a') as char);
            }
        }
        println!();
    }
}


Score : <var>1000</var> points

Problem Statement

There are <var>N</var> balls in a row.
Initially, the <var>i</var>-th ball from the left has the integer <var>A_i</var> written on it.

When Snuke cast a spell, the following happens:

Let the current number of balls be <var>k</var>. All the balls with <var>k</var> written on them disappear at the same time.

Snuke's objective is to vanish all the balls by casting the spell some number of times.
This may not be possible as it is. If that is the case, he would like to modify the integers on the minimum number of balls to make his objective achievable.

By the way, the integers on these balls sometimes change by themselves.
There will be <var>M</var> such changes. In the <var>j</var>-th change, the integer on the <var>X_j</var>-th ball from the left will change into <var>Y_j</var>.

After each change, find the minimum number of modifications of integers on the balls Snuke needs to make if he wishes to achieve his objective before the next change occurs. We will assume that he is quick enough in modifying integers. Here, note that he does not actually perform those necessary modifications and leaves them as they are.

Constraints

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

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

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

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

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

Subscore

In the test set worth <var>500</var> points, <var>N \leq 200</var> and <var>M \leq 200</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>A_2</var> ... <var>A_N</var>
<var>X_1</var> <var>Y_1</var>
<var>X_2</var> <var>Y_2</var>
:
<var>X_M</var> <var>Y_M</var>

Output

Print <var>M</var> lines.
The <var>j</var>-th line should contain the minimum necessary number of modifications of integers on the balls to make Snuke's objective achievable.

Sample Input 1

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

Sample Output 1

0
1
1

After the first change, the integers on the balls become <var>2</var>, <var>1</var>, <var>3</var>, <var>4</var>, <var>5</var>, from left to right. Here, all the balls can be vanished by casting the spell five times. Thus, no modification is necessary.

After the second change, the integers on the balls become <var>2</var>, <var>5</var>, <var>3</var>, <var>4</var>, <var>5</var>, from left to right. In this case, at least one modification must be made. One optimal solution is to modify the integer on the fifth ball from the left to <var>2</var>, and cast the spell four times.

After the third change, the integers on the balls become <var>2</var>, <var>5</var>, <var>3</var>, <var>4</var>, <var>4</var>, from left to right. Also in this case, at least one modification must be made. One optimal solution is to modify the integer on the third ball from the left to <var>2</var>, and cast the spell three times.

Sample Input 2

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

Sample Output 2

0
1
2
3

Sample Input 3

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

Sample Output 3

1
0
1
2
2
3
3
3
3
2

int solution() {
  int N;
  int M;
  int i;
  int j;
  int ans = 0;
  int old;
  int new;
  scanf("%d%d", &N, &M);
  int *A = (int *)malloc(sizeof(int) * N);
  int *Anum = (int *)malloc(sizeof(int) * N);
  int *B = (int *)malloc(sizeof(int) * N * 2);
  int *X = (int *)malloc(sizeof(int) * M);
  int *Y = (int *)malloc(sizeof(int) * M);
  for (i = 0; i < N; i++) {
    scanf("%d", &A[i]);
    A[i]--;
    Anum[i] = 0;
    B[i] = 0;
    B[N + i] = 0;
  }
  for (j = 0; j < M; j++) {
    scanf("%d%d", &X[j], &Y[j]);
    X[j]--;
    Y[j]--;
  }
  for (i = 0; i < N; i++) {
    B[N + A[i] - Anum[A[i]]]++;
    Anum[A[i]]++;
  }
  for (i = 0; i < N; i++) {
    if (B[N + i] == 0) {
      ans++;
    }
  }
  for (j = 0; j < M; j++) {

    old = A[X[j]];
    new = Y[j];
    A[X[j]] = Y[j];
    Anum[old]--;
    B[N + old - Anum[old]]--;
    if (B[N + old - Anum[old]] == 0 && old - Anum[old] >= 0) {
      ans++;
    }
    if (B[N + new - Anum[new]] == 0 && new - Anum[new] >= 0) {
      ans--;
    }
    B[N + new - Anum[new]]++;
    Anum[new]++;
    printf("%d\n", ans);
  }
  return 0;
}

fn solution() {
    input! {
        n: usize,
        m: usize,
        mut v: [usize; n],
        xy: [(usize1, usize); m]
    }
    let mut cnt = vec![0; n + 1];
    let mut ds = vec![0; n];
    for &a in &v {
        if cnt[a] < a {
            ds[a - cnt[a] - 1] += 1;
        }
        cnt[a] += 1;
    }
    let mut ans = ds.iter().filter(|&&x| x == 0).count();
    for &(x, y) in &xy {
        cnt[v[x]] -= 1;
        if cnt[v[x]] < v[x] {
            ds[v[x] - cnt[v[x]] - 1] -= 1;
            if ds[v[x] - cnt[v[x]] - 1] == 0 {
                ans += 1;
            }
        }
        if cnt[y] < y {
            if ds[y - cnt[y] - 1] == 0 {
                ans -= 1;
            }
            ds[y - cnt[y] - 1] += 1;
        }
        cnt[y] += 1;
        v[x] = y;
        println!("{}", ans);
    }
}


Berland State University has received a new update for the operating system. Initially it is installed only on the $$$1$$$-st computer.Update files should be copied to all $$$n$$$ computers. The computers are not connected to the internet, so the only way to transfer update files from one computer to another is to copy them using a patch cable (a cable connecting two computers directly). Only one patch cable can be connected to a computer at a time. Thus, from any computer where the update files are installed, they can be copied to some other computer in exactly one hour.Your task is to find the minimum number of hours required to copy the update files to all $$$n$$$ computers if there are only $$$k$$$ patch cables in Berland State University.

int solution() {
  int t;
  long long int n;
  long long int k;
  long long int done;
  long long int path;
  long long int h;
  scanf("%d%*c", &t);
  while (t > 0) {
    scanf("%lld %lld%*c", &n, &k);
    done = 1;
    n -= 1;
    h = 0;
    path = 1;
    while (n > 0) {
      if (2 * path <= k && 2 * path <= done) {
        path = 2 * path;
        n -= path;
        done += path;
        h += 1;
      } else if (path < k && k <= done) {
        path = k;
        n -= path;
        done += path;
        h += 1;
      } else {
        if (done == 1) {
          n -= path;
          done += path;
          h += 1;
        } else {
          h += n / path;
          if (n % path != 0) {
            h += 1;
          }
          n = 0;
        }
      }
    }
    printf("%lld\n", h);
    t -= 1;
  }
  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: u64 = it.next().unwrap().parse().unwrap();
        let k: u64 = it.next().unwrap().parse().unwrap();
        let mut hour = 0;
        let mut install = 1;
        while install < n {
            let new_install = k.min(install);
            if new_install == k {
                let to_install = n - install;
                let rem_hours = to_install / k;
                hour += rem_hours;
                if rem_hours * k < to_install {
                    hour += 1;
                }
                break;
            } else {
                hour += 1;
                install += new_install;
            }
        }
        let ans = format!("{}\n", hour);
        out.push_str(ans.as_str());
    }
    print!("{}", out);
    Ok(())
}


Given a permutation $$$p$$$ of length $$$n$$$, find its subsequence $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ of length at least $$$2$$$ such that:  $$$|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$$$ is as big as possible over all subsequences of $$$p$$$ with length at least $$$2$$$.  Among all such subsequences, choose the one whose length, $$$k$$$, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some (possibly, zero or all) elements.A permutation of length $$$n$$$ is an array of length $$$n$$$ in which every element from $$$1$$$ to $$$n$$$ occurs exactly once.

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

  while (t--) {
    int n = 0;
    scanf("%d", &n);

    int arr[n];
    int res[n];
    int tmp = 0;
    int r = 0;

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

    res[r++] = arr[0];

    for (int i = 1; i < (n - 1); i++) {
      if ((arr[i - 1] < arr[i]) != (arr[i] < arr[i + 1])) {
        res[r++] = arr[i];
      }
    }

    res[r++] = arr[n - 1];

    printf("%d\n", r);
    for (int i = 0; i < r; i++) {
      printf("%d ", res[i]);
    }
    printf("\n");
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let ss: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let mut ts: Vec<usize> = vec![ss[0]];
        for i in 1..(n - 1) {
            if ss[i - 1] < ss[i] && ss[i] > ss[i + 1] {
                ts.push(ss[i]);
            } else if ss[i - 1] == ss[i] && ss[i] != ss[i + 1] {
                ts.push(ss[i]);
            } else if ss[i - 1] > ss[i] && ss[i] < ss[i + 1] {
                ts.push(ss[i]);
            }
        }
        ts.push(ss[n - 1]);
        println!("{}", ts.len());
        for t in ts {
            print!("{} ", t);
        }
        println!();
    }
}


Score : <var>100</var> points

Problem Statement

There are <var>N</var> slimes lining up in a row.
Initially, the <var>i</var>-th slime from the left has a size of <var>a_i</var>.

Taro is trying to combine all the slimes into a larger slime.
He will perform the following operation repeatedly until there is only one slime:

Choose two adjacent slimes, and combine them into a new slime. The new slime has a size of <var>x + y</var>, where <var>x</var> and <var>y</var> are the sizes of the slimes before combining them. Here, a cost of <var>x + y</var> is incurred. The positional relationship of the slimes does not change while combining slimes.

Find the minimum possible total cost incurred.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 20 30 40

Sample Output 1

190

Taro should do as follows (slimes being combined are shown in bold):

(10, 20, 30, 40) → (30, 30, 40)

(30, 30, 40) → (60, 40)

(60, 40) → (100)

Sample Input 2

5
10 10 10 10 10

Sample Output 2

120

Taro should do, for example, as follows:

(10, 10, 10, 10, 10) → (20, 10, 10, 10)

(20, 10, 10, 10) → (20, 20, 10)

(20, 20, 10) → (20, 30)

(20, 30) → (50)

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 4

6
7 6 8 6 1 1

Sample Output 4

68

Taro should do, for example, as follows:

(7, 6, 8, 6, 1, 1) → (7, 6, 8, 6, 2)

(7, 6, 8, 6, 2) → (7, 6, 8, 8)

(7, 6, 8, 8) → (13, 8, 8)

(13, 8, 8) → (13, 16)

(13, 16) → (29)

fn solution() {
    input! {
        n: usize,
        v: [usize; n]
    }
    let mut tab: Vec<Vec<usize>> = vec![vec![usize::max_value(); n]; n];
    let mut ps: Vec<usize> = v
        .iter()
        .clone()
        .scan(0, |ac, x| {
            *ac += *x;
            Some(*ac)
        })
        .collect();
    ps.insert(0, 0);
    for i in 0..n {
        tab[i][i] = 0;
    }
    for d in 1..n {
        for i in 0..n - d {
            tab[i][i + d] = ps[i + d + 1] - ps[i]
                + (i..i + d)
                    .map(|x| tab[i][x] + tab[x + 1][i + d])
                    .min()
                    .unwrap();
        }
    }
    println!("{}", tab[0][n - 1]);
}


Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws each box vertically down on the first wi stairs of the staircase, that is, the box covers stairs with numbers 1, 2, ..., wi. Each thrown box flies vertically down until at least one of the two following events happen:  the bottom of the box touches the top of a stair;  the bottom of the box touches the top of a box, thrown earlier. We only consider touching of the horizontal sides of stairs and boxes, at that touching with the corners isn't taken into consideration. Specifically, that implies that a box with width wi cannot touch the stair number wi + 1.You are given the description of the staircase and the sequence in which Dima threw the boxes at it. For each box, determine how high the bottom of the box after landing will be. Consider a box to fall after the previous one lands.

int solution() {

  int n;
  int m;
  int i;
  int w;
  int h;

  double max = 0;

  scanf("%d", &n);

  int v[n];

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

  scanf("%d", &m);

  for (i = 0; i < m; i++) {
    scanf("%d %d", &w, &h);
    if (max > v[w - 1]) {
      max = max;
    } else {
      max = v[w - 1];
    }
    printf("%.f\n", max);
    max = max + h;
  }
  return 0;
}

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

    let a: Vec<i64> = buffer
        .split_whitespace()
        .filter_map(|str| str.parse::<i64>().ok())
        .collect();
    buffer = String::new();
    io::stdin().read_line(&mut buffer);
    let m = buffer
        .split_whitespace()
        .filter_map(|str| str.parse::<i64>().ok())
        .next()
        .unwrap();
    let mut last: i64 = -1;
    for _i in 0..m {
        buffer = String::new();
        io::stdin().read_line(&mut buffer);
        let o: Vec<i64> = buffer
            .split_whitespace()
            .filter_map(|str| str.parse::<i64>().ok())
            .collect();
        let w = o[0];
        let h = o[1];
        let answer = std::cmp::max(last, a[w as usize - 1]);
        println!("{}", answer);
        last = answer + h;
    }
}


One day, Vogons wanted to build a new hyperspace highway through a distant system with $$$n$$$ planets. The $$$i$$$-th planet is on the orbit $$$a_i$$$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.Vogons have two machines to do that.  The first machine in one operation can destroy any planet at cost of $$$1$$$ Triganic Pu.  The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $$$c$$$ Triganic Pus. Vogons can use each machine as many times as they want.Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int c;
    int count = 0;
    scanf("%d %d", &n, &c);

    int b[101];
    for (int i = 0; i < 101; i++) {
      b[i] = 0;
    }

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

    for (int i = 0; i < 101; i++) {
      if (b[i] > c) {
        count = count + c;
      } else {
        count = count + b[i];
      }
    }

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

  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let stdin_lock = stdin.lock();
    let mut line_iter = stdin_lock.lines();
    let t = line_iter
        .next()
        .unwrap()
        .unwrap()
        .as_str()
        .parse::<usize>()
        .unwrap();
    for _ in 0..t {
        let line1 = line_iter.next().unwrap().unwrap();
        let (n_str, c_str) = line1.split_once(' ').unwrap();
        let _n = n_str.parse::<usize>().unwrap();
        let c = c_str.parse::<usize>().unwrap();

        let mut orbit_counts = [0_usize; 101];

        let line2 = line_iter.next().unwrap().unwrap();
        let orbit_iter = line2
            .split(' ')
            .map(|orbit_str| orbit_str.parse::<usize>().unwrap());
        for orbit in orbit_iter {
            orbit_counts[orbit] += 1;
        }

        let mut min_cost: usize = 0;
        for orbit_count in orbit_counts {
            if orbit_count > 0 {
                min_cost += orbit_count.min(c);
            }
        }

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


Sayaka Saeki is a member of the student council, which has $$$n$$$ other members (excluding Sayaka). The $$$i$$$-th member has a height of $$$a_i$$$ millimeters.It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wants to arrange all the members in a line such that the amount of photogenic consecutive pairs of members is as large as possible.A pair of two consecutive members $$$u$$$ and $$$v$$$ on a line is considered photogenic if their average height is an integer, i.e. $$$\frac{a_u + a_v}{2}$$$ is an integer.Help Sayaka arrange the other members to maximize the number of photogenic consecutive pairs.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    scanf("%d", &n);
    int a[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    int odd = 0;
    int even = 0;
    int o[n];
    int e[n];
    for (int i = 0; i < n; i++) {
      o[i] = 0;
      e[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      if (a[i] % 2 == 1) {
        o[odd] = a[i];
        odd++;
      }
      if (a[i] % 2 == 0) {
        e[even] = a[i];
        even++;
      }
    }
    for (int i = 0; i < odd; i++) {
      printf("%d ", o[i]);
    }
    for (int i = 0; i < even; i++) {
      printf("%d ", e[i]);
    }
    printf("\n");
  }
  return 0;
}

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

    for _ in 0..t {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let _n: i64 = line.trim().parse().unwrap();

        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut a: Vec<i64> = line
            .split_whitespace()
            .map(|x| x.parse().unwrap())
            .collect();

        a.sort_by_key(|x| x % 2);

        for item in a {
            print!("{} ", item);
        }
        println!();
    }
}


You are given four positive integers $$$n$$$, $$$m$$$, $$$a$$$, $$$b$$$ ($$$1 \le b \le n \le 50$$$; $$$1 \le a \le m \le 50$$$). Find any such rectangular matrix of size $$$n \times m$$$ that satisfies all of the following conditions:  each row of the matrix contains exactly $$$a$$$ ones;  each column of the matrix contains exactly $$$b$$$ ones;  all other elements are zeros. If the desired matrix does not exist, indicate this.For example, for $$$n=3$$$, $$$m=6$$$, $$$a=2$$$, $$$b=1$$$, there exists a matrix satisfying the conditions above:$$$$$$ \begin{vmatrix} 0 & 1 & 0 & 0 & 0 & 1 \\ 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \end{vmatrix} $$$$$$

int solution() {
  int t;
  int m;
  int n;
  int i;
  int b;
  int a;
  int j;
  int count;
  scanf("%d", &t);
  while (t--) {
    scanf("%d%d%d%d", &n, &m, &a, &b);
    if (n * a != m * b) {
      printf("NO\n");
      continue;
    }
    printf("YES\n");
    int aa[51][51];
    i = -1;
    while (++i < n) {
      j = -1;
      while (++j < m) {
        aa[i][j] = 0;
      }
    }
    i = 0;
    j = 0;
    count = 0;
    while (count < n * a) {
      if (aa[i % n][j % m] == 0) {
        aa[i % n][j % m] = 1;
        count++;
        i++;
        j++;
      } else {
        i++;
      }
    }
    i = -1;
    while (++i < n) {
      j = -1;
      while (++j < m) {
        putchar(aa[i][j] + '0');
      }
      putchar('\n');
    }
  }
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut out = Vec::new();
    for _ in 0..t {
        let n: usize = itr.next().unwrap().parse().unwrap();
        let m: usize = itr.next().unwrap().parse().unwrap();
        let a: usize = itr.next().unwrap().parse().unwrap();
        let b: usize = itr.next().unwrap().parse().unwrap();
        if n * a != m * b {
            writeln!(out, "NO").ok();
        } else {
            writeln!(out, "YES").ok();
            let mut ans: Vec<Vec<usize>> = vec![vec![0; m]; n];

            let mut x = 0;
            for i in 0..n {
                for _ in 0..a {
                    ans[i][x] = 1;
                    x = (x + 1) % m;
                }
            }

            for i in 0..n {
                for j in 0..m {
                    write!(out, "{}", ans[i][j]).ok();
                }
                writeln!(out).ok();
            }
        }
    }
    stdout().write_all(&out).unwrap();
}


Ania has a large integer $$$S$$$. Its decimal representation has length $$$n$$$ and doesn't contain any leading zeroes. Ania is allowed to change at most $$$k$$$ digits of $$$S$$$. She wants to do it in such a way that $$$S$$$ still won't contain any leading zeroes and it'll be minimal possible. What integer will Ania finish with?

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

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let mut s = input.trim().bytes().map(|x| x - b'0').collect::<Vec<u8>>();

    if k != 0 {
        let mut start = 0;
        if s.len() > 1 {
            start = 1;
            if s[0] != 1 {
                s[0] = 1;
                k -= 1;
            }
        }

        if k != 0 {
            for d in start..s.len() {
                if s[d] != 0 {
                    s[d] = 0;
                    k -= 1;
                    if k == 0 {
                        break;
                    }
                }
            }
        }
    }

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

    for d in s.iter() {
        write!(buf, "{}", d);
    }
    writeln!(buf);
}


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

int solution() {

  int n;
  int k;
  scanf("%d %d", &n, &k);
  char c;
  scanf("%c", &c);
  char input[n];
  int chars[26];
  for (int i = 0; i < 26; i++) {
    chars[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    scanf("%c", &c);
    input[i] = c;
  }
  scanf("%c", &c);
  for (int i = 0; i < k; i++) {
    scanf("%c", &c);
    int tmp = c - 'a';
    chars[tmp] = 1;
    scanf("%c", &c);
  }
  long long count = 0;
  long long res = 0;
  for (int i = 0; i < n; i++) {
    if (chars[input[i] - 'a'] == 1) {
      count++;
    } else {
      res += (count * (count + 1)) / 2;
      count = 0;
    }
  }
  res += (count * (count + 1)) / 2;

  printf("%lld", res);
  return 0;
}

fn solution() {
    let mut str = String::new();
    let _b1 = stdin().read_line(&mut str).unwrap();
    let mut iter = str.split_whitespace();
    let m: i64 = iter.next().unwrap().parse().unwrap();
    let _n: i64 = iter.next().unwrap().parse().unwrap();

    let mut test_string = String::new();
    let _b1 = stdin().read_line(&mut test_string).unwrap();

    str.clear();
    let _b1 = stdin().read_line(&mut str).unwrap();
    let mut iter = str.split_whitespace();
    let mut work: Vec<char> = Vec::new();
    loop {
        match iter.next() {
            Some(c) => work.push(c.chars().next().unwrap()),
            None => break,
        }
    }
    let mut last: i64 = -1;
    let mut total: i64 = 0;
    test_string = test_string.trim().to_string();
    test_string.push('1');
    let mut char_iter = test_string.chars();
    for i in 0..(m + 1) {
        let c = char_iter.next().unwrap();
        if work.contains(&c) {
        } else {
            let x = i - last - 1;
            total += x * (x + 1);
            last = i;
        }
    }

    println!("{}", total / 2);
}