Score : <var>300</var> points

Problem Statement

Takahashi participated in a contest on AtCoder.

The contest had <var>N</var> problems.

Takahashi made <var>M</var> submissions during the contest.

The <var>i</var>-th submission was made for the <var>p_i</var>-th problem and received the verdict <var>S_i</var> (AC or WA).

The number of Takahashi's correct answers is the number of problems on which he received an AC once or more.

The number of Takahashi's penalties is the sum of the following count for the problems on which he received an AC once or more: the number of WAs received before receiving an AC for the first time on that problem.

Find the numbers of Takahashi's correct answers and penalties.

Constraints

<var>N</var>, <var>M</var>, and <var>p_i</var> are integers.

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

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

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

<var>S_i</var> is AC or WA.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>p_1</var> <var>S_1</var>
<var>:</var>
<var>p_M</var> <var>S_M</var>

Output

Print the number of Takahashi's correct answers and the number of Takahashi's penalties.

Sample Input 1

2 5
1 WA
1 AC
2 WA
2 AC
2 WA

Sample Output 1

2 2

In his second submission, he received an AC on the first problem for the first time. Before this, he received one WA on this problem.

In his fourth submission, he received an AC on the second problem for the first time. Before this, he received one WA on this problem.

Thus, he has two correct answers and two penalties.

Sample Input 2

100000 3
7777 AC
7777 AC
7777 AC

Sample Output 2

1 0

Note that it is pointless to get an AC more than once on the same problem.

Sample Input 3

6 0

Sample Output 3

0 0

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

    let mut letter = buffer.split_whitespace();
    let n = letter.next().unwrap().to_string().parse::<usize>().unwrap();
    let m = letter.next().unwrap().to_string().parse::<usize>().unwrap();

    let mut sub = vec![(0, 0); n];
    for _ in 0..m {
        let mut res = String::new();
        io::stdin().read_line(&mut res).unwrap();

        let mut res = res.split_whitespace();
        let num = res.next().unwrap().to_string().parse::<usize>().unwrap() - 1;
        let ans = res.next().unwrap().to_string();

        if &ans == "AC" {
            sub[num].0 += 1;
        } else if sub[num].0 == 0 {
            sub[num].1 += 1;
        }
    }

    let acc = sub
        .iter()
        .filter(|&&(a, _r)| a > 0)
        .collect::<Vec<_>>()
        .len();
    let pen: usize = sub.iter().map(|&(a, r)| if a > 0 { r } else { 0 }).sum();

    println!("{} {}", acc, pen);
}


Score : <var>300</var> points

Problem Statement

Sitting in a station waiting room, Joisino is gazing at her train ticket.

The ticket is numbered with four digits <var>A</var>, <var>B</var>, <var>C</var> and <var>D</var> in this order, each between <var>0</var> and <var>9</var> (inclusive).

In the formula <var>A</var> <var>op1</var> <var>B</var> <var>op2</var> <var>C</var> <var>op3</var> <var>D</var> <var>=</var> <var>7</var>, replace each of the symbols <var>op1</var>, <var>op2</var> and <var>op3</var> with + or - so that the formula holds.

The given input guarantees that there is a solution. If there are multiple solutions, any of them will be accepted.

Constraints

<var>0≤A,B,C,D≤9</var>

All input values are integers.

It is guaranteed that there is a solution.

Input

Input is given from Standard Input in the following format:

<var>ABCD</var>

Output

Print the formula you made, including the part =7.

Use the signs + and -.

Do not print a space between a digit and a sign.

Sample Input 1

1222

Sample Output 1

1+2+2+2=7

This is the only valid solution.

Sample Input 2

0290

Sample Output 2

0-2+9+0=7

<var>0 - 2 + 9 - 0 = 7</var> is also a valid solution.

Sample Input 3

3242

Sample Output 3

3+2+4-2=7

fn solution() {
    let stdin = std::io::stdin();
    let mut reader = std::io::BufReader::new(stdin.lock());
    let mut s = String::new();
    reader.read_line(&mut s).unwrap();
    let s = s.trim();
    let abcd: Vec<i32> = s.chars().map(|x| x.to_string().parse().unwrap()).collect();
    let a = abcd[0];
    let b = abcd[1];
    let c = abcd[2];
    let d = abcd[3];

    let abcd = [
        [a, b, c, d],
        [a, -b, c, d],
        [a, b, -c, d],
        [a, b, c, -d],
        [a, -b, -c, d],
        [a, b, -c, -d],
        [a, -b, c, -d],
        [a, -b, -c, -d],
    ];
    let ans = abcd.iter().find(|x| x.iter().sum::<i32>() == 7).unwrap();
    println!("{}{:+}{:+}{:+}=7", ans[0], ans[1], ans[2], ans[3]);
}


Score : <var>200</var> points

Problem Statement

There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.

Takahashi says: "there are <var>X</var> animals in total in the garden, and they have <var>Y</var> legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If there is a combination of numbers of cranes and turtles in which the statement is correct, print Yes; otherwise, print No.

Sample Input 1

3 8

Sample Output 1

Yes

The statement "there are <var>3</var> animals in total in the garden, and they have <var>8</var> legs in total" is correct if there are two cranes and one turtle. Thus, there is a combination of numbers of cranes and turtles in which the statement is correct.

Sample Input 2

2 100

Sample Output 2

No

There is no combination of numbers of cranes and turtles in which this statement is correct.

Sample Input 3

1 2

Sample Output 3

Yes

We also consider the case in which there are only cranes or only turtles.

int solution(void) {

  int x[2];

  scanf("%d", &x[0]);
  scanf("%d", &x[1]);

  int sum = 0;
  int i = 0;
  int flag = 0;

  for (i = 0; i <= x[0]; i++) {
    sum = (x[0] - i) * 2 + i * 4;

    if (sum == x[1]) {
      flag = 1;
      break;
    }
  }

  if (flag) {
    printf("Yes");
  } else {
    printf("No");
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let nums: Vec<i64> = buf
        .split_whitespace()
        .filter_map(|x| x.parse::<i64>().ok())
        .collect();
    let x = nums[0];
    let y = nums[1];
    if y % 2 == 1 {
        println!("No");
    } else if 2 * x <= y && y <= 4 * x {
        println!("Yes");
    } else {
        println!("No");
    }
}


Score : <var>700</var> points

Problem Statement

<var>N</var> people are waiting in a single line in front of the Takahashi Store. The cash on hand of the <var>i</var>-th person from the front of the line is a positive integer <var>A_i</var>.

Mr. Takahashi, the shop owner, has decided on the following scheme: He picks a product, sets a positive integer <var>P</var> indicating its price, and shows this product to customers in order, starting from the front of the line. This step is repeated as described below.

At each step, when a product is shown to a customer, if price <var>P</var> is equal to or less than the cash held by that customer at the time, the customer buys the product and Mr. Takahashi ends the current step. That is, the cash held by the first customer in line with cash equal to or greater than <var>P</var> decreases by <var>P</var>, and the next step begins.

Mr. Takahashi can set the value of positive integer <var>P</var> independently at each step.

He would like to sell as many products as possible. However, if a customer were to end up with <var>0</var> cash on hand after a purchase, that person would not have the fare to go home. Customers not being able to go home would be a problem for Mr. Takahashi, so he does not want anyone to end up with <var>0</var> cash.

Help out Mr. Takahashi by writing a program that determines the maximum number of products he can sell, when the initial cash in possession of each customer is given.

Constraints

<var>1 ≦ | N | ≦ 100000</var>

<var>1 ≦ A_i ≦ 10^9(1 ≦ i ≦ N)</var>

All inputs are integers.

Input

Inputs are provided from Standard Inputs in the following form.

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

Output

Output an integer representing the maximum number of products Mr. Takahashi can sell.

Sample Input 1

3
3
2
5

Sample Output 1

3

As values of <var>P</var>, select in order <var>1, 4, 1</var>.

Sample Input 2

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

Sample Output 2

18

int solution() {
  long ans = 0;
  int N;
  scanf("%d", &N);
  long A[N];
  int i = 0;
  for (i = 0; i < N; i++) {
    scanf("%ld", &A[i]);
  }
  ans += A[0] - 1;
  long r = 2;
  for (i = 1; i < N; i++) {
    if (A[i] != r) {
      ans += (A[i] - 1) / r;
    } else {
      r++;
    }
  }
  printf("%ld\n", ans);
  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()
    };
    let A: Vec<i64> = (0..N)
        .map(|_| {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        })
        .collect();

    let (ans, _) = A.iter().fold((0, 1), |(res, h), &a| {
        (res + (a - 1) / h, if h == a || h == 1 { h + 1 } else { h })
    });

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


Luis has a sequence of $$$n+1$$$ integers $$$a_1, a_2, \ldots, a_{n+1}$$$. For each $$$i = 1, 2, \ldots, n+1$$$ it is guaranteed that $$$0\leq a_i < n$$$, or $$$a_i=n^2$$$. He has calculated the sum of all the elements of the sequence, and called this value $$$s$$$. Luis has lost his sequence, but he remembers the values of $$$n$$$ and $$$s$$$. Can you find the number of elements in the sequence that are equal to $$$n^2$$$?We can show that the answer is unique under the given constraints.

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

  long long int ans[n];

  for (int i = 0; i < n; i++) {
    ans[i] = (arr[i][1] / (arr[i][0] * arr[i][0]));
  }

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

  return 0;
}

fn solution() {
    let mut count = 0u64;
    let mut t = String::new();
    io::stdin().read_line(&mut t).expect("error reading line");
    let t: u64 = t.trim().parse().expect("enter a number");
    loop {
        count += 1;

        let mut line = String::new();
        io::stdin()
            .read_line(&mut line)
            .expect("error reading line");
        let mut iter = line.split_whitespace();
        let n: u64 = iter.next().unwrap().parse().unwrap();
        let s: u64 = iter.next().unwrap().parse().unwrap();
        println!("{}", s / (n * n));
        if count == t {
            break;
        }
    }
}


You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains:   $$$a$$$ letters 'A';  $$$b$$$ letters 'B';  $$$c$$$ letters 'C';  no other letters;  exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one).

fn solution() {
    let reader = io::stdin();
    let mut buffer = String::new();
    reader.read_line(&mut buffer).unwrap();
    let mut t: i32 = buffer.trim().parse().unwrap();
    while t > 0 {
        let mut buffer = String::new();
        reader.read_line(&mut buffer).unwrap();
        let [mut a, mut b, mut c, m] = <[i32; 4]>::try_from(
            buffer
                .split_whitespace()
                .map(|s| s.parse::<i32>().unwrap())
                .collect::<Vec<i32>>(),
        )
        .unwrap();
        if a > b {
            std::mem::swap(&mut a, &mut b);
        }
        if b > c {
            std::mem::swap(&mut b, &mut c);
        }
        let min_v = std::cmp::max(0, c - (a + b + 1));
        let max_v = (a - 1) + (b - 1) + (c - 1);
        if m >= min_v && m <= max_v {
            println!("YES");
        } else {
            println!("NO");
        }
        t -= 1;
    }
}


Simple Calculator

Write a program which reads two integers <var>a</var>, <var>b</var> and an operator <var>op</var>, and then prints the value of <var>a</var> <var>op</var> <var>b</var>.

The operator <var>op</var> is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

The input consists of multiple datasets. Each dataset is given in the following format.

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

The input ends with a dataset where <var>op</var> = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

 0 ≤ <var>a</var>, <var>b</var> ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108

fn solution() {
    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let uline = line.unwrap();
        let vec: Vec<&str> = uline.split_whitespace().collect();
        let a: i32 = vec[0].parse().unwrap_or(0);
        let o: &str = vec[1];
        let b: i32 = vec[2].parse().unwrap_or(0);
        if o == "?" {
            break;
        } else if o == "+" {
            println!("{}", a + b);
        } else if o == "-" {
            println!("{}", a - b);
        } else if o == "*" {
            println!("{}", a * b);
        } else if o == "/" {
            println!("{}", a / b);
        }
    }
}


$$$n$$$ heroes fight against each other in the Arena. Initially, the $$$i$$$-th hero has level $$$a_i$$$.Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $$$1$$$.The winner of the tournament is the first hero that wins in at least $$$100^{500}$$$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.Calculate the number of possible winners among $$$n$$$ heroes.

int solution() {
  int T = 0;
  scanf("%d", &T);
  int a[500];

  for (int i = 0; i < T; i++) {
    int n = 0;
    scanf("%d", &n);
    int min = 100;
    int counter = 0;
    for (int j = 0; j < n; j++) {
      int num = 0;
      scanf("%d", &num);
      if (min > num) {
        min = num;
        counter = 1;
      } else if (min == num) {
        counter++;
      }
    }
    a[i] = n - counter;
  }

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

  return 0;
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let mut v = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<u32>().unwrap())
            .collect::<Vec<_>>();
        v.sort_unstable();
        let r = v.iter().filter(|&n| n > &v[0]).count();
        writeln!(o, "{}", r).ok();
    }
}


Suppose you have a special $$$x$$$-$$$y$$$-counter. This counter can store some value as a decimal number; at first, the counter has value $$$0$$$. The counter performs the following algorithm: it prints its lowest digit and, after that, adds either $$$x$$$ or $$$y$$$ to its value. So all sequences this counter generates are starting from $$$0$$$. For example, a $$$4$$$-$$$2$$$-counter can act as follows:  it prints $$$0$$$, and adds $$$4$$$ to its value, so the current value is $$$4$$$, and the output is $$$0$$$;  it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$8$$$, and the output is $$$04$$$;  it prints $$$8$$$, and adds $$$4$$$ to its value, so the current value is $$$12$$$, and the output is $$$048$$$;  it prints $$$2$$$, and adds $$$2$$$ to its value, so the current value is $$$14$$$, and the output is $$$0482$$$;  it prints $$$4$$$, and adds $$$4$$$ to its value, so the current value is $$$18$$$, and the output is $$$04824$$$. This is only one of the possible outputs; for example, the same counter could generate $$$0246802468024$$$ as the output, if we chose to add $$$2$$$ during each step.You wrote down a printed sequence from one of such $$$x$$$-$$$y$$$-counters. But the sequence was corrupted and several elements from the sequence could be erased.Now you'd like to recover data you've lost, but you don't even know the type of the counter you used. You have a decimal string $$$s$$$ — the remaining data of the sequence. For all $$$0 \le x, y < 10$$$, calculate the minimum number of digits you have to insert in the string $$$s$$$ to make it a possible output of the $$$x$$$-$$$y$$$-counter. Note that you can't change the order of digits in string $$$s$$$ or erase any of them; only insertions are allowed.

fn solution() {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();
    let line: Vec<u8> = line.trim().as_bytes().iter().map(|&it| it - b'0').collect();

    let mut from_to = [[0; 10]; 10];
    for i in 0..line.len() - 1 {
        let a = line[i] as usize;
        let b = line[i + 1] as usize;
        from_to[a][b] += 1;
    }

    for i in 0..10 {
        for j in 0..10 {
            let mut steps = [[2_000_000_000; 10]; 10];

            for a in 0..10 {
                for x in 0..10 {
                    for y in 0..10 {
                        if x + y == 0 {
                            continue;
                        }
                        let b = (a + i * x + j * y) % 10;
                        steps[a][b] = steps[a][b].min(x + y - 1);
                    }
                }
            }

            let mut answer = 0;
            'l: for a in 0..10 {
                for b in 0..10 {
                    if steps[a][b] == 2_000_000_000 && from_to[a][b] != 0 {
                        answer = -1;
                        break 'l;
                    }
                    answer += (steps[a][b] * from_to[a][b]) as isize;
                }
            }
            print!("{} ", answer);
        }
        println!();
    }
}


An integer array $$$a_1, a_2, \ldots, a_n$$$ is being transformed into an array of lowercase English letters using the following prodecure:While there is at least one number in the array:   Choose any number $$$x$$$ from the array $$$a$$$, and any letter of the English alphabet $$$y$$$.  Replace all occurrences of number $$$x$$$ with the letter $$$y$$$. For example, if we initially had an array $$$a = [2, 3, 2, 4, 1]$$$, then we could transform it the following way:  Choose the number $$$2$$$ and the letter c. After that $$$a = [c, 3, c, 4, 1]$$$.  Choose the number $$$3$$$ and the letter a. After that $$$a = [c, a, c, 4, 1]$$$.  Choose the number $$$4$$$ and the letter t. After that $$$a = [c, a, c, t, 1]$$$.  Choose the number $$$1$$$ and the letter a. After that $$$a = [c, a, c, t, a]$$$. After the transformation all letters are united into a string, in our example we get the string "cacta".Having the array $$$a$$$ and the string $$$s$$$ determine if the string $$$s$$$ could be got from the array $$$a$$$ after the described transformation?

int solution(void) {

  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    scanf("%d", &n);
    int a[n];
    for (int j = 0; j < n; j++) {
      scanf("%d", &a[j]);
    }
    char h[n + 1];
    scanf("%s", h);
    int f = 1;

    for (int m = 0; m < n; m++) {

      for (int l = 0; l < n + 1; l++) {
        if (a[m] == a[l] && h[m] != h[l]) {

          f = 0;
          break;
        }
        f = 1;
      }
      if (f == 0) {
        break;
      }
    }
    if (f == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }

  return 0;
}

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

    let mut solutions = Vec::new();
    'outer: for _ in 0..t {
        let mut n = String::new();
        io::stdin().read_line(&mut n).expect("Erorr");
        let _: i32 = n.trim().parse().unwrap();

        let mut a = String::new();
        io::stdin().read_line(&mut a).expect("Error");
        let a: Vec<i32> = a
            .trim()
            .split(' ')
            .map(|x| x.parse::<i32>().unwrap())
            .collect();

        let mut s = String::new();
        io::stdin().read_line(&mut s).expect("Error");

        let mut pairs: Vec<(i32, char)> = Vec::new();
        'inner: for (i, c) in s.trim().chars().enumerate() {
            for (vi, vc) in &pairs {
                if *vi == a[i] {
                    if c == *vc {
                        continue 'inner;
                    } else {
                        solutions.push(false);
                        continue 'outer;
                    }
                }
            }
            pairs.push((a[i], c));
        }
        solutions.push(true);
    }

    for sol in solutions {
        if sol {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


You are given a positive integer $$$n$$$.The weight of a permutation $$$p_1, p_2, \ldots, p_n$$$ is the number of indices $$$1\le i\le n$$$ such that $$$i$$$ divides $$$p_i$$$. Find a permutation $$$p_1,p_2,\dots, p_n$$$ with the minimum possible weight (among all permutations of length $$$n$$$).A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

fn solution() -> Result<(), std::io::Error> {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();
    let t = lines.next().unwrap()?.parse::<i32>().unwrap();
    for _ in 0..t {
        let n = lines.next().unwrap()?.parse::<i32>().unwrap();
        let res: Vec<_> = if n % 2 == 0 {
            (1..=n)
                .map(|i| if i % 2 == 0 { i - 1 } else { i + 1 })
                .map(|i| i.to_string())
                .collect()
        } else {
            ["1".to_owned()]
                .into_iter()
                .chain(
                    (2..=n)
                        .map(|i| if i % 2 == 0 { i + 1 } else { i - 1 })
                        .map(|i| i.to_string()),
                )
                .collect()
        };
        println!("{}", res.join(" "));
    }
    Ok(())
}


Score : <var>100</var> points

Problem Statement

We have five variables <var>x_1, x_2, x_3, x_4,</var> and <var>x_5</var>.

The variable <var>x_i</var> was initially assigned a value of <var>i</var>.

Snuke chose one of these variables and assigned it <var>0</var>.

You are given the values of the five variables after this assignment.

Find out which variable Snuke assigned <var>0</var>.

Constraints

The values of <var>x_1, x_2, x_3, x_4,</var> and <var>x_5</var> given as input are a possible outcome of the assignment by Snuke.

Input

Input is given from Standard Input in the following format:

<var>x_1</var> <var>x_2</var> <var>x_3</var> <var>x_4</var> <var>x_5</var>

Output

If the variable Snuke assigned <var>0</var> was <var>x_i</var>, print the integer <var>i</var>.

Sample Input 1

0 2 3 4 5

Sample Output 1

1

In this case, Snuke assigned <var>0</var> to <var>x_1</var>, so we should print <var>1</var>.

Sample Input 2

1 2 0 4 5

Sample Output 2

3

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let item = buf.split_whitespace().filter_map(|x| x.parse::<i64>().ok());
    for (ix, v) in item.enumerate() {
        if v == 0 {
            println!("{}", ix + 1);
        }
    }
}


Mihai plans to watch a movie. He only likes palindromic movies, so he wants to skip some (possibly zero) scenes to make the remaining parts of the movie palindromic.You are given a list $$$s$$$ of $$$n$$$ non-empty strings of length at most $$$3$$$, representing the scenes of Mihai's movie.A subsequence of $$$s$$$ is called awesome if it is non-empty and the concatenation of the strings in the subsequence, in order, is a palindrome.Can you help Mihai check if there is at least one awesome subsequence of $$$s$$$?A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforces", "reality", "ab" are not.A sequence $$$a$$$ is a non-empty subsequence of a non-empty sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero, but not all) elements.

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

    let stdin = stdin.lock();
    let stdout = stdout.lock();
    let mut stdout = BufWriter::new(stdout);

    let stdin = &mut stdin.lines().map(Result::unwrap);

    let nn = stdin.next().unwrap().parse().unwrap();
    let chr = |c| ((c - b'a') & 31) as usize;

    for _ii in 0..nn {
        let mut pending3 = [[[0u8; 32]; 32]; 32];
        let mut pending2 = [[0u8; 32]; 32];

        let n: usize = stdin.next().unwrap().parse().unwrap();
        let mut data = stdin.take(n).map(String::into_bytes);
        let res = data.any(|s| match s[..] {
            [_] => true,
            [a, b] | [a, _, b] if a == b => true,
            [a, b] => {
                let (a, b) = (chr(a), chr(b));
                pending2[b][a] = 3;
                pending2[a][b] != 0
            }
            [a, b, c] => {
                let (a, b, c) = (chr(a), chr(b), chr(c));
                pending3[c][b][a] = 1;
                pending2[b][a] |= 2;
                ((pending2[b][c] | pending3[a][b][c]) & 1) != 0
            }
            _ => false,
        });

        data.for_each(drop);
        writeln!(stdout, "{}", if res { "YES" } else { "NO" }).unwrap();
    }

    stdout.flush().unwrap();
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> consisting of lowercase English letters.
Find the lexicographically (alphabetically) smallest lowercase English letter that does not occur in <var>S</var>.
If every lowercase English letter occurs in <var>S</var>, print None instead.

Constraints

<var>1 \leq |S| \leq 10^5</var> (<var>|S|</var> is the length of string <var>S</var>.)

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the lexicographically smallest lowercase English letter that does not occur in <var>S</var>.
If every lowercase English letter occurs in <var>S</var>, print None instead.

Sample Input 1

atcoderregularcontest

Sample Output 1

b

The string atcoderregularcontest contains a, but does not contain b.

Sample Input 2

abcdefghijklmnopqrstuvwxyz

Sample Output 2

None

This string contains every lowercase English letter.

Sample Input 3

fajsonlslfepbjtsaayxbymeskptcumtwrmkkinjxnnucagfrg

Sample Output 3

d

int solution() {

  char s[100000];
  scanf("%s", s);

  unsigned int allbit = 0;
  unsigned int bit = 0;
  for (unsigned int i = 0; s[i] != '\0'; i++) {
    bit = 1;
    bit = bit << (s[i] - 0x61);
    allbit = allbit | bit;
  }

  unsigned int expected_all = 0;
  for (unsigned int i = 0; i < 26; i++) {
    bit = 1;
    bit = bit << i;
    expected_all = expected_all | bit;
  }

  if (allbit == expected_all) {
    printf("None\n");
    return 0;
  }

  for (int i = 0; i < 26; i++) {
    if ((~allbit >> i) & 0x1) {
      printf("%c\n", i + 0x61);
      break;
    }
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let s = buf.trim().chars().collect::<Vec<char>>();
    let mut set = HashSet::new();
    for i in s {
        set.insert(i);
    }
    let mut a = b'a';
    let mut flag = true;
    while a <= b'z' {
        if set.insert(a as char) {
            break;
        }
        if a == b'z' {
            flag = false;
        }
        a += 1;
    }
    if flag {
        println!("{}", (a as char));
    } else {
        println!("None");
    }
}


Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has $$$a$$$ vanilla cookies and $$$b$$$ chocolate cookies for the party.She invited $$$n$$$ guests of the first type and $$$m$$$ guests of the second type to the party. They will come to the party in some order. After coming to the party, each guest will choose the type of cookie (vanilla or chocolate) to eat. There is a difference in the way how they choose that type:If there are $$$v$$$ vanilla cookies and $$$c$$$ chocolate cookies at the moment, when the guest comes, then  if the guest of the first type: if $$$v>c$$$ the guest selects a vanilla cookie. Otherwise, the guest selects a chocolate cookie.  if the guest of the second type: if $$$v>c$$$ the guest selects a chocolate cookie. Otherwise, the guest selects a vanilla cookie. After that:  If there is at least one cookie of the selected type, the guest eats one.  Otherwise (there are no cookies of the selected type), the guest gets angry and returns to home. Anna wants to know if there exists some order of guests, such that no one guest gets angry. Your task is to answer her question.

int solution() {
  unsigned long long int a;
  unsigned long long int b;
  unsigned long long int n;
  unsigned long long int m;
  int t;

  scanf("%d", &t);

  while (t) {
    scanf("%llu%llu%llu%llu", &a, &b, &n, &m);
    if ((a + b) < (n + m) || (a <= b && a < m) || (a >= b && b < m)) {
      printf("No\n");
    } else {
      printf("Yes\n");
    }
    t--;
  }
  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 xs: Vec<u64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let (a, b, n, m) = (xs[0], xs[1], xs[2], xs[3]);
        let c = min(a, b);
        let ok = m <= c && m + n <= a + b;
        println!("{}", if ok { "Yes" } else { "No" });
    }
}


For a collection of integers $$$S$$$, define $$$\operatorname{mex}(S)$$$ as the smallest non-negative integer that does not appear in $$$S$$$.NIT, the cleaver, decides to destroy the universe. He is not so powerful as Thanos, so he can only destroy the universe by snapping his fingers several times.The universe can be represented as a 1-indexed array $$$a$$$ of length $$$n$$$. When NIT snaps his fingers, he does the following operation on the array:  He selects positive integers $$$l$$$ and $$$r$$$ such that $$$1\le l\le r\le n$$$. Let $$$w=\operatorname{mex}(\{a_l,a_{l+1},\dots,a_r\})$$$. Then, for all $$$l\le i\le r$$$, set $$$a_i$$$ to $$$w$$$. We say the universe is destroyed if and only if for all $$$1\le i\le n$$$, $$$a_i=0$$$ holds.Find the minimum number of times NIT needs to snap his fingers to destroy the universe. That is, find the minimum number of operations NIT needs to perform to make all elements in the array equal to $$$0$$$.

fn solution() {
    input! {
        name = reader,
        tests: usize
    }
    for _ in 0..tests {
        input! {
            use reader,
            n: usize,
            a: [u32; n]
        }
        let mut a = VecDeque::from(a);
        while let Some(0) = a.front() {
            a.pop_front();
        }
        while let Some(0) = a.back() {
            a.pop_back();
        }
        let found0 = a.iter().position(|&x| x == 0).is_some();
        let ans = if a.is_empty() {
            0
        } else if found0 {
            2
        } else {
            1
        };
        println!("{}", ans);
    }
}


You are given four integers $$$n$$$, $$$B$$$, $$$x$$$ and $$$y$$$. You should build a sequence $$$a_0, a_1, a_2, \dots, a_n$$$ where $$$a_0 = 0$$$ and for each $$$i \ge 1$$$ you can choose:   either $$$a_i = a_{i - 1} + x$$$  or $$$a_i = a_{i - 1} - y$$$. Your goal is to build such a sequence $$$a$$$ that $$$a_i \le B$$$ for all $$$i$$$ and $$$\sum\limits_{i=0}^{n}{a_i}$$$ is maximum possible.

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

  for (int i = 0; i < t; i++) {
    long long int sum = 0;
    long int n = 0;
    long long int B = 0;
    long long int x = 0;
    long long int y = 0;
    scanf("%ld%lld%lld%lld", &n, &B, &x, &y);
    long long int a[n + 1];
    a[0] = 0;
    for (long int j = 1; j <= n; j++) {
      if ((a[j - 1] + x) <= B) {
        a[j] = a[j - 1] + x;
      } else {
        a[j] = a[j - 1] - y;
      }
    }
    for (long int j = 0; j <= n; j++) {
      sum += a[j];
    }
    printf("%lld\n", sum);
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut stdin = stdin.lock();
    let stdout = io::stdout();
    let stdout_handle = stdout.lock();
    let mut out_buffer = BufWriter::with_capacity(65536, stdout_handle);

    let mut line = String::new();
    stdin.read_line(&mut line).unwrap();
    let t: usize = line.trim().parse().unwrap();

    for _t in 0..t {
        line.clear();
        stdin.read_line(&mut line).unwrap();
        let mut values = line.split_ascii_whitespace();
        let length: u64 = values.next().unwrap().parse().unwrap();
        let max_value: i64 = values.next().unwrap().parse().unwrap();
        let add: i64 = values.next().unwrap().parse().unwrap();
        let sub: i64 = values.next().unwrap().parse().unwrap();

        let mut max_sum: i64 = 0;
        let mut current_value: i64 = 0;
        for _i in 0..length {
            if current_value + add <= max_value {
                current_value += add;
            } else {
                current_value -= sub;
            }
            max_sum += current_value;
        }

        writeln!(&mut out_buffer, "{}", max_sum).unwrap();
    }
    out_buffer.flush().unwrap();
}


You are given an array of $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. After you watched the amazing film "Everything Everywhere All At Once", you came up with the following operation.In one operation, you choose $$$n-1$$$ elements of the array and replace each of them with their arithmetic mean (which doesn't have to be an integer). For example, from the array $$$[1, 2, 3, 1]$$$ we can get the array $$$[2, 2, 2, 1]$$$, if we choose the first three elements, or we can get the array $$$[\frac{4}{3}, \frac{4}{3}, 3, \frac{4}{3}]$$$, if we choose all elements except the third.Is it possible to make all elements of the array equal by performing a finite number of such operations?

int solution() {

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

  float arr[50];
  int n = 0;

  int sum = 0;
  int checker = 0;
  int results[200];

  for (int i = 0; i < t; i++) {

    sum = 0;
    checker = 0;

    n = 0;
    scanf("%d", &n);

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

    for (int j = 0; j < n; j++) {
      sum += arr[j];
    }

    for (int j = 0; j < n; j++) {

      if ((sum - arr[j]) / (n - 1) == arr[j]) {
        checker = 1;
      }
    }

    if (checker == 1) {
      results[i] = 1;
    } else {
      results[i] = 0;
    }
  }

  for (int m = 0; m < t; m++) {

    if (results[m] == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }

  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 n: i32 = lines.next().unwrap().parse().unwrap();
        let a: Vec<i32> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|s| s.parse().unwrap())
            .collect();
        let sum: i32 = a.iter().sum();
        if sum % n != 0 || !a.contains(&(sum / n)) {
            println!("NO");
        } else {
            println!("YES");
        }
    }
}


Two players play a game.Initially there are $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. $$$n - 1$$$ turns are made. The first player makes the first move, then players alternate turns.The first player wants to minimize the last number that would be left on the board, while the second player wants to maximize it.You want to know what number will be left on the board after $$$n - 1$$$ turns if both players make optimal moves.

int solution() {

  int cases;
  scanf("%d", &cases);
  int arr[cases];
  for (int i = 0; i < cases; i++) {
    scanf("%d", &arr[i]);
  }
  for (int j = 0; j < cases; j++) {
    for (int k = 1; k < cases - j; k++) {
      if (arr[k] > arr[k - 1]) {
        int temp = arr[k];
        arr[k] = arr[k - 1];
        arr[k - 1] = temp;
      }
    }
  }
  if (cases % 2 == 0) {
    printf("%d\n", arr[cases / 2]);
  } else {
    printf("%d\n", arr[(cases - 1) / 2]);
  }

  return 0;
}

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

    let amount = input
        .trim()
        .parse::<usize>()
        .expect("amount: parse to usize failed");
    input.clear();

    std::io::stdin()
        .read_line(&mut input)
        .expect("input : read line failed");

    let mut vec = input
        .split_whitespace()
        .map(|item| item.parse::<i32>().expect("item: parse i32 failed"))
        .collect::<Vec<_>>();

    vec.sort();
    let index = if amount % 2 == 0 {
        amount / 2 - 1
    } else {
        amount / 2
    };
    let outcome = vec[index];

    println!("{}", &outcome);
}


Score: <var>400</var> points

Problem Statement

AtCoder Inc. has decided to lock the door of its office with a <var>3</var>-digit PIN code.

The company has an <var>N</var>-digit lucky number, <var>S</var>. Takahashi, the president, will erase <var>N-3</var> digits from <var>S</var> and concatenate the remaining <var>3</var> digits without changing the order to set the PIN code.

How many different PIN codes can he set this way?

Both the lucky number and the PIN code may begin with a <var>0</var>.

Constraints

<var>4 \leq N \leq 30000</var>

<var>S</var> is a string of length <var>N</var> consisting of digits.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of different PIN codes Takahashi can set.

Sample Input 1

4
0224

Sample Output 1

3

Takahashi has the following options:

Erase the first digit of <var>S</var> and set 224.

Erase the second digit of <var>S</var> and set 024.

Erase the third digit of <var>S</var> and set 024.

Erase the fourth digit of <var>S</var> and set 022.

Thus, he can set three different PIN codes: 022, 024, and 224.

Sample Input 2

6
123123

Sample Output 2

17

Sample Input 3

19
3141592653589793238

Sample Output 3

329

int solution() {
  int n;
  scanf("%d", &n);
  char s[n + 1];
  scanf("%s", s);
  int ans = 0;
  for (int i = 0; i < 1000; i++) {
    int first = i / 100;
    int sec = (i - i / 100 * 100) / 10;
    int ff = 0;
    int fs = 0;
    int tert = i % 10;
    int ft = 0;
    int mark = 0;
    while (ft == 0 && mark < n) {
      if (ff == 0 && s[mark] - '0' == first) {
        ff = 1;
      } else if (ff == 1 && fs == 0 && s[mark] - '0' == sec) {
        fs = 1;
      } else if (ff == 1 && fs == 1 && ft == 0 && s[mark] - '0' == tert) {
        ft = 1;
      }
      mark++;
    }
    if (ft == 1) {
      ans++;
    }
  }
  printf("%d", ans);

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let _n = it.next().unwrap().parse::<usize>().unwrap();
    let s = it.next().unwrap().as_bytes();
    let mut res = 0;
    for i in 0..1000 {
        let mut m: u32 = i;
        let mut cnt = 0;
        for &c in s {
            if c == b'0' + (m % 10) as u8 {
                cnt += 1;
                m /= 10;
            }
        }
        if cnt >= 3 {
            res += 1;
        }
    }
    println!("{}", res);
}


The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square.

int solution() {
  int n;
  int t;
  double x;

  scanf("%d", &t);

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

    n = n * 2;
    x = 360 / (1.0 * n);
    x = (180 - x);
    x = x / 2;

    x = (x * acos(-1)) / 180;
    double y = tan(x);

    printf("%.9f\n", y);
  }
  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 x: f64 = lines.next().unwrap().unwrap().parse().unwrap();
        let ans = (std::f64::consts::FRAC_PI_2 * (1.0 - 1.0 / x)).tan();
        println!("{}", ans);
    }
}


Score: <var>300</var> points

Problem Statement

We have <var>N</var> voting papers. The <var>i</var>-th vote <var>(1 \leq i \leq N)</var> has the string <var>S_i</var> written on it.

Print all strings that are written on the most number of votes, in lexicographical order.

Constraints

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

<var>S_i</var> <var>(1 \leq i \leq N)</var> are strings consisting of lowercase English letters.

The length of <var>S_i</var> <var>(1 \leq i \leq N)</var> is between <var>1</var> and <var>10</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var>
<var>:</var>
<var>S_N</var>

Output

Print all strings in question in lexicographical order.

Sample Input 1

7
beat
vet
beet
bed
vet
bet
beet

Sample Output 1

beet
vet

beet and vet are written on two sheets each, while beat, bed, and bet are written on one vote each. Thus, we should print the strings beet and vet.

Sample Input 2

8
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo
buffalo

Sample Output 2

buffalo

Sample Input 3

7
bass
bass
kick
kick
bass
kick
kick

Sample Output 3

kick

Sample Input 4

4
ushi
tapu
nichia
kun

Sample Output 4

kun
nichia
tapu
ushi

fn solution() {
    let mut vote_count = String::new();
    io::stdin().read_line(&mut vote_count).unwrap();
    vote_count.pop();
    let vote_count = u32::from_str(&vote_count).unwrap();

    let mut votes = HashMap::new();
    for _ in 0..vote_count {
        let mut vote = String::new();
        io::stdin().read_line(&mut vote).unwrap();
        vote.pop();
        let value = if let Some(cnt) = votes.get(&vote) {
            cnt + 1
        } else {
            1
        };
        votes.insert(vote, value);
    }

    let mut max_value = 0;
    let mut max_votes: Vec<String> = Vec::new();
    for (key, value) in votes.iter() {
        if *value > max_value {
            max_value = *value;
            max_votes.clear();
        }
        if *value == max_value {
            max_votes.push(key.to_string());
        }
    }

    max_votes.sort();
    for vote in max_votes.iter() {
        println!("{}", vote);
    }
}


Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.

int solution(void) {

  long int n;
  long int m;
  scanf("%ld %ld", &n, &m);
  long int a[n];
  long int b[n];
  for (int i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
    if (a[i] == 1) {
      printf("-1");
      return 0;
    }
  }
  for (int i = 0; i < n; i++) {
    scanf("%ld", &b[i]);
    if (b[i] == 1) {
      printf("-1");
      return 0;
    }
  }
  long int an = 0;
  long int bn = 1;
  long int ab[2 * n];
  for (int i = 0; i < 2 * n; i++) {
    if (i % 2 == 0) {
      ab[i] = a[an++];
    } else {
      if (bn == n) {
        ab[i] = b[0];
      } else {
        ab[i] = b[bn++];
      }
    }
  }
  double result = (double)m;
  for (int i = ((2 * n) - 1); i >= 0; i--) {
    double result1 = result / ((double)ab[i] - 1);
    result += result1;
  }
  result -= (double)m;
  printf("%f\n", result);
  return 0;
}

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

    let n = get!(usize);
    let m = get!(f64);
    let mut xs = vec![];
    let mut ys = vec![];
    for _ in 0..n {
        let x = get!();
        if x == 1 {
            println!("-1");
            return;
        }
        xs.push(x as f64);
    }
    for _ in 0..n {
        let y = get!();
        if y == 1 {
            println!("-1");
            return;
        }
        ys.push(y as f64);
    }

    let mut ans = m / (ys[0] - 1.0);

    for i in 0..n {
        let j = n - i - 1;
        ans += (m + ans) / (xs[j] - 1.0);
        if j == 0 {
            break;
        }
        ans += (m + ans) / (ys[j] - 1.0);
    }

    println!("{:.*}", 10, ans);
}


A $$$\mathbf{0}$$$-indexed array $$$a$$$ of size $$$n$$$ is called good if for all valid indices $$$i$$$ ($$$0 \le i \le n-1$$$), $$$a_i + i$$$ is a perfect square$$$^\dagger$$$.Given an integer $$$n$$$. Find a permutation$$$^\ddagger$$$ $$$p$$$ of $$$[0,1,2,\ldots,n-1]$$$ that is good or determine that no such permutation exists.$$$^\dagger$$$ An integer $$$x$$$ is said to be a perfect square if there exists an integer $$$y$$$ such that $$$x = y^2$$$.$$$^\ddagger$$$ An array $$$b$$$ is a permutation of an array $$$a$$$ if $$$b$$$ consists of the elements of $$$a$$$ in arbitrary order. For example, $$$[4,2,3,4]$$$ is a permutation of $$$[3,2,4,4]$$$ while $$$[1,2,2]$$$ is not a permutation of $$$[1,2,3]$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int k = 0;
    int a[n];
    while (k * k <= 2 * (n - 1)) {
      a[k] = k * k;
      k++;
    }
    int h[n];
    int f[n];
    for (int i = 0; i < n; i++) {
      f[i] = 0;
    }
    int ans = 0;
    for (int i = n - 1; i >= 0; i--) {
      ans = a[k - 1] - i;
      if (ans > n - 1) {
        i++;
        k--;
      } else {
        if (f[ans] == 0) {
          h[i] = ans;
          f[ans] = 1;
        } else {
          i++;
          k--;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      printf("%d ", h[i]);
    }
    printf("\n");
  }
  return 0;
}

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

    for _i in 0..t {
        let mut n = String::new();
        io::stdin().read_line(&mut n).unwrap();
        let n: usize = n.trim().parse().unwrap();

        let mut _n = n;
        let mut a: [usize; 100005] = [0; 100005];
        let mut z: usize = 0;

        while _n != 0 {
            if _n < 2 {
                z = 0;
            } else {
                z = ((_n - 2) as f64).sqrt() as usize + 1;
                z = z * z;
            }
            for _j in (z - (_n - 1)).._n {
                a[_j] = z - _j;
            }
            _n = z - (_n - 1);
        }
        for _j in 0..n {
            print!("{} ", a[_j]);
        }
        println!();
    }
}


Score : <var>700</var> points

Problem Statement

We have <var>N</var> cards numbered <var>1, 2, ..., N</var>.
Card <var>i</var> (<var>1 \leq i \leq N</var>) has an integer <var>A_i</var> written in red ink on one side and an integer <var>B_i</var> written in blue ink on the other side.
Initially, these cards are arranged from left to right in the order from Card <var>1</var> to Card <var>N</var>, with the red numbers facing up.

Determine whether it is possible to have a non-decreasing sequence facing up from left to right (that is, for each <var>i</var> (<var>1 \leq i \leq N - 1</var>), the integer facing up on the <var>(i+1)</var>-th card from the left is not less than the integer facing up on the <var>i</var>-th card from the left) by repeating the operation below. If the answer is yes, find the minimum number of operations required to achieve it.

Choose an integer <var>i</var> (<var>1 \leq i \leq N - 1</var>).
Swap the <var>i</var>-th and <var>(i+1)</var>-th cards from the left, then flip these two cards.

Constraints

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

<var>1 \leq A_i, B_i \leq 50</var> (<var>1 \leq i \leq N</var>)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>
<var>B_1</var> <var>B_2</var> <var>...</var> <var>B_N</var>

Output

If it is impossible to have a non-decreasing sequence, print -1.
If it is possible, print the minimum number of operations required to achieve it.

Sample Input 1

3
3 4 3
3 2 3

Sample Output 1

1

By doing the operation once with <var>i = 1</var>, we have a sequence <var>[2, 3, 3]</var> facing up, which is non-decreasing.

Sample Input 2

2
2 1
1 2

Sample Output 2

-1

After any number of operations, we have the sequence <var>[2, 1]</var> facing up, which is not non-decreasing.

Sample Input 3

4
1 2 3 4
5 6 7 8

Sample Output 3

0

No operation may be required.

Sample Input 4

5
28 15 22 43 31
20 22 43 33 32

Sample Output 4

-1

Sample Input 5

5
4 46 6 38 43
33 15 18 27 37

Sample Output 5

3

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

    const INF: usize = 1_000_000_000;
    let res = (0..(1 << N))
        .map(|p| {
            let mut X = vec![];
            for i in 0..N {
                X.push((i, 1));
            }
            let mut Y = vec![];
            for i in 0..N {
                if (p >> i) & 1 == 1 {
                    Y.push(A[i]);
                } else {
                    Y.push(B[i]);
                }
            }
            let mut cost = 0;

            for i in 0..N {
                let l = (i..N)
                    .find(|&l| ((l - i) + X[l].1) % 2 == (p >> X[l].0) & 1)
                    .unwrap_or(INF);
                if l == INF {
                    cost = INF;
                    break;
                }
                let mut k = l;
                for j in l..N {
                    if Y[j] < Y[k] && ((j - i) + X[j].1) % 2 == (p >> X[j].0) & 1 {
                        k = j;
                    }
                }

                for r in (i..k).rev() {
                    let tmp = X[r + 1];
                    X[r + 1] = (X[r].0, 1 - X[r].1);
                    X[r] = (tmp.0, 1 - tmp.1);
                    Y.swap(r + 1, r);
                    cost += 1;
                }
            }
            if (1..N).any(|i| Y[i - 1] > Y[i]) {
                cost = INF;
            }

            cost
        })
        .min()
        .unwrap();
    let ans = if res >= INF { -1 } else { res as i64 };

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


Score : <var>200</var> points

Problem Statement

You are given positive integers <var>A</var> and <var>B</var>.

Find the <var>K</var>-th largest positive integer that divides both <var>A</var> and <var>B</var>.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

<var>1 \leq A, B \leq 100</var>

The <var>K</var>-th largest positive integer that divides both <var>A</var> and <var>B</var> exists.

<var>K \geq 1</var>

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var> <var>K</var>

Output

Print the <var>K</var>-th largest positive integer that divides both <var>A</var> and <var>B</var>.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both <var>8</var> and <var>12</var>: <var>1, 2</var> and <var>4</var>.
Among them, the second largest is <var>2</var>.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1

int solution() {
  int a = 0;
  int b = 0;
  int k = 0;
  int count = 0;
  scanf("%d %d %d", &a, &b, &k);
  for (int i = 100; i > 0; i--) {
    if (a % i == 0 && b % i == 0) {
      count++;
      if (count == k) {
        printf("%d\n", i);
        return 0;
      }
    }
  }
  printf("ans not found\n");
  return 0;
}

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

    let mut iter = buf.split_whitespace();

    let a: usize = iter.next().unwrap().parse().unwrap();
    let b: usize = iter.next().unwrap().parse().unwrap();
    let k: usize = iter.next().unwrap().parse().unwrap();

    let max = min(a, b);
    let mut count = 0;

    for i in (1..max + 1).rev() {
        if a.is_multiple_of(i) && b.is_multiple_of(i) {
            count += 1;
            if count == k {
                println!("{}", i);
                break;
            }
        }
    }
}


You are given a string $$$s$$$ consisting of $$$n$$$ characters. Each character of $$$s$$$ is either 0 or 1.A substring of $$$s$$$ is a contiguous subsequence of its characters.You have to choose two substrings of $$$s$$$ (possibly intersecting, possibly the same, possibly non-intersecting — just any two substrings). After choosing them, you calculate the value of the chosen pair of substrings as follows:  let $$$s_1$$$ be the first substring, $$$s_2$$$ be the second chosen substring, and $$$f(s_i)$$$ be the integer such that $$$s_i$$$ is its binary representation (for example, if $$$s_i$$$ is 11010, $$$f(s_i) = 26$$$);  the value is the bitwise OR of $$$f(s_1)$$$ and $$$f(s_2)$$$. Calculate the maximum possible value you can get, and print it in binary representation without leading zeroes.

int solution(void) {
  int n;
  scanf("%d", &n);
  char num_origin[n + 1];
  const char *num = num_origin;
  scanf("%s", num_origin);

  for (; *num == '0'; num++, n--) {
    ;
  }
  int zero_pos[n];
  int zero_n = 0;
  int first = 0;
  for (; first < n && num[first] == '1'; first++) {
    ;
  }
  if (n == 0) {
    puts("0");
  } else if (first == n) {
    puts(num);
  } else {
    for (int i = 0; i < n; i++) {
      if (num[i] == '0') {
        zero_pos[zero_n++] = i;
      }
    }
    int candidate[first];
    int trash[first];
    int candidate_n = first;
    int trash_n = 0;
    for (int i = 0; i < first; i++) {
      candidate[i] = i + 1;
    }
    int ans;
    for (int i = 0; i < zero_n; i++) {
      trash_n = 0;
      for (int j = 0; j < candidate_n; j++) {
        if (num[zero_pos[i] - candidate[j]] != '1') {
          trash[trash_n++] = candidate[j];
          candidate[j--] = candidate[--candidate_n];
        }
      }
      if (!candidate_n) {
        memcpy(candidate, trash, trash_n);
        candidate_n = trash_n;
      } else if (candidate_n == 1) {
        ans = candidate[0];
        goto finish;
      }
    }
    ans = candidate[0];
  finish:;
    for (int i = 0; i < n; i++) {
      putchar(num[i] == '0' ? num[i - ans] : '1');
    }
    putchar('\n');
  }
  return 0;
}

fn solution() {
    input! {
        n: usize,
        s: bytes,
    }
    let one = match s.iter().position(|&c| c == b'1') {
        Some(i) => i,
        None => {
            println!("0");
            return;
        }
    };
    let mut ans = s.clone();
    if let Some(zero) = s[one..].iter().position(|&c| c == b'0') {
        for i in 1..=zero {
            let mut cur = s.clone();
            for j in 0..n - i {
                cur[i + j] |= s[j];
            }
            ans = ans.max(cur);
        }
    }
    println!("{}", std::str::from_utf8(&ans[one..]).unwrap());
}


Ivan is playing a strange game.He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:  Initially Ivan's score is 0;  In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that ai, j = 1). If there are no 1's in the column, this column is skipped;  Ivan will look at the next min(k, n - i + 1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.

int solution() {
  int n;
  int m;
  int k;
  scanf("%d%d%d", &n, &m, &k);
  int numbers[n][m];
  int ct1;
  int ct2;
  int ct3;
  for (ct1 = 0; ct1 < n; ct1++) {
    for (ct2 = 0; ct2 < m; ct2++) {
      scanf("%d", &numbers[ct1][ct2]);
    }
  }

  int max = 0;
  int counter = 0;
  int counter2 = 0;
  int test = 0;
  int result1 = 0;
  int result2 = 0;

  for (ct1 = 0; ct1 < m; ct1++) {
    max = counter = 0;
    for (ct2 = 0; ct2 < n; ct2++) {
      if (numbers[ct2][ct1] == 1) {
        counter++;
        test = 0;
        for (ct3 = 0; ct3 + ct2 < n && ct3 < k; ct3++) {
          test += numbers[ct3 + ct2][ct1];
        }
        if (test > max) {
          max = test;
          counter2 = counter - 1;
        }
      }
    }
    result1 += max;
    result2 += counter2;
  }
  printf("%d %d", result1, result2);
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let nmk: Vec<usize> = line
        .trim()
        .split(" ")
        .map(|x| x.parse::<usize>().unwrap())
        .collect();
    let (n, m, k): (usize, usize, usize) = (nmk[0], nmk[1], nmk[2]);

    let mut matrix = vec![vec![0_i32; 0]; n];
    for i in 0..n {
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        matrix[i] = line
            .trim()
            .split(" ")
            .map(|x| x.parse::<i32>().unwrap())
            .collect();
    }

    let mut best_score = 0;
    let mut need_to_delete = 0;
    for j in 0..m {
        let mut best_column_deleted = 0;
        let mut top = 0;
        let mut bottom = k;
        let mut current_score = 0;
        let mut current_deleted = 0;
        for i in top..bottom {
            if matrix[i][j] == 1 {
                current_score += 1;
            }
        }
        let mut best_column_score = current_score;

        while top < n {
            if matrix[top][j] == 1 {
                current_score -= 1;
                current_deleted += 1;
            }

            if bottom < n && matrix[bottom][j] == 1 {
                current_score += 1;
            }
            top += 1;
            bottom += 1;

            if current_score > best_column_score {
                best_column_score = current_score;
                best_column_deleted = current_deleted;
            }
        }

        best_score += best_column_score;
        need_to_delete += best_column_deleted;
    }

    print!("{} {}", best_score, need_to_delete);
}


Handsel

Alice and Brown are brothers in a family and each receives pocket money in celebration of the coming year. They are very close and share the total amount of the money fifty-fifty. The pocket money each receives is a multiple of 1,000 yen.

  Write a program to calculate each one’s share given the amount of money Alice and Brown received.

Input

  The input is given in the following format.

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

A line of data is given that contains two values of money: <var>a</var> (1000 ≤ <var>a</var> ≤ 50000) for Alice and <bar>b</var> (1000 ≤ <var>b</var> ≤ 50000) for Brown.

Output

  Output the amount of money each of Alice and Brown receive in a line.

Sample Input 1

1000 3000

Sample Output 1

2000

Sample Input 2

5000 5000

Sample Output 2

5000

Sample Input 3

1000 2000

Sample Output 3

1500

int solution(void) {
  int a = 0;
  int b = 0;
  int z;
  scanf("%d", &a);
  scanf("%d", &b);
  z = (a + b) / 2;
  printf("%d\n", z);
  return 0;
}

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

    let a: usize = iter.next().unwrap().parse().unwrap();
    let b: usize = iter.next().unwrap().parse().unwrap();

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


There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete — the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\max(A) - \min(B)|$$$ is as small as possible, where $$$\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is:   first team: $$$A = [1, 2, 4]$$$,  second team: $$$B = [3, 6]$$$. In this case, the value $$$|\max(A) - \min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\max(A) - \min(B)|$$$.

int solution() {
  int number_of_loops;
  scanf("%d", &number_of_loops);
  int sol[number_of_loops];
  for (int i = 0; i < number_of_loops; i++) {
    int number_of_athletics;
    scanf("%d", &number_of_athletics);
    int athlete_power[number_of_athletics];
    for (int j = 0; j < number_of_athletics; j++) {
      scanf("%d", &athlete_power[j]);
    }
    int diffrent = abs(athlete_power[1] - athlete_power[2]);
    int min_diffrent = diffrent;
    for (int m = 0; m < number_of_athletics; m++) {
      for (int n = 0; n < number_of_athletics; n++) {
        if (m == n) {
          continue;
        }
        diffrent = abs(athlete_power[m] - athlete_power[n]);
        if (diffrent < min_diffrent) {
          min_diffrent = diffrent;
        }
      }
      if (min_diffrent == 0) {
        break;
      }
    }
    sol[i] = min_diffrent;
  }

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

  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let 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 mut a: Vec<usize> = (0..n)
            .map(|_| itr.next().unwrap().parse().unwrap())
            .collect();
        a.sort();
        let mut ans = 100000000;
        for i in 0..n - 1 {
            ans = std::cmp::min(ans, a[i + 1] - a[i]);
        }
        writeln!(out, "{}", ans).ok();
    }
    stdout().write_all(&out).unwrap();
}


Score : <var>500</var> points

Problem Statement

There are <var>N</var> squares numbered <var>1</var> to <var>N</var> from left to right.
Each square has a character written on it, and Square <var>i</var> has a letter <var>s_i</var>. Besides, there is initially one golem on each square.

Snuke cast <var>Q</var> spells to move the golems.

The <var>i</var>-th spell consisted of two characters <var>t_i</var> and <var>d_i</var>, where <var>d_i</var> is L or R.
When Snuke cast this spell, for each square with the character <var>t_i</var>, all golems on that square moved to the square adjacent to the left if <var>d_i</var> is L, and moved to the square adjacent to the right if <var>d_i</var> is R.

However, when a golem tried to move left from Square <var>1</var> or move right from Square <var>N</var>, it disappeared.

Find the number of golems remaining after Snuke cast the <var>Q</var> spells.

Constraints

<var>1 \leq N,Q \leq 2 \times 10^{5}</var>

<var>|s| = N</var>

<var>s_i</var> and <var>t_i</var> are uppercase English letters.

<var>d_i</var> is L or R.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>Q</var>
<var>s</var>
<var>t_1</var> <var>d_1</var>
<var>\vdots</var>
<var>t_{Q}</var> <var>d_Q</var>

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square <var>1</var> tries to move left and disappears.

In the second spell, the golem on Square <var>2</var> moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square <var>1</var> moves right.

After the four spells are cast, there is one golem on Square <var>2</var> and one golem on Square <var>3</var>, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square <var>2</var>, two golems on Square <var>4</var> and two golems on Square <var>6</var>, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3

int solution() {
  int n;
  int q;
  int i;
  int j;
  int min;
  int max;
  scanf("%d %d", &n, &q);
  char s[200001];
  scanf("%s", s);
  char t[200001];
  char d[200001];
  for (i = 0; i < q; i++) {
    scanf("\n%c %c", &t[i], &d[i]);
  }
  for (i = q - 1, min = 0, max = n - 1; i >= 0; i--) {
    switch (d[i]) {
    case 'R':
      if (t[i] == s[max]) {
        max--;
      }
      if (min > 0 && t[i] == s[min - 1]) {
        min--;
      }
      break;
    case 'L':
      if (t[i] == s[min]) {
        min++;
      }
      if (max < n - 1 && t[i] == s[max + 1]) {
        max++;
      }
      break;
    }
  }
  printf("%d", max - min + 1);
  return 0;
}

fn solution() {
    input! {
        n: usize,
        q: usize,
        s: chars,
        td: [(String, String); q]
    };
    let mut lcurrent = 0;
    let mut rcurrent = 0;
    for (t, d) in td.iter().rev() {
        let t = t.chars().next().unwrap();
        let d = d.chars().next().unwrap();
        if d == 'L' {
            if lcurrent < n && s[lcurrent] == t {
                lcurrent += 1;
            }
            if rcurrent > 0 && s[n - rcurrent] == t {
                rcurrent -= 1;
            }
        } else {
            if rcurrent < n && s[n - rcurrent - 1] == t {
                rcurrent += 1;
            }
            if lcurrent > 0 && s[lcurrent - 1] == t {
                lcurrent -= 1;
            }
        }
    }

    println!("{}", n - lcurrent - rcurrent);
}


The great hero guards the country where Homer lives. The hero has attack power $$$A$$$ and initial health value $$$B$$$. There are $$$n$$$ monsters in front of the hero. The $$$i$$$-th monster has attack power $$$a_i$$$ and initial health value $$$b_i$$$. The hero or a monster is said to be living, if his or its health value is positive (greater than or equal to $$$1$$$); and he or it is said to be dead, if his or its health value is non-positive (less than or equal to $$$0$$$).In order to protect people in the country, the hero will fight with monsters until either the hero is dead or all the monsters are dead.  In each fight, the hero can select an arbitrary living monster and fight with it. Suppose the $$$i$$$-th monster is selected, and the health values of the hero and the $$$i$$$-th monster are $$$x$$$ and $$$y$$$ before the fight, respectively. After the fight, the health values of the hero and the $$$i$$$-th monster become $$$x-a_i$$$ and $$$y-A$$$, respectively. Note that the hero can fight the same monster more than once.For the safety of the people in the country, please tell them whether the great hero can kill all the monsters (even if the great hero himself is dead after killing the last monster).

int solution() {
  int www;
  scanf("%d", &www);
  while (www--) {
    int A;
    int B;
    int n;
    scanf("%d%d%d", &A, &B, &n);
    int a[n];
    int b[n];
    int x = B;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    for (int i = 0; i < n; i++) {
      scanf("%d", &b[i]);
      x -= (ceil(b[i] / (1.0 * (A)))) * a[i];
    }
    int flag = 0;
    for (int i = 0; i < n; i++) {
      if (x + a[i] > 0) {
        flag = 1;
        break;
      }
    }
    if (flag == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

fn solution() {
    use std::io::{self, Write};

    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 tc: usize = sc.next();
    for _ in 0..tc {
        let (A, B, n): (i64, i64, usize) = (sc.next(), sc.next(), sc.next());
        let a: Vec<i64> = (0..n).map(|_| sc.next()).collect();
        let b: Vec<i64> = (0..n).map(|_| sc.next()).collect();
        let mut damage = Vec::with_capacity(n);
        for i in 0..n {
            damage.push(((b[i] + A - 1) / A) * a[i]);
        }
        let total_damage: i64 = damage.iter().sum();
        let possible = a.iter().fold(false, |x, y| x | (total_damage - *y < B));
        writeln!(out, "{}", if possible { "YES" } else { "NO" }).unwrap();
    }
}


You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.

fn solution() {
    let inputstatus = 1;

    let mut buf = String::new();
    let filename = "inputrust.txt";

    if inputstatus == 0 {
        let mut f = File::open(filename).expect("file not found");
        f.read_to_string(&mut buf)
            .expect("something went wrong reading the file");
    } else {
        std::io::stdin().read_to_string(&mut buf).unwrap();
    }

    let mut iter = buf.split_whitespace();

    let n: usize = iter.next().unwrap().parse().unwrap();
    for _ in 0..n {
        let s: &str = iter.next().unwrap();
        const M: usize = 1000000;
        let mut ans: usize = M;
        let mut l: usize;
        let mut r: usize;
        let mut v: [usize; 3] = [M; 3];
        let mut p: usize;

        for (i, c) in s.bytes().enumerate() {
            p = c as usize - '1' as usize;
            v[p] = i;
            l = cmp::min(v[0], cmp::min(v[1], v[2]));
            r = cmp::max(v[0], cmp::max(v[1], v[2]));
            if r != M {
                ans = cmp::min(ans, r - l + 1);
            }
        }
        ans = if ans == M { 0 } else { ans };
        println!("{}", ans);
    }
}


This is the hard version of the problem. The difference between the versions is the constraint on $$$n$$$ and the required number of operations. You can make hacks only if all versions of the problem are solved.There are two binary strings $$$a$$$ and $$$b$$$ of length $$$n$$$ (a binary string is a string consisting of symbols $$$0$$$ and $$$1$$$). In an operation, you select a prefix of $$$a$$$, and simultaneously invert the bits in the prefix ($$$0$$$ changes to $$$1$$$ and $$$1$$$ changes to $$$0$$$) and reverse the order of the bits in the prefix.For example, if $$$a=001011$$$ and you select the prefix of length $$$3$$$, it becomes $$$011011$$$. Then if you select the entire string, it becomes $$$001001$$$.Your task is to transform the string $$$a$$$ into $$$b$$$ in at most $$$2n$$$ operations. It can be proved that it is always possible.

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    let mut current = Vec::new();
    let mut needed = Vec::new();
    let mut operations = Vec::new();
    input.read_line(&mut line).unwrap();
    let mut count: i16 = line.trim().parse().unwrap();
    while count > 0 {
        input.read_line(&mut line).unwrap();
        line.clear();
        input.read_line(&mut line).unwrap();
        for item in line.trim().chars() {
            current.push(item != '0');
        }
        line.clear();
        input.read_line(&mut line).unwrap();
        for item in line.trim().chars() {
            needed.push(item != '0');
        }
        let mut inversed = false;
        let mut head = 0;
        let mut current_tail = current.len();
        let mut needed_tail = current_tail;
        while needed_tail > 0 {
            if inversed {
                current_tail += 1;
            } else {
                current_tail -= 1;
            };
            needed_tail -= 1;
            let needed_item = needed[needed_tail] ^ inversed;
            if current[current_tail] == needed_item {
                continue;
            }
            if current[head] == needed_item {
                operations.push(1);
            }
            operations.push(needed_tail + 1);
            inversed = !inversed;
            std::mem::swap(&mut head, &mut current_tail);
        }
        current.clear();
        needed.clear();
        print!("{}", operations.len());
        for operation in &operations {
            print!(" {}", operation);
        }
        println!();
        operations.clear();
        count -= 1;
    }
}


After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.The three friends are very smart so they passed all the challenges very quickly and finally reached the destination. But the treasure can only belong to one cat so they started to think of something which can determine who is worthy of the treasure. Instantly, Kuro came up with some ribbons.A random colorful ribbon is given to each of the cats. Each color of the ribbon can be represented as an uppercase or lowercase Latin letter. Let's call a consecutive subsequence of colors that appears in the ribbon a subribbon. The beauty of a ribbon is defined as the maximum number of times one of its subribbon appears in the ribbon. The more the subribbon appears, the more beautiful is the ribbon. For example, the ribbon aaaaaaa has the beauty of $$$7$$$ because its subribbon a appears $$$7$$$ times, and the ribbon abcdabc has the beauty of $$$2$$$ because its subribbon abc appears twice.The rules are simple. The game will have $$$n$$$ turns. Every turn, each of the cats must change strictly one color (at one position) in his/her ribbon to an arbitrary color which is different from the unchanged one. For example, a ribbon aaab can be changed into acab in one turn. The one having the most beautiful ribbon after $$$n$$$ turns wins the treasure.Could you find out who is going to be the winner if they all play optimally?

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

    let n = get!(usize);
    let kuro = get().as_bytes();
    let shiro = get().as_bytes();
    let katie = get().as_bytes();

    if n >= kuro.len() {
        println!("Draw");
        return;
    }

    let mut kuro_c = vec![0; 1256];
    let mut shiro_c = vec![0; 1256];
    let mut katie_c = vec![0; 1256];

    for i in 0..kuro.len() {
        kuro_c[kuro[i] as usize] += 1;
        shiro_c[shiro[i] as usize] += 1;
        katie_c[katie[i] as usize] += 1;
    }

    use std::cmp::{max, min};
    let mut kuro_mx = 0;
    let mut shiro_mx = 0;
    let mut katie_mx = 0;
    for i in 0..kuro_c.len() {
        kuro_mx = max(kuro_mx, kuro_c[i]);
        shiro_mx = max(shiro_mx, shiro_c[i]);
        katie_mx = max(katie_mx, katie_c[i]);
    }
    let sz = kuro.len();
    if n == 1 {
        kuro_mx = if kuro_mx == sz {
            kuro_mx - 1
        } else {
            kuro_mx + 1
        };
        shiro_mx = if shiro_mx == sz {
            shiro_mx - 1
        } else {
            shiro_mx + 1
        };
        katie_mx = if katie_mx == sz {
            katie_mx - 1
        } else {
            katie_mx + 1
        };
    } else {
        kuro_mx = min(kuro_mx + n, sz);
        shiro_mx = min(shiro_mx + n, sz);
        katie_mx = min(katie_mx + n, sz);
    }
    let mut xs = [(kuro_mx, 0), (shiro_mx, 1), (katie_mx, 2)];
    xs.sort();

    if xs[1].0 == xs[2].0 {
        println!("Draw");
        return;
    }

    if xs[2].1 == 0 {
        println!("Kuro");
    } else if xs[2].1 == 1 {
        println!("Shiro");
    } else {
        println!("Katie");
    }
}


Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password k times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).

int solution() {
  int n;
  int k;
  char s[102];
  scanf("%d%d\n", &n, &k);
  int a[102];
  for (int i = 0; i < 102; i++) {
    a[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    scanf("%s", s);
    a[strlen(s)]++;
  }
  scanf("%s", s);
  int m = strlen(s);
  int sum = 0;
  for (int i = 0; i < m; i++) {
    sum = sum + a[i];
  }
  int mn = sum + 1;
  int mx = sum + a[m];
  printf("%d %d", mn + (((mn - 1) / k) * 5), mx + (((mx - 1) / k) * 5));
  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let handle = stdin.lock();
    let mut i = 0;
    let (mut n, mut k) = (0, 0);

    let mut passwords: Vec<i32> = Vec::with_capacity(110);
    for _ in 0..110 {
        passwords.push(0);
    }

    let mut answer = 0;

    for line in handle.lines() {
        if i == 0 {
            let split = line.unwrap();
            let mut iter = split.split_whitespace();
            n = iter.next().unwrap().parse().unwrap();
            k = iter.next().unwrap().parse().unwrap();
        } else if i == (n + 1) {
            answer = line.unwrap().len();
            break;
        } else {
            passwords[line.unwrap().len()] += 1;
        }
        i += 1;
    }

    let (mut lower, mut higher) = (0, 0);

    for i in 1..answer {
        lower += passwords[i];
        higher += passwords[i];
    }
    lower += 1;
    higher += passwords[answer];

    lower += 5 * ((lower - 1) / k);
    higher += 5 * ((higher - 1) / k);

    println!("{} {}", lower, higher);
}


Score : <var>200</var> points

Problem Statement

Takahashi has many red balls and blue balls. Now, he will place them in a row.

Initially, there is no ball placed.

Takahashi, who is very patient, will do the following operation <var>10^{100}</var> times:

Place <var>A</var> blue balls at the end of the row of balls already placed. Then, place <var>B</var> red balls at the end of the row.

How many blue balls will be there among the first <var>N</var> balls in the row of balls made this way?

Constraints

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

<var>A, B \geq 0</var>

<var>0 < A + B \leq 10^{18}</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of blue balls that will be there among the first <var>N</var> balls in the row of balls.

Sample Input 1

8 3 4

Sample Output 1

4

Let b denote a blue ball, and r denote a red ball. The first eight balls in the row will be bbbrrrrb, among which there are four blue balls.

Sample Input 2

8 0 4

Sample Output 2

0

He placed only red balls from the beginning.

Sample Input 3

6 2 4

Sample Output 3

2

Among bbrrrr, there are two blue balls.

int solution() {
  long long n;
  long long a;
  long long b;
  scanf("%lld%lld%lld", &n, &a, &b);
  if ((a + b) == 0) {
    printf("0\n");
  } else {
    if (n % (a + b) > a) {
      printf("%lld", a + (a * (n / (a + b))));
    } else {
      printf("%lld\n", (a * (n / (a + b))) + (n % (a + b)));
    }
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    if io::stdin().read_line(&mut input).is_ok() {
        let v: Vec<i64> = input
            .trim()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let count = v[0];
        let unit = v[1] + v[2];
        let blue = v[1];
        let div = count / unit;
        let res = count % unit;
        println!("{}", div * blue + min(res, blue));
    }
}


On an $$$8 \times 8$$$ grid, some horizontal rows have been painted red, and some vertical columns have been painted blue, in some order. The stripes are drawn sequentially, one after the other. When the stripe is drawn, it repaints all the cells through which it passes.Determine which color was used last.  The red stripe was painted after the blue one, so the answer is R.

int solution() {
  int i = 0;

  char str[8][8];
  scanf("%d", &i);
  for (int j = 0; j < i; j++) {
    int b = 0;

    for (int k = 0; k < 8; ++k) {
      scanf("%s", str[k]);
    }

    for (int c = 0; c < 8; ++c) {
      int cnt = 0;

      for (int b = 0; b < 8; ++b) {
        if (str[c][b] == 'R') {
          ++cnt;
        }
      }
      if (cnt == 8) {
        b = 1;
        break;
      }
    }
    if (b == 1) {
      printf("R\n");
    } else {
      printf("B\n");
    }
  }
  return 0;
}

fn solution() {
    (0..{
        let mut buf = String::new();
        stdin().read_line(&mut buf).unwrap();
        buf.trim().parse::<u16>().unwrap()
    })
        .for_each(|_| {
            let mut lines = [['.'; 8]; 8];
            let mut buf = String::new();
            lines[0] = loop {
                if {
                    buf.clear();
                    stdin().read_line(&mut buf).unwrap();
                    !buf.trim().is_empty()
                } {
                    break {
                        let mut chars = ['.'; 8];
                        buf.trim()
                            .split("")
                            .filter_map(|x| {
                                if !x.is_empty() {
                                    Some(x.chars().next().unwrap())
                                } else {
                                    None
                                }
                            })
                            .enumerate()
                            .for_each(|(i, x)| {
                                chars[i] = x;
                            });
                        chars
                    };
                }
            };
            (1..8).for_each(|i| {
                lines[i] = {
                    buf.clear();
                    stdin().read_line(&mut buf).unwrap();
                    let mut chars = ['.'; 8];
                    buf.trim()
                        .split("")
                        .filter_map(|x| {
                            if !x.trim().is_empty() {
                                Some(x.chars().next().unwrap())
                            } else {
                                None
                            }
                        })
                        .enumerate()
                        .for_each(|(i, x)| {
                            chars[i] = x;
                        });
                    chars
                };
            });

            println!(
                "{}",
                if {
                    let mut is_r = true;
                    for i in 0..8 {
                        let mut flag = true;
                        for j in 1..8 {
                            if lines[i][j] != 'R' || lines[i][j - 1] != 'R' {
                                is_r = false;
                                flag = false;
                                break;
                            } else {
                                is_r = true;
                                flag = true;
                            }
                        }
                        if flag {
                            break;
                        }
                    }
                    is_r
                } {
                    "R"
                } else {
                    "B"
                }
            );
        });
}


Score : <var>100</var> points

Problem Statement

Based on some criterion, Snuke divided the integers from <var>1</var> through <var>12</var> into three groups as shown in the figure below.
Given two integers <var>x</var> and <var>y</var> (<var>1 ≤ x < y ≤ 12</var>), determine whether they belong to the same group.

Constraints

<var>x</var> and <var>y</var> are integers.

<var>1 ≤ x < y ≤ 12</var>

Input

Input is given from Standard Input in the following format:

<var>x</var> <var>y</var>

Output

If <var>x</var> and <var>y</var> belong to the same group, print Yes; otherwise, print No.

Sample Input 1

1 3

Sample Output 1

Yes

Sample Input 2

2 4

Sample Output 2

No

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

    let mut it = buf.split_whitespace().map(|n| i64::from_str(n).unwrap());
    let (x, y) = (it.next().unwrap(), it.next().unwrap());

    let mut a: HashSet<_> = [1, 3, 5, 7, 8, 10, 12].iter().cloned().collect();
    let mut b: HashSet<_> = [4, 6, 9, 11].iter().cloned().collect();

    a.insert(x);
    a.insert(y);
    if a.len() == 7 {
        println!("Yes");
        return;
    }
    b.insert(x);
    b.insert(y);
    if b.len() == 4 {
        println!("Yes");
        return;
    }

    if x == 2 && y == 2 {
        println!("Yes");
        return;
    }
    println!("No");
}


Let's consider all integers in the range from $$$1$$$ to $$$n$$$ (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $$$\mathrm{gcd}(a, b)$$$, where $$$1 \leq a < b \leq n$$$.The greatest common divisor, $$$\mathrm{gcd}(a, b)$$$, of two positive integers $$$a$$$ and $$$b$$$ is the biggest integer that is a divisor of both $$$a$$$ and $$$b$$$.

int solution() {
  int n = 0;
  scanf("%d", &n);
  int s[n];
  int i;
  for (i = 0; i < n; i++) {
    scanf("%d", &s[i]);
  }
  for (i = 0; i < n; i++) {
    int a = s[i] / 2;
    printf("%d\n", a);
  }
  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();
        println!("{}", n / 2);
    }
}


Score : <var>100</var> points

Problem Statement

AtCoDeer the deer found two positive integers, <var>a</var> and <var>b</var>.
Determine whether the product of <var>a</var> and <var>b</var> is even or odd.

Constraints

<var>1</var> <var>≤</var> <var>a,b</var> <var>≤</var> <var>10000</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

If the product is odd, print Odd; if it is even, print Even.

Sample Input 1

3 4

Sample Output 1

Even

As <var>3 × 4 = 12</var> is even, print Even.

Sample Input 2

1 21

Sample Output 2

Odd

As <var>1 × 21 = 21</var> is odd, print Odd.

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

  if (a * b % 2 == 0) {
    printf("Even");
  } else {
    printf("Odd");
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let cond = buf
        .trim()
        .split(' ')
        .map(|x| x.parse::<i32>().unwrap())
        .product::<i32>()
        % 2
        == 0;
    if cond {
        println!("Even");
    } else {
        println!("Odd");
    }
}


Score : <var>100</var> points

Problem Statement

We conducted a survey on newspaper subscriptions.
More specifically, we asked each of the <var>N</var> respondents the following two questions:

Question <var>1</var>: Are you subscribing to Newspaper X?

Question <var>2</var>: Are you subscribing to Newspaper Y?

As the result, <var>A</var> respondents answered "yes" to Question <var>1</var>, and <var>B</var> respondents answered "yes" to Question <var>2</var>.

What are the maximum possible number and the minimum possible number of respondents subscribing to both newspapers X and Y?

Write a program to answer this question.

Constraints

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible number and the minimum possible number of respondents subscribing to both newspapers, in this order, with a space in between.

Sample Input 1

10 3 5

Sample Output 1

3 0

In this sample, out of the <var>10</var> respondents, <var>3</var> answered they are subscribing to Newspaper X, and <var>5</var> answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most <var>3</var> and at least <var>0</var>.

Sample Input 2

10 7 5

Sample Output 2

5 2

In this sample, out of the <var>10</var> respondents, <var>7</var> answered they are subscribing to Newspaper X, and <var>5</var> answered they are subscribing to Newspaper Y.

Here, the number of respondents subscribing to both newspapers is at most <var>5</var> and at least <var>2</var>.

Sample Input 3

100 100 100

Sample Output 3

100 100

int solution() {
  int n_person = 0;
  int a_newsp = 0;
  int b_newsp = 0;
  int both = 0;
  int min = 0;

  scanf("%d %d %d", &n_person, &a_newsp, &b_newsp);

  if (a_newsp > b_newsp) {
    both = b_newsp;
  } else {
    both = a_newsp;
  }

  min = (a_newsp + b_newsp) - n_person;
  if (min > 0) {
  } else {
    min = 0;
  }
  printf("%d %d", both, min);
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let a: usize = itr.next().unwrap().parse().unwrap();
    let b: usize = itr.next().unwrap().parse().unwrap();
    println!("{} {}", min(a, b), (a + b).saturating_sub(n));
}


Polycarp has $$$3$$$ positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He can perform the following operation exactly once.  Choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$. Can Polycarp make it so that after performing the operation, the sequence of three numbers $$$a$$$, $$$b$$$, $$$c$$$ (in this order) forms an arithmetic progression? Note that you cannot change the order of $$$a$$$, $$$b$$$ and $$$c$$$.Formally, a sequence $$$x_1, x_2, \dots, x_n$$$ is called an arithmetic progression (AP) if there exists a number $$$d$$$ (called "common difference") such that $$$x_{i+1}=x_i+d$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$. In this problem, $$$n=3$$$.For example, the following sequences are AP: $$$[5, 10, 15]$$$, $$$[3, 2, 1]$$$, $$$[1, 1, 1]$$$, and $$$[13, 10, 7]$$$. The following sequences are not AP: $$$[1, 2, 4]$$$, $$$[0, 1, 0]$$$ and $$$[1, 3, 2]$$$.You need to answer $$$t$$$ independent test cases.

fn solution() {
    let mut handle = std::io::BufWriter::new(std::io::stdout());
    let mut test_no = String::new();
    std::io::stdin().read_line(&mut test_no).unwrap();
    let test_no: u16 = test_no.trim().parse().unwrap();
    for _ in 0..test_no {
        let mut string = String::new();
        std::io::stdin().read_line(&mut string).unwrap();
        let arraystr: Vec<&str> = string.trim().split(' ').collect();
        let array: Vec<u32> = arraystr.iter().map(|x| x.parse().unwrap()).collect();
        let a = array[0];
        let b = array[1];
        let c = array[2];
        if (a + c).is_multiple_of(2 * b)
            || (2 * b - a).is_multiple_of(c) && 2 * b > a
            || (2 * b - c).is_multiple_of(a) && 2 * b > c
        {
            writeln!(handle, "YES").expect("");
        } else {
            writeln!(handle, "NO").expect("");
        }
    }
}


The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?

int solution() {
  int n = 0;
  int k = 0;
  scanf("%i %i", &n, &k);
  int z[2000] = {0};
  int diff = 5 - k;
  int number = 0;
  for (int i = 0; i < n; i++) {
    scanf("%i", &z[i]);
    if (z[i] <= diff) {
      number++;
    }
  }
  number = number / 3;

  printf("%i", number);
}

fn solution() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };
    let k = v[1];
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };
    let n = v.iter().filter(|&i| *i <= 5 - k).count();
    println!("{:?}", n / 3);
}