Score : <var>300</var> points

Problem Statement

There are <var>N</var> people living on a number line.

The <var>i</var>-th person lives at coordinate <var>X_i</var>.

You are going to hold a meeting that all <var>N</var> people have to attend.

The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate <var>P</var>, the <var>i</var>-th person will spend <var>(X_i - P)^2</var> points of stamina to attend the meeting.

Find the minimum total points of stamina the <var>N</var> people have to spend.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>X_1</var> <var>X_2</var> <var>...</var> <var>X_N</var>

Output

Print the minimum total stamina the <var>N</var> people have to spend.

Sample Input 1

2
1 4

Sample Output 1

5

Assume the meeting is held at coordinate <var>2</var>. In this case, the first person will spend <var>(1 - 2)^2</var> points of stamina, and the second person will spend <var>(4 - 2)^2 = 4</var> points of stamina, for a total of <var>5</var> points of stamina. This is the minimum total stamina that the <var>2</var> people have to spend.

Note that you can hold the meeting only at an integer coordinate.

Sample Input 2

7
14 14 2 13 56 2 37

Sample Output 2

2354

int solution() {
  int N;
  int sum = 0;
  int sum_sq = 0;
  int p = 0;
  int ans_a = 0;
  int ans_b = 0;
  scanf("%d", &N);
  int x[N];
  for (int i = 0; i < N; i++) {
    scanf("%d", &x[i]);
    sum += x[i];
    sum_sq += x[i] * x[i];
  }
  p = sum / N;
  ans_a = N * p * p - 2 * sum * p + sum_sq;
  p++;
  ans_b = N * p * p - 2 * sum * p + sum_sq;
  printf("%d\n", (ans_a > ans_b ? ans_b : ans_a));

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin()
        .read_line(&mut buf)
        .expect("Failed to read line");
    let vec_1: Vec<&str> = buf.split_whitespace().collect();
    let n: i32 = vec_1[0].parse().unwrap_or(0);

    let mut buf = String::new();
    io::stdin()
        .read_line(&mut buf)
        .expect("Failed to read line");
    let vec_x: Vec<&str> = buf.split_whitespace().collect();

    let mut sum_x: i32 = 0;
    for i in &vec_x {
        let t: i32 = i.parse().unwrap();
        sum_x += t;
    }
    let mut p: i32 = sum_x / n;

    let mut ans_1: i32 = 0;
    for i in &vec_x {
        let t: i32 = i.parse().unwrap();
        ans_1 += (t - p) * (t - p);
    }

    p += 1;
    let mut ans_2: i32 = 0;
    for i in &vec_x {
        let t: i32 = i.parse().unwrap();
        ans_2 += (t - p) * (t - p);
    }

    println!("{}", min(ans_1, ans_2));
}


Score : <var>500</var> points

Problem Statement

There is a string <var>s</var> of length <var>3</var> or greater.
No two neighboring characters in <var>s</var> are equal.

Takahashi and Aoki will play a game against each other.
The two players alternately performs the following operation, Takahashi going first:

Remove one of the characters in <var>s</var>, excluding both ends. However, a character cannot be removed if removal of the character would result in two neighboring equal characters in <var>s</var>.

The player who becomes unable to perform the operation, loses the game. Determine which player will win when the two play optimally.

Constraints

<var>3 ≤ |s| ≤ 10^5</var>

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

No two neighboring characters in <var>s</var> are equal.

Input

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

<var>s</var>

Output

If Takahashi will win, print First. If Aoki will win, print Second.

Sample Input 1

aba

Sample Output 1

Second

Takahashi, who goes first, cannot perform the operation, since removal of the b, which is the only character not at either ends of <var>s</var>, would result in <var>s</var> becoming aa, with two as neighboring.

Sample Input 2

abc

Sample Output 2

First

When Takahashi removes b from <var>s</var>, it becomes ac.
Then, Aoki cannot perform the operation, since there is no character in <var>s</var>, excluding both ends.

Sample Input 3

abcab

Sample Output 3

First

int solution() {
  char s[100002];
  scanf("%s", s);
  int len = strlen(s);
  if ((s[0] == s[len - 1] || len % 2 != 0) &&
      (s[0] != s[len - 1] || len % 2 == 0)) {
    printf("First\n");
  } else {
    printf("Second\n");
  }
}

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

    stdin.read_line(&mut buf).unwrap();
    let s_vec: Vec<char> = buf.trim().chars().collect();

    let parity = s_vec.len() + if s_vec.first() == s_vec.last() { 1 } else { 0 };

    match parity % 2 {
        1 => println!("First"),
        _ => println!("Second"),
    }
}


Tired of boring office work, Denis decided to open a fast food restaurant.On the first day he made $$$a$$$ portions of dumplings, $$$b$$$ portions of cranberry juice and $$$c$$$ pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|l| l.unwrap());
    let t: u32 = lines.next().unwrap().trim().parse().unwrap();
    for _ in 0..t {
        let line = lines.next().unwrap();
        let mut parts = line.split_whitespace();
        let a: u32 = parts.next().unwrap().parse().unwrap();
        let b: u32 = parts.next().unwrap().parse().unwrap();
        let c: u32 = parts.next().unwrap().parse().unwrap();
        let mut x = [a, b, c];
        x.sort();
        match x[0] {
            0 => {
                if x[2] == 0 {
                    println!("0");
                } else if x[1] == 0 {
                    println!("1");
                } else if x[1] == 1 {
                    println!("2");
                } else {
                    println!("3");
                }
            }
            1 => {
                if x[1] == 1 {
                    println!("3");
                } else {
                    println!("4");
                }
            }
            2 => {
                if x[2] == 2 {
                    println!("4");
                } else {
                    println!("5");
                }
            }
            3 => {
                println!("6");
            }
            _ => {
                println!("7");
            }
        }
    }
}


C: 祈祷 (Pray)

とある双子は、コンテスト前に祈祷をすることで有名である。

4 つの整数 $H, W, X, Y$ があって、$H \times W$ と $x + y$ が両方とも奇数だと縁起が悪いらしい。

入力

4 つの整数 $H, W, X, Y$ が空白区切りで与えられる。

出力

縁起が悪いなら "No"、そうでないなら "Yes" を出力しなさい。ただし、最後の改行を忘れないこと。

制約

$H, W, X, Y$ は $1$ 以上 $100$ 以下の整数

入力例1

3 5 1 4

出力例1

No

$3 \times 5 = 15$, $1 + 4 = 5$ で、両方とも奇数なので、縁起が悪いです。

入力例2

3 5 2 4

出力例2

Yes

$3 \times 5 = 15$ で奇数ですが、$2 + 4 = 6$ で偶数なので、縁起は悪くないです。

int solution() {
  int h;
  int w;
  int x;
  int y;

  scanf("%d%d%d%d", &h, &w, &x, &y);
  if ((h * w & 1) && ((x + y) & 1)) {
    puts("No");
  } else {
    puts("Yes");
  }
  return 0;
}


Score : <var>700</var> points

Problem Statement

Given are positive integers <var>N</var> and <var>K</var>.

Determine if the <var>3N</var> integers <var>K, K+1, ..., K+3N-1</var> can be partitioned into <var>N</var> triples <var>(a_1,b_1,c_1), ..., (a_N,b_N,c_N)</var> so that the condition below is satisfied. Any of the integers <var>K, K+1, ..., K+3N-1</var> must appear in exactly one of those triples.

For every integer <var>i</var> from <var>1</var> to <var>N</var>, <var>a_i + b_i \leq c_i</var> holds.

If the answer is yes, construct one such partition.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>

Output

If it is impossible to partition the integers satisfying the condition, print -1. If it is possible, print <var>N</var> triples in the following format:

<var>a_1</var> <var>b_1</var> <var>c_1</var>
<var>:</var>
<var>a_N</var> <var>b_N</var> <var>c_N</var>

Sample Input 1

1 1

Sample Output 1

1 2 3

Sample Input 2

3 3

Sample Output 2

-1

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

    let mut a = vec![0; N];
    let mut b = vec![0; N];
    let c = (0..N).map(|i| K + 2 * N + i).collect::<Vec<_>>();
    let m = (N - 1) / 2;
    let mut j = m;
    for x in (K..(K + N)).rev() {
        a[j] = x;
        j = (j + 1) % N;
    }
    for i in 0..m {
        b[i] = K + N + 2 * i + 1;
    }
    for i in m..N {
        b[i] = std::cmp::min(K + N + 2 * (i - m), K + 2 * N - 1);
    }
    let ans = if (0..N).all(|i| a[i] + b[i] <= c[i]) {
        (0..N)
            .map(|i| format!("{} {} {}", a[i], b[i], c[i]))
            .collect::<Vec<_>>()
            .join("\n")
    } else {
        "-1".to_string()
    };

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


Score : <var>300</var> points

Problem Statement

There are <var>N</var> monsters, numbered <var>1, 2, ..., N</var>.

Initially, the health of Monster <var>i</var> is <var>A_i</var>.

Below, a monster with at least <var>1</var> health is called alive.

Until there is only one alive monster, the following is repeated:

A random alive monster attacks another random alive monster.

As a result, the health of the monster attacked is reduced by the amount equal to the current health of the monster attacking.

Find the minimum possible final health of the last monster alive.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum possible final health of the last monster alive.

Sample Input 1

4
2 10 8 40

Sample Output 1

2

When only the first monster keeps on attacking, the final health of the last monster will be <var>2</var>, which is minimum.

Sample Input 2

4
5 13 8 1000000000

Sample Output 2

1

Sample Input 3

3
1000000000 1000000000 1000000000

Sample Output 3

1000000000

int solution(void) {

  int N;
  scanf("%d", &N);
  int A[N];
  for (int i = 0; i < N; i++) {
    scanf("%d", &A[i]);
  }
  while (1) {
    int min_iter = 0;
    while (A[min_iter] == 0) {
      min_iter++;
    }
    for (int i = 0; i < N; i++) {
      if (A[i] < A[min_iter] && A[i] != 0) {
        min_iter = i;
      }
    }
    for (int i = 0; i < N; i++) {
      if (i != min_iter) {
        A[i] = A[i] % A[min_iter];
      }
    }
    int count = 0;
    for (int i = 0; i < N; i++) {
      if (A[i] != 0) {
        count++;
      }
    }
    if (count == 1) {
      break;
    }
  }
  for (int i = 0; i < N; i++) {
    if (A[i] != 0) {
      printf("%d\n", A[i]);
    }
  }
  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 _n: usize = iter.next().unwrap().parse().unwrap();
    let ns: Vec<usize> = iter.map(|n| n.parse::<usize>().unwrap()).collect();

    let mut min: usize = *ns.iter().min().unwrap();

    loop {
        let pre_min = min;
        for n in ns.iter() {
            let sub = n % min;
            if sub != 0 && sub < min {
                min = sub;
            }
        }
        if min == pre_min {
            break;
        }
    }

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


Score : <var>100</var> points

Problem Statement

When you asked some guy in your class his name, he called himself <var>S</var>, where <var>S</var> is a string of length between <var>3</var> and <var>20</var> (inclusive) consisting of lowercase English letters.
You have decided to choose some three consecutive characters from <var>S</var> and make it his nickname. Print a string that is a valid nickname for him.

Constraints

<var>3 \leq |S| \leq 20</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 your answer.

Sample Input 1

takahashi

Sample Output 1

tak

Sample Input 2

naohiro

Sample Output 2

nao

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

    stdin().read_line(&mut is).ok();

    println!("{}", &is[..3]);
}


We call two numbers $$$x$$$ and $$$y$$$ similar if they have the same parity (the same remainder when divided by $$$2$$$), or if $$$|x-y|=1$$$. For example, in each of the pairs $$$(2, 6)$$$, $$$(4, 3)$$$, $$$(11, 7)$$$, the numbers are similar to each other, and in the pairs $$$(1, 4)$$$, $$$(3, 12)$$$, they are not.You are given an array $$$a$$$ of $$$n$$$ ($$$n$$$ is even) positive integers. Check if there is such a partition of the array into pairs that each element of the array belongs to exactly one pair and the numbers in each pair are similar to each other.For example, for the array $$$a = [11, 14, 16, 12]$$$, there is a partition into pairs $$$(11, 12)$$$ and $$$(14, 16)$$$. The numbers in the first pair are similar because they differ by one, and in the second pair because they are both even.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    scanf("%d", &n);
    int a[n];
    int nc = 0;
    int nl = n - 1;
    int v = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &v);
      if (v % 2 == 0) {
        a[nc] = v;
        nc++;
      } else {
        a[nl] = v;
        nl--;
      }
    }

    if (nc % 2 == 0 && (n - nc) % 2 == 0) {
      printf("YES\n");
    } else {
      bool k = false;
      while (nc--) {
        for (int i = n - 1; i > nl; i--) {
          if (a[nc] - a[i] == 1 || a[i] - a[nc] == 1) {
            k = true;
            break;
          }
        }

        if (k) {
          break;
        }
      }

      if (k) {
        printf("YES\n");
      } else {
        printf("NO\n");
      }
    }
  }
  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();
        let odd = a.iter().filter(|&&x| x % 2 == 0).count();
        let even = n - odd;
        if odd % 2 == 0 && even.is_multiple_of(2) {
            writeln!(out, "YES").ok();
        } else {
            a.sort();
            let mut ok = false;
            for i in 0..n - 1 {
                if a[i + 1] - a[i] == 1 {
                    writeln!(out, "YES").ok();
                    ok = true;
                    break;
                }
            }
            if !ok {
                writeln!(out, "NO").ok();
            }
        }
    }
    stdout().write_all(&out).unwrap();
}


Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?

int solution() {

  int n;
  int k;
  scanf("%d %d", &n, &k);
  int a[k];
  int por = (n / 2) + (n % 2);
  for (int i = 0; i < k; i++) {
    a[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    int tmp;
    scanf("%d", &tmp);
    a[tmp - 1]++;
  }
  for (int i = 0; i < k; i++) {
    while (a[i] > 1) {
      por--;
      a[i] -= 2;
    }
  }
  if (por > 0) {
    for (int i = 0; i < k; i++) {
      if (a[i] > 0 && por > 0) {
        a[i]--;
        por--;
      }
    }
  }
  int res = 0;
  for (int i = 0; i < k; i++) {
    res += a[i];
  }
  printf("%d", n - res);
  return 0;
}

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

    let n = get!();
    let k = get!(usize);
    let mut ds = vec![0; k];
    for _ in 0..n {
        let d = get!(usize) - 1;
        ds[d] += 1;
    }
    ds.retain(|&d| d > 0);
    ds.sort();
    let mut o = (n + 1) / 2;
    let mut ans = 0;
    let mut rem = 0;
    while let Some(d) = ds.pop() {
        rem += d % 2;
        let d = d - d % 2;
        if o >= d / 2 {
            ans += d;
            o -= d / 2;
        }
    }
    ans += std::cmp::min(o, rem);
    println!("{}", ans);
}


Score : <var>200</var> points

Problem Statement

There are four towns, numbered <var>1,2,3</var> and <var>4</var>.
Also, there are three roads. The <var>i</var>-th road connects different towns <var>a_i</var> and <var>b_i</var> bidirectionally.
No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roads.

Determine if we can visit all the towns by traversing each of the roads exactly once.

Constraints

<var>1 \leq a_i,b_i \leq 4(1\leq i\leq 3)</var>

<var>a_i</var> and <var>b_i</var> are different. <var>(1\leq i\leq 3)</var>

No two roads connect the same pair of towns.

Any town can be reached from any other town using the roads.

Input

Input is given from Standard Input in the following format:

<var>a_1</var> <var>b_1</var>
<var>a_2</var> <var>b_2</var>
<var>a_3</var> <var>b_3</var>

Output

If we can visit all the towns by traversing each of the roads exactly once, print YES; otherwise, print NO.

Sample Input 1

4 2
1 3
2 3

Sample Output 1

YES

We can visit all the towns in the order <var>1,3,2,4</var>.

Sample Input 2

3 2
2 4
1 2

Sample Output 2

NO

Sample Input 3

2 1
3 2
4 3

Sample Output 3

YES

int solution(void) {
  int a = 0;
  int b = 0;
  int c = 0;
  int d = 0;
  int e = 0;
  int f = 0;
  int g = 0;
  scanf("%d", &a);
  scanf("%d", &b);
  scanf("%d", &c);
  scanf("%d", &d);
  scanf("%d", &e);
  scanf("%d", &f);
  g = a + b + c + d + e + f;
  if (g == 15) {
    printf("YES\n");
  } else {
    printf("NO\n");
  }
  return 0;
}

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

    let iter = buf.split_whitespace().map(|c| c.parse::<usize>().unwrap());
    let mut counts = HashMap::new();

    for c in iter {
        if let Some(x) = counts.get_mut(&c) {
            *x += 1;
            continue;
        }
        counts.insert(c, 1);
    }

    if counts.values().all(|&c| (1..=2).contains(&c)) {
        println!("YES");
    } else {
        println!("NO");
    }
}


Score : <var>300</var> points

Problem Statement

When <var>l</var> is an odd number, the median of <var>l</var> numbers <var>a_1, a_2, ..., a_l</var> is the <var>(\frac{l+1}{2})</var>-th largest value among <var>a_1, a_2, ..., a_l</var>.

You are given <var>N</var> numbers <var>X_1, X_2, ..., X_N</var>, where <var>N</var> is an even number.
For each <var>i = 1, 2, ..., N</var>, let the median of <var>X_1, X_2, ..., X_N</var> excluding <var>X_i</var>, that is, the median of <var>X_1, X_2, ..., X_{i-1}, X_{i+1}, ..., X_N</var> be <var>B_i</var>.

Find <var>B_i</var> for each <var>i = 1, 2, ..., N</var>.

Constraints

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

<var>N</var> is even.

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>X_1</var> <var>X_2</var> ... <var>X_N</var>

Output

Print <var>N</var> lines.
The <var>i</var>-th line should contain <var>B_i</var>.

Sample Input 1

4
2 4 4 3

Sample Output 1

4
3
3
4

Since the median of <var>X_2, X_3, X_4</var> is <var>4</var>, <var>B_1 = 4</var>.

Since the median of <var>X_1, X_3, X_4</var> is <var>3</var>, <var>B_2 = 3</var>.

Since the median of <var>X_1, X_2, X_4</var> is <var>3</var>, <var>B_3 = 3</var>.

Since the median of <var>X_1, X_2, X_3</var> is <var>4</var>, <var>B_4 = 4</var>.

Sample Input 2

2
1 2

Sample Output 2

2
1

Sample Input 3

6
5 5 4 4 3 3

Sample Output 3

4
4
4
4
4
4

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut x = Vec::new();
    for i in 0..n {
        let a: usize = itr.next().unwrap().parse().unwrap();
        x.push((a, i));
    }
    x.sort();

    let mut ans = vec![0; n];
    let mut out = Vec::new();
    for i in 0..n {
        if i < n / 2 {
            ans[x[i].1] = x[n / 2].0;
        } else {
            ans[x[i].1] = x[n / 2 - 1].0;
        }
    }
    for i in 0..n {
        writeln!(out, "{}", ans[i]).ok();
    }
    stdout().write_all(&out).unwrap();
}


$$$2^k$$$ teams participate in a playoff tournament. The tournament consists of $$$2^k - 1$$$ games. They are held as follows: first of all, the teams are split into pairs: team $$$1$$$ plays against team $$$2$$$, team $$$3$$$ plays against team $$$4$$$ (exactly in this order), and so on (so, $$$2^{k-1}$$$ games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only $$$2^{k-1}$$$ teams remain. If only one team remains, it is declared the champion; otherwise, $$$2^{k-2}$$$ games are played: in the first one of them, the winner of the game "$$$1$$$ vs $$$2$$$" plays against the winner of the game "$$$3$$$ vs $$$4$$$", then the winner of the game "$$$5$$$ vs $$$6$$$" plays against the winner of the game "$$$7$$$ vs $$$8$$$", and so on. This process repeats until only one team remains.For example, this picture describes the chronological order of games with $$$k = 3$$$:  Let the string $$$s$$$ consisting of $$$2^k - 1$$$ characters describe the results of the games in chronological order as follows:  if $$$s_i$$$ is 0, then the team with lower index wins the $$$i$$$-th game;  if $$$s_i$$$ is 1, then the team with greater index wins the $$$i$$$-th game;  if $$$s_i$$$ is ?, then the result of the $$$i$$$-th game is unknown (any team could win this game). Let $$$f(s)$$$ be the number of possible winners of the tournament described by the string $$$s$$$. A team $$$i$$$ is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team $$$i$$$ is the champion.You are given the initial state of the string $$$s$$$. You have to process $$$q$$$ queries of the following form:   $$$p$$$ $$$c$$$ — replace $$$s_p$$$ with character $$$c$$$, and print $$$f(s)$$$ as the result of the query.

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

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

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

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

    let s = lines.next().unwrap();

    let n = 1 << k;
    let mut t = vec![(0, 0); n];

    for (i, c) in s.chars().enumerate() {
        let i = n - 1 - i;
        match c {
            '0' => {
                t[i].1 = 0;
                t[i].0 = t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1);
            }
            '1' => {
                t[i].1 = 1;
                t[i].0 = t.get(2 * i).map(|&(x, _)| x).unwrap_or(1);
            }
            _ => {
                t[i].1 = 2;
                t[i].0 = t.get(2 * i).map(|&(x, _)| x).unwrap_or(1)
                    + t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1);
            }
        }
    }

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

    for _ in 0..q {
        let s = lines.next().unwrap();
        let mut it = s.split_whitespace();

        let p = it.next().unwrap().parse::<usize>().unwrap();
        let c = it.next().unwrap();

        let mut i = n - p;
        let d = match c {
            "0" => 0,
            "1" => 1,
            _ => 2,
        };

        let a = match d {
            0 => t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1),
            1 => t.get(2 * i).map(|&(x, _)| x).unwrap_or(1),
            _ => {
                t.get(2 * i).map(|&(x, _)| x).unwrap_or(1)
                    + t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1)
            }
        };

        t[i].0 += a;

        let s = match t[i].1 {
            0 => t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1),
            1 => t.get(2 * i).map(|&(x, _)| x).unwrap_or(1),
            _ => {
                t.get(2 * i).map(|&(x, _)| x).unwrap_or(1)
                    + t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1)
            }
        };

        t[i].0 -= s;

        t[i].1 = d;

        i /= 2;

        while i > 0 {
            let s = match t[i].1 {
                0 => t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1),
                1 => t.get(2 * i).map(|&(x, _)| x).unwrap_or(1),
                _ => {
                    t.get(2 * i).map(|&(x, _)| x).unwrap_or(1)
                        + t.get(2 * i + 1).map(|&(x, _)| x).unwrap_or(1)
                }
            };

            t[i].0 = s;

            i /= 2;
        }

        let ans: u64 = t[1].0;
        writeln!(&mut output, "{}", ans).unwrap();
    }
}


void solution(int *array, int length) {
  int i, j;

  int **piles = (int **)malloc(sizeof(int *) * length);

  for (i = 0; i < length; ++i) {
    piles[i] = (int *)malloc(sizeof(int) * length);
  }

  int *pileSizes = (int *)calloc(length, sizeof(int));

  piles[0][0] = array[0];
  int pileCount = 1;

  for (i = 1; i < length; ++i) {
    int placed = 0;

    for (j = 0; j < pileCount; ++j) {
      if (piles[j][pileSizes[j]] > array[i]) {
        piles[j][pileSizes[j] + 1] = array[i];
        pileSizes[j]++;
        placed = 1;
        break;
      }
    }

    if (!placed) {
      piles[pileCount][0] = array[i];
      pileCount++;
    }
  }

  for (i = 0; i < length; ++i) {
    int min, minLocation = -1;

    for (j = 0; j < pileCount; ++j) {
      if (pileSizes[j] >= 0) {
        min = piles[j][pileSizes[j]];
        minLocation = j;
        break;
      }
    }

    for (j = 0; j < pileCount; ++j) {
      if (pileSizes[j] < 0)
        continue;

      if (piles[j][pileSizes[j]] < min) {
        min = piles[j][pileSizes[j]];
        minLocation = j;
      }
    }

    array[i] = min;
    pileSizes[minLocation]--;
  }

  free(pileSizes);

  for (i = 0; i < length; ++i) {
    free(piles[i]);
  }

  free(piles);
}

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

    let mut piles: Vec<Vec<T>> = Vec::new();
    for &card in arr.iter() {
        let mut left = 0usize;
        let mut right = piles.len();

        while left < right {
            let mid = left + (right - left) / 2;
            if piles[mid][piles[mid].len() - 1] >= card {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        if left == piles.len() {
            piles.push(vec![card]);
        } else {
            piles[left].push(card);
        }
    }

    let mut idx = 0usize;
    while let Some((min_id, pile)) = piles
        .iter()
        .enumerate()
        .min_by_key(|(_, pile)| *pile.last().unwrap())
    {
        arr[idx] = *pile.last().unwrap();
        idx += 1;
        piles[min_id].pop();

        if piles[min_id].is_empty() {
            _ = piles.remove(min_id);
        }
    }
}


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

int solution(void) {
  int n = 0;
  int i = 0;
  int min = -1;
  int max = -1;
  int cnt = 0;
  int arr[100000] = {
      0,
  };

  scanf("%d", &n);

  for (i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
    if (min == -1 || min > arr[i]) {
      min = arr[i];
    }

    if (max < arr[i]) {
      max = arr[i];
    }
  }

  for (i = 0; i < n; i++) {
    if (arr[i] > min && arr[i] < max) {
      cnt++;
    }
  }

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

  return 0;
}

fn solution() {
    use std::io;
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let mut ns: Vec<u32> = buf
        .split_whitespace()
        .map(|str| str.trim().parse().unwrap())
        .collect();
    ns.sort();
    let min = ns[0];
    let max = ns.last().copied().unwrap();
    if min == max {
        println!("0");
    } else {
        let num_min = ns.iter().take_while(|&&x| x == min).count();
        let num_max = ns.iter().rev().take_while(|&&x| x == max).count();
        println!("{}", (ns.len() - num_min) - num_max);
    }
}


Deque

  For a dynamic array $A = \{a_0, a_1, ...\}$ of integers, perform a sequence of the following operations:

push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$.

randomAccess($p$): Print element $a_p$.

pop($d$): Delete the first element of $A$, if $d = 0$. Delete the last element of $A$, if $d = 1$.

  $A$ is a 0-origin array and it is empty in the initial state.

Input

  The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given by

0 $d$ $x$

or

1 $p$

or

2 $d$

  where the first digits 0, 1 and 2 represent push, randomAccess and pop operations respectively.

 randomAccess and pop operations will not be given for an empty array.

Output

  For each randomAccess, print $a_p$ in a line.

Constraints

$1 \leq q \leq 400,000$

$0 \leq p < $ the size of $A$

$-1,000,000,000 \leq x \leq 1,000,000,000$

Sample Input 1

11
0 0 1
0 0 2
0 1 3
1 0
1 1
1 2
2 0
2 1
0 0 4
1 0
1 1

Sample Output 1

2
1
3
4
1

int solution() {
  int q;
  scanf("%d", &q);
  int A[q * 2];
  int head = q;
  int end = q;
  int order;
  int hob;
  int position;
  int data;

  while (q--) {
    scanf("%d", &order);
    switch (order) {
    case 0:
      scanf("%d%d", &hob, &data);
      if (hob == 0) {
        head--;
        A[head] = data;

      } else {
        A[end] = data;
        end++;
      }

      break;

    case 1:
      scanf("%d", &position);
      printf("%d\n", A[head + position]);
      break;

    case 2:
      scanf("%d", &hob);
      if (hob == 0) {
        head++;
      } else {
        end--;
      }

      break;
    }
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    let row: usize = s.trim().parse().unwrap_or(0);
    s.clear();
    let mut array = VecDeque::with_capacity(row);

    for _ in 0..row {
        io::stdin().read_line(&mut s).ok();
        let v: Vec<isize> = s
            .split_whitespace()
            .map(|e| e.parse().unwrap_or(0))
            .collect();

        match v[0] {
            0 => {
                if v[1] == 0 {
                    array.push_front(v[2]);
                } else {
                    array.push_back(v[2]);
                }
            }
            1 => {
                println!("{}", array[v[1] as usize]);
            }
            2 => {
                if v[1] == 0 {
                    array.pop_front();
                } else {
                    array.pop_back();
                }
            }
            _ => println!("error 0 or 1 or 2"),
        }
        s.clear();
    }
}


We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array:  The array consists of $$$n$$$ distinct positive (greater than $$$0$$$) integers.  The array contains two elements $$$x$$$ and $$$y$$$ (these elements are known for you) such that $$$x < y$$$.  If you sort the array in increasing order (such that $$$a_1 < a_2 < \ldots < a_n$$$), differences between all adjacent (consecutive) elements are equal (i.e. $$$a_2 - a_1 = a_3 - a_2 = \ldots = a_n - a_{n-1})$$$. It can be proven that such an array always exists under the constraints given below.Among all possible arrays that satisfy the given conditions, we ask you to restore one which has the minimum possible maximum element. In other words, you have to minimize $$$\max(a_1, a_2, \dots, a_n)$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int x;
    int y;
    scanf("%d%d%d", &n, &x, &y);
    int jiange = 1;
    int zhongjiangeshu = y - x - 1;

    while (1) {
      if ((zhongjiangeshu + 1) % jiange == 0) {
        if (zhongjiangeshu / jiange + 2 <= n) {
          break;
        }
      }
      jiange++;
    }
    int tempy = y;
    while (1) {
      printf("%d ", tempy);
      tempy -= jiange;
      n--;
      if (tempy <= 0 || n == 0) {
        break;
      }
    }
    tempy = y + jiange;
    while (n--) {
      printf("%d ", tempy);
      tempy += jiange;
    }
    printf("\n");
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let t: i32 = s.trim().parse().unwrap();
    for _i in 0..t {
        s.clear();
        io::stdin().read_line(&mut s).unwrap();
        let arr: Vec<i32> = s.split_whitespace().map(|s| s.parse().unwrap()).collect();
        let (n, x, y) = (arr[0], arr[1], arr[2]);
        let mut d = 0;
        loop {
            d += 1;
            if (y - x) % d == 0 && (y - x) / d < n {
                break;
            }
        }
        let d = d;
        let st = {
            let mut x = y % d;
            if x == 0 {
                x = d;
            }
            x
        };
        let st = cmp::max(st, y - (n - 1) * d);
        for i in 0..n {
            if i > 0 {
                print!(" ");
            }
            print!("{}", st + i * d);
        }
        println!();
    }
}


You are given an array $$$a$$$ with $$$n$$$ integers. You can perform the following operation at most $$$k$$$ times:  Choose two indices $$$i$$$ and $$$j$$$, in which $$$i \,\bmod\, k = j \,\bmod\, k$$$ ($$$1 \le i < j \le n$$$).  Swap $$$a_i$$$ and $$$a_j$$$. After performing all operations, you have to select $$$k$$$ consecutive elements, and the sum of the $$$k$$$ elements becomes your score. Find the maximum score you can get.Here $$$x \bmod y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.

int solution() {
  long x[1000] = {0};
  int t = 0;
  scanf("%d", &t);
  int len = 0;
  int k = 0;
  for (int T = 0; T < t; T++) {
    scanf("%d  %d", &len, &k);
    for (int i = 0; i < len; i++) {
      scanf("%ld", &x[i]);
    }
    long long sum = 0;
    for (int i = 0; i < k; i++) {
      int mid = 0;
      for (int j = i; j < len; j += k) {
        mid = x[j] > mid ? x[j] : mid;
      }
      sum += mid;
    }
    printf("%lld\n", sum);
  }
  return 0;
}

fn solution() {
    let k = std::io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i64>()
        .unwrap();
    'joker: for _ in 0..k {
        let mut l = String::new();
        std::io::stdin().read_line(&mut l).unwrap();
        let l = l
            .trim()
            .split(" ")
            .flat_map(str::parse::<i64>)
            .collect::<Vec<_>>();
        let mut m = String::new();
        std::io::stdin().read_line(&mut m).unwrap();
        let mut m = m
            .trim()
            .split(" ")
            .flat_map(str::parse::<i64>)
            .collect::<Vec<_>>();
        let mut ans = 0i64;
        let _flag = true;
        let mut cl_f = l[0];
        'jester: while cl_f != 0 {
            'clown: for ids in 0..l[0] {
                if ids == m.len() as i64 - l[1] {
                    break 'clown;
                }
                if m[ids as usize] < m[ids as usize + l[1] as usize] {
                    m.swap(ids as usize, ids as usize + l[1] as usize);
                }
            }
            cl_f -= 1;
        }
        for vls in 0..l[1] {
            ans += m[vls as usize]
        }
        println!("{}", ans);
    }
}


Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat the patty-cakes but to try not to eat the patty-cakes with the same filling way too often. To achieve this she wants the minimum distance between the eaten with the same filling to be the largest possible. Herein Pinkie Pie called the distance between two patty-cakes the number of eaten patty-cakes strictly between them.Pinkie Pie can eat the patty-cakes in any order. She is impatient about eating all the patty-cakes up so she asks you to help her to count the greatest minimum distance between the eaten patty-cakes with the same filling amongst all possible orders of eating!Pinkie Pie is going to buy more bags of patty-cakes so she asks you to solve this problem for several bags!

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

  while (t != 0) {
    long long int n;
    scanf("%lld", &n);

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

    long long int *c = (long long int *)malloc(100000 * sizeof(long long int));

    for (i = 0; i < 100000; ++i) {
      c[i] = 0;
    }

    for (i = 0; i < n; ++i) {
      c[b[i] - 1] += 1;
    }
    long long int select;
    for (i = n - 1; i >= 0; --i) {
      if (c[i] != 0) {
        select = i;
        break;
      }
    }

    long long int sol = c[select];
    long long int aux = n - ((select + 1) * c[select]);
    sol = sol + aux / select - 1;
    printf("%lld\n", sol);

    --t;
  }
}

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

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

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

        let mut map = HashMap::new();
        for i in 0..n {
            *map.entry(a[i]).or_insert(0) += 1;
        }

        let (mut left, mut right) = (0, n);
        'outer: while right - left > 1 {
            let mid = (left + right) / 2;

            let mut heap = BinaryHeap::new();
            for &value in map.values() {
                heap.push(value);
            }

            let mut memo = vec![0; n];
            for i in 0..n {
                if let Some(value) = heap.pop() {
                    memo[i] = value - 1;
                } else {
                    right = mid;
                    continue 'outer;
                }
                if i >= mid && memo[i - mid] > 0 {
                    heap.push(memo[i - mid]);
                }
            }
            left = mid;
        }
        println!("{}", left);
    }
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> islands lining up from west to east, connected by <var>N-1</var> bridges.

The <var>i</var>-th bridge connects the <var>i</var>-th island from the west and the <var>(i+1)</var>-th island from the west.

One day, disputes took place between some islands, and there were <var>M</var> requests from the inhabitants of the islands:

Request <var>i</var>: A dispute took place between the <var>a_i</var>-th island from the west and the <var>b_i</var>-th island from the west. Please make traveling between these islands with bridges impossible.

You decided to remove some bridges to meet all these <var>M</var> requests.

Find the minimum number of bridges that must be removed.

Constraints

All values in input are integers.

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

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

<var>1 \leq a_i < b_i \leq N</var>

All pairs <var>(a_i, b_i)</var> are distinct.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>a_2</var> <var>b_2</var>
<var>:</var>
<var>a_M</var> <var>b_M</var>

Output

Print the minimum number of bridges that must be removed.

Sample Input 1

5 2
1 4
2 5

Sample Output 1

1

The requests can be met by removing the bridge connecting the second and third islands from the west.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

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

Sample Output 3

4

int solution(void) {
  int n;
  int m;
  int near = 0;
  int ans = 0;
  scanf("%d%d", &n, &m);
  int a[m];
  int b[m];
  int c[n];
  for (int i = 0; i < n; i++) {
    c[i] = 1e9;
  }
  for (int i = 0; i < m; i++) {
    scanf("%d%d", &a[i], &b[i]);
    a[i]--;
    b[i]--;
    if (c[a[i]] > b[i]) {
      c[a[i]] = b[i];
    }
  }
  for (int i = 0; i < n; i++) {
    if (c[i] != 1e9) {
      if (i >= near) {
        ans++;
        near = c[i];
      } else if (c[i] < near) {
        near = c[i];
      }
    }
  }
  printf("%d\n", ans);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.trim().split(" ");
    let _n: usize = iter.next().unwrap().parse().unwrap();
    let m: usize = iter.next().unwrap().parse().unwrap();
    let mut v: Vec<(u32, u32)> = Vec::with_capacity(m);
    for _ in 0..m {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.trim().split(" ");
        let a: u32 = iter.next().unwrap().parse().unwrap();
        let b: u32 = iter.next().unwrap().parse().unwrap();
        v.push((a, b));
    }
    v.sort_by_key(|&x| x.1);
    let mut s: BTreeSet<u32> = BTreeSet::new();
    for (a, b) in v {
        if s.iter().any(|&x| a <= x && x < b) {
            continue;
        }
        s.insert(b - 1);
    }
    println!("{}", s.len());
}


You are given a binary string $$$s$$$ (recall that a string is binary if each character is either $$$0$$$ or $$$1$$$).Let $$$f(t)$$$ be the decimal representation of integer $$$t$$$ written in binary form (possibly with leading zeroes). For example $$$f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$$$ and $$$f(000100) = 4$$$.The substring $$$s_{l}, s_{l+1}, \dots , s_{r}$$$ is good if $$$r - l + 1 = f(s_l \dots s_r)$$$.For example string $$$s = 1011$$$ has $$$5$$$ good substrings: $$$s_1 \dots s_1 = 1$$$, $$$s_3 \dots s_3 = 1$$$, $$$s_4 \dots s_4 = 1$$$, $$$s_1 \dots s_2 = 10$$$ and $$$s_2 \dots s_4 = 011$$$. Your task is to calculate the number of good substrings of string $$$s$$$.You have to answer $$$t$$$ independent queries.

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

  while (t--) {
    char *s = malloc(sizeof(char) * 200001);
    int str_len;
    int good_substrings = 0;
    int zeros = 0;

    scanf("%s", s);
    str_len = strlen(s);

    for (int i = 0; i < str_len; i++) {
      if (s[i] == '0') {
        zeros++;
      } else {
        long long val = 0;
        int substr_len = zeros;
        for (int j = i; j < str_len && val <= substr_len; j++) {
          substr_len++;
          val <<= 1;
          val += s[j] - 48;
          if (val <= substr_len) {
            good_substrings++;
          }
        }
        zeros = 0;
      }
    }

    free(s);
    printf("%d\n", good_substrings);
  }

  return 0;
}

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

    let t = get!();
    for _ in 0..t {
        let s = get().as_bytes();
        let mut z = 0;
        let mut ans = 0;
        for i in 0..s.len() {
            let x = (s[i] - b'0') as u32;
            if x == 0 {
                z += 1;
                continue;
            }
            let mut e = x;
            ans += 1;
            for j in i + 1..s.len() {
                let c = (j - i + 1) + z;
                let y = (s[j] - b'0') as u32;
                e = (e << 1) | y;
                if e > c as u32 {
                    break;
                }
                ans += 1;
            }
            z = 0;
        }
        println!("{}", ans);
    }
}


Score : <var>300</var> points

Problem Statement

If there is an integer not less than <var>0</var> satisfying the following conditions, print the smallest such integer; otherwise, print -1.

The integer has exactly <var>N</var> digits in base ten. (We assume <var>0</var> to be a <var>1</var>-digit integer. For other integers, leading zeros are not allowed.)

The <var>s_i</var>-th digit from the left is <var>c_i</var>. <var>\left(i = 1, 2, \cdots, M\right)</var>

Constraints

All values in input are integers.

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

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

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

<var>0 \leq c_i \leq 9</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>s_1</var> <var>c_1</var>
<var>\vdots</var>
<var>s_M</var> <var>c_M</var>

Output

Print the answer.

Sample Input 1

3 3
1 7
3 2
1 7

Sample Output 1

702

<var>702</var> satisfies the conditions - its <var>1</var>-st and <var>3</var>-rd digits are 7 and 2, respectively - while no non-negative integer less than <var>702</var> satisfies them.

Sample Input 2

3 2
2 1
2 3

Sample Output 2

-1

Sample Input 3

3 1
1 0

Sample Output 3

-1

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let m: usize = s.next().unwrap().parse().unwrap();
    let a: Vec<_> = (0..m)
        .map(|_| {
            (
                s.next().unwrap().parse::<usize>().unwrap(),
                s.next().unwrap().parse::<usize>().unwrap(),
            )
        })
        .collect();
    let range = match n {
        1 => 0..10,
        2 => 10..100,
        3 => 100..1000,
        _ => panic!(),
    };
    'a: for i in range {
        let mut j = i;
        let mut d = vec![];
        for _ in 0..n {
            d.push(j % 10);
            j /= 10;
        }
        for &(s, c) in a.iter() {
            if d[n - s] != c {
                continue 'a;
            }
        }
        println!("{}", i);
        return;
    }
    println!("-1");
}


In order to write a string, Atilla needs to first learn all letters that are contained in the string.Atilla needs to write a message which can be represented as a string $$$s$$$. He asks you what is the minimum alphabet size required so that one can write this message.The alphabet of size $$$x$$$ ($$$1 \leq x \leq 26$$$) contains only the first $$$x$$$ Latin letters. For example an alphabet of size $$$4$$$ contains only the characters $$$\texttt{a}$$$, $$$\texttt{b}$$$, $$$\texttt{c}$$$ and $$$\texttt{d}$$$.

int solution() {
  int m = 0;
  int n = 0;
  int max = 0;
  char a[102];
  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    scanf("%d", &n);
    scanf("%s", a);
    max = a[0];
    for (int j = 0; j < n; j++) {
      if (max < a[j]) {
        max = a[j];
      }
    }
    max = max - 'a' + 1;
    printf("%d\n", max);
  }
  return 0;
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(2)
        .step_by(2)
        .flatten()
        .for_each(|s| {
            if let Some(m) = s.as_bytes().iter().max() {
                let ans = m.wrapping_sub(b'`');
                writeln!(buf, "{ans}").ok();
            };
        });
}


Vasya has his favourite number $$$n$$$. He wants to split it to some non-zero digits. It means, that he wants to choose some digits $$$d_1, d_2, \ldots, d_k$$$, such that $$$1 \leq d_i \leq 9$$$ for all $$$i$$$ and $$$d_1 + d_2 + \ldots + d_k = n$$$.Vasya likes beauty in everything, so he wants to find any solution with the minimal possible number of different digits among $$$d_1, d_2, \ldots, d_k$$$. Help him!

int solution() {
  int x;
  scanf("%d", &x);
  printf("%d\n", x);
  while (x--) {
    printf("1 ");
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    let number: u16 = lines.next().unwrap().unwrap().parse::<u16>().unwrap();

    let mut output = String::with_capacity(2000);
    write!(output, "{}\n1", number).unwrap();
    for _ in 1..number {
        write!(output, " 1").unwrap();
    }

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


Score : <var>100</var> points

Problem Statement

In programming, hexadecimal notation is often used.

In hexadecimal notation, besides the ten digits <var>0, 1, ..., 9</var>, the six letters A, B, C, D, E and F are used to represent the values <var>10, 11, 12, 13, 14</var> and <var>15</var>, respectively.

In this problem, you are given two letters <var>X</var> and <var>Y</var>. Each <var>X</var> and <var>Y</var> is A, B, C, D, E or F.

When <var>X</var> and <var>Y</var> are seen as hexadecimal numbers, which is larger?

Constraints

Each <var>X</var> and <var>Y</var> is A, B, C, D, E or F.

Input

Input is given from Standard Input in the following format:

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

Output

If <var>X</var> is smaller, print <; if <var>Y</var> is smaller, print >; if they are equal, print =.

Sample Input 1

A B

Sample Output 1

<

<var>10 < 11</var>.

Sample Input 2

E C

Sample Output 2

>

<var>14 > 12</var>.

Sample Input 3

F F

Sample Output 3

=

<var>15 = 15</var>.

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let s: Vec<&str> = buf.split_whitespace().collect();

    if s[0] > s[1] {
        println!(">");
    } else if s[0] == s[1] {
        println!("=");
    } else {
        println!("<");
    }
}


You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i. e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.You have to answer $$$t$$$ independent test cases.

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

    let t: usize = testcases.trim().parse().expect("errr");
    testcases.clear();

    for _ in 0..t {
        let mut n = String::new();
        io::stdin().read_line(&mut n).expect("Error");
        let n: usize = n.trim().parse().expect("errr");
        let tme: usize;
        let m = n % 3;
        let n3: usize = n / 3;
        if n == 1 {
            tme = 2;
        } else if m == 0 {
            tme = n3;
        } else {
            tme = n3 + 1;
        };
        println!("{}", tme);
    }
}


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

int solution() {
  int t = 0;
  scanf("%d", &t);
  long int n = 0;
  int temp = 0;
  int count = 0;
  for (int i = 0; i < t; i++) {
    scanf("%ld", &n);
    count = 0;
    while (n != 0) {
      temp = n % 10;
      if (temp > count) {
        count = temp;
      }
      n = n / 10;
    }
    printf("%d\n", count);
  }
  return 0;
}

fn solution() -> Result<(), Box<dyn Error>> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let cases = input.trim().parse::<u32>()?;
    for _ in 0..cases {
        input.clear();
        io::stdin().read_line(&mut input)?;
        let mut n = input.trim().parse::<u32>()?;
        let mut max_digit = 0;
        while n != 0 {
            let d = n % 10;
            if d > max_digit {
                max_digit = d;
            }
            n /= 10;
        }
        println!("{}", max_digit)
    }

    Ok(())
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> bags of biscuits. The <var>i</var>-th bag contains <var>A_i</var> biscuits.

Takaki will select some of these bags and eat all of the biscuits inside.
Here, it is also possible to select all or none of the bags.

He would like to select bags so that the total number of biscuits inside is congruent to <var>P</var> modulo <var>2</var>.
How many such ways to select bags there are?

Constraints

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

<var>P = 0</var> or <var>1</var>

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of ways to select bags so that the total number of biscuits inside is congruent to <var>P</var> modulo <var>2</var>.

Sample Input 1

2 0
1 3

Sample Output 1

2

There are two ways to select bags so that the total number of biscuits inside is congruent to <var>0</var> modulo <var>2</var>:

Select neither bag. The total number of biscuits is <var>0</var>.

Select both bags. The total number of biscuits is <var>4</var>.

Sample Input 2

1 1
50

Sample Output 2

0

Sample Input 3

3 0
1 1 1

Sample Output 3

4

Two bags are distinguished even if they contain the same number of biscuits.

Sample Input 4

45 1
17 55 85 55 74 20 90 67 40 70 39 89 91 50 16 24 14 43 24 66 25 9 89 71 41 16 53 13 61 15 85 72 62 67 42 26 36 66 4 87 59 91 4 25 26

Sample Output 4

17592186044416

int solution(void) {
  int n;
  int p;
  int even = 0;
  int odd = 0;
  long long ans = 1;
  long long tmp1 = 1;
  long long tmp2 = 0;
  scanf("%d%d", &n, &p);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    if (a[i] % 2 == 0) {
      even++;
    } else {
      odd++;
    }
  }
  if (p == 0) {
    for (int i = 0; i < even; i++) {
      ans *= 2;
    }
    for (int i = 0; i <= odd / 2; i++) {
      for (int j = 0; j < i * 2; j++) {
        tmp1 = tmp1 * (odd - j) / (j + 1);
      }
      tmp2 += tmp1;
      tmp1 = 1;
    }
    ans = ans * tmp2;
  } else {
    for (int i = 0; i < even; i++) {
      ans *= 2;
    }
    for (int i = 0; i < odd / 2; i++) {
      for (int j = 0; j < i * 2 + 1; j++) {
        tmp1 = tmp1 * (odd - j) / (j + 1);
      }
      tmp2 += tmp1;
      tmp1 = 1;
    }
    ans = ans * tmp2;
  }
  printf("%lld\n", ans);
  return 0;
}

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

    let ans = if A.iter().all(|&a| a % 2 == 0) {
        (1 - P) * 2i64.pow(N as u32)
    } else {
        2i64.pow((N - 1) as u32)
    };

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


A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.There is a string $$$s$$$. You must insert exactly one character 'a' somewhere in $$$s$$$. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose $$$s=$$$ "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.

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

    let mut it = input.split_whitespace();

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

    for s in it {
        match s.chars().position(|c| c != 'a') {
            Some(i) => {
                let j = s.len() - i;
                let (s0, s1) = s.split_at(j);
                println!("YES\n{}a{}", s0, s1);
            }
            None => println!("NO"),
        }
    }
}


You are given a bracket sequence $$$s$$$ of length $$$n$$$, where $$$n$$$ is even (divisible by two). The string $$$s$$$ consists of $$$\frac{n}{2}$$$ opening brackets '(' and $$$\frac{n}{2}$$$ closing brackets ')'.In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index $$$i$$$, remove the $$$i$$$-th character of $$$s$$$ and insert it before or after all remaining characters of $$$s$$$).Your task is to find the minimum number of moves required to obtain regular bracket sequence from $$$s$$$. It can be proved that the answer always exists under the given constraints.Recall what the regular bracket sequence is:  "()" is regular bracket sequence;  if $$$s$$$ is regular bracket sequence then "(" + $$$s$$$ + ")" is regular bracket sequence;  if $$$s$$$ and $$$t$$$ are regular bracket sequences then $$$s$$$ + $$$t$$$ is regular bracket sequence. For example, "()()", "(())()", "(())" and "()" are regular bracket sequences, but ")(", "()(" and ")))" are not.You have to answer $$$t$$$ independent test cases.

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

  for (int i = 0; i < n; i++) {
    int br = 0;
    int sum = 0;
    int moves = 0;
    char c = '0';
    scanf("%d", &br);
    while (br >= 0) {
      br--;
      scanf("%c", &c);
      if (c == '(') {
        sum++;
      } else if (c == ')') {
        sum--;
      }
      if (sum < 0) {
        moves++;
        sum++;
      }
    }
    printf("%d\n", moves);
  }
}

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 _ = lines.next().unwrap().unwrap();
        let cs: Vec<char> = lines.next().unwrap().unwrap().chars().collect();
        let mut x: i32 = 0;
        let mut m: i32 = 0;
        for c in cs {
            x += if c == ')' { -1 } else { 1 };
            m = min(m, x);
        }
        println!("{}", -m);
    }
}


Score: <var>100</var> points

Problem Statement

E869120's and square1001's <var>16</var>-th birthday is coming soon.

Takahashi from AtCoder Kingdom gave them a round cake cut into <var>16</var> equal fan-shaped pieces.

E869120 and square1001 were just about to eat <var>A</var> and <var>B</var> of those pieces, respectively,

when they found a note attached to the cake saying that "the same person should not take two adjacent pieces of cake".

Can both of them obey the instruction in the note and take desired numbers of pieces of cake?

Constraints

<var>A</var> and <var>B</var> are integers between <var>1</var> and <var>16</var> (inclusive).

<var>A+B</var> is at most <var>16</var>.

Input

Input is given from Standard Input in the following format:

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

Output

If both E869120 and square1001 can obey the instruction in the note and take desired numbers of pieces of cake, print Yay!; otherwise, print :(.

Sample Input 1

5 4

Sample Output 1

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 2

8 8

Sample Output 2

Yay!

Both of them can take desired number of pieces as follows:

Sample Input 3

11 4

Sample Output 3

:(

In this case, there is no way for them to take desired number of pieces, unfortunately.

int solution() {
  int A = 0;
  int B = 0;

  scanf("%d %d", &A, &B);

  if (A <= 8 && B <= 8) {
    printf("Yay!\n");
  } else {
    printf(":(\n");
  }

  return 0;
}

fn solution() {
    let mut args = String::new();
    stdin().read_line(&mut args).expect("Failed to read line");
    let args: Vec<i32> = args
        .split_whitespace()
        .filter_map(|it| it.parse().ok())
        .collect();
    let a = args[0];
    let b = args[1];
    println!("{}", if a > 8 || b > 8 { ":(" } else { "Yay!" });
}


Sorting Five Numbers

Write a program which reads five numbers and sorts them in descending order.

Input

Input consists of five numbers <var>a</var>, <var>b</var>, <var>c</var>, <var>d</var> and  <var>e</var> (-100000 ≤ <var>a</var>, <var>b</var>, <var>c</var>, <var>d</var>,<var>e</var> ≤ 100000). The five numbers are separeted by a space.

Output

Print the ordered numbers in a line. Adjacent numbers should be separated by a space.

Sample Input

3 6 9 7 5

Output for the Sample Input

9 7 6 5 3

int solution(void) {
  int number[5];
  int i;
  int j;
  scanf("%d %d %d %d %d", &number[0], &number[1], &number[2], &number[3],
        &number[4]);

  for (i = 0; i < 5; i++) {
    for (j = 4; j > i; j--) {
      if (number[j] > number[j - 1]) {
        int temp = number[j];
        number[j] = number[j - 1];
        number[j - 1] = temp;
      }
    }
  }
  for (i = 0; i < 4; i++) {
    printf("%d ", number[i]);
  }
  printf("%d\n", number[4]);

  return 0;
}

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let mut values: Vec<i32> = buf
        .split_whitespace()
        .filter_map(|x| x.parse::<i32>().ok())
        .collect();
    values.sort();
    let values: Vec<String> = values.iter().rev().map(|x| x.to_string()).collect();
    println!("{}", values.join(" "));
}


Score : <var>300</var> points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate <var>X</var>. He will make exactly <var>K</var> moves of distance <var>D</var> in the positive or negative direction.

More specifically, in one move, he can go from coordinate <var>x</var> to <var>x + D</var> or <var>x - D</var>.

He wants to make <var>K</var> moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

<var>-10^{15} \leq X \leq 10^{15}</var>

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

<var>1 \leq D \leq 10^{15}</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>K</var> <var>D</var>

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate <var>6</var>. It is optimal to make the following moves:

Move from coordinate <var>6</var> to (<var>6 - 4 =</var>) <var>2</var>.

Move from coordinate <var>2</var> to (<var>2 - 4 =</var>) <var>-2</var>.

Here, the absolute value of the coordinate of the destination is <var>2</var>, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate <var>7</var>. It is optimal to make, for example, the following moves:

Move from coordinate <var>7</var> to <var>4</var>.

Move from coordinate <var>4</var> to <var>7</var>.

Move from coordinate <var>7</var> to <var>4</var>.

Move from coordinate <var>4</var> to <var>1</var>.

Here, the absolute value of the coordinate of the destination is <var>1</var>, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.

int solution(void) {
  long long int x;
  long long int k;
  long long int d;
  long long int q;
  long long int r;
  scanf("%lld%lld%lld", &x, &k, &d);
  x = llabs(x);
  d = llabs(d);
  q = x / d;
  r = x % d;
  if (k <= q) {
    printf("%lld", x - (d * k));
    return 0;
  }
  if ((k - q) % 2 == 0) {
    printf("%lld", r);
    return 0;
  }
  if ((k - q) % 2 != 0) {
    printf("%lld", d - r);
    return 0;
  }
}

fn solution() {
    let (x, k, d): (i64, i64, i64) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };

    let x = x.abs();
    let c = x / d;
    if c <= k {
        if (k - c) % 2 == 0 {
            println!("{}", x - c * d);
        } else {
            println!("{}", (c + 1) * d - x);
        }
    } else {
        println!("{}", x - k * d);
    }
}


Suppose you are performing the following algorithm. There is an array $$$v_1, v_2, \dots, v_n$$$ filled with zeroes at start. The following operation is applied to the array several times — at $$$i$$$-th step ($$$0$$$-indexed) you can:   either choose position $$$pos$$$ ($$$1 \le pos \le n$$$) and increase $$$v_{pos}$$$ by $$$k^i$$$;  or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array $$$v$$$ equal to the given array $$$a$$$ ($$$v_j = a_j$$$ for each $$$j$$$) after some step?

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

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

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

        let _n = words[0];
        let k = words[1];

        line = String::new();
        stdin().read_line(&mut line).unwrap();

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

        let mut ans = "YES";
        while a.iter().any(|&x| x != 0) {
            let b = a
                .iter()
                .map(|x| x % k)
                .filter(|&x| x != 0)
                .collect::<Vec<i64>>();
            if b > vec![1] {
                ans = "NO";
                break;
            }
            a = a.iter().map(|x| x / k).collect();
        }
        println!("{}", ans);
    }
}


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

int solution() {
  char str[1001];
  scanf("%s", str);
  int i = 0;
  int ans = 0;
  int k;
  int cnt[26];
  scanf("%d", &k);
  while (i < 26) {
    cnt[i++] = 0;
  }
  i = 0;
  while (str[i] != '\0') {
    if (cnt[str[i] - 'a'] == 0) {
      ans++;
      cnt[str[i] - 'a'] = 1;
    }
    i++;
  }
  if (i < k) {
    printf("impossible\n");
  } else if (ans > k) {
    printf("0\n");
  } else {
    printf("%d\n", k - ans);
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).expect("Something went wrong");
    let s: &str = s.trim();
    let mut k = String::new();
    io::stdin().read_line(&mut k).expect("Something went wrong");
    let k: i32 = k.trim().parse().expect("Something went wrong");
    if k > s.len() as i32 {
        println!("impossible")
    } else {
        let s1: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
        let mut a: [i32; 26] = [0; 26];
        for c in s.chars() {
            let mut d: usize = 25;
            let mut b: usize = 0;
            let mut m: usize = (b + d) / 2;
            while b < d - 1 {
                m = (b + d) / 2;
                if c > s1[m] {
                    b = m
                } else {
                    d = m
                }
            }
            if d == 1 && c == 'a' {
                a[0] = 1
            } else if a[d] == 0 {
                a[d] = 1;
            }
        }
        let mut sum: i32 = 0;
        for f in 0..26 {
            sum += a[f];
        }
        if k - sum > 0 {
            println!("{}", k - sum)
        } else {
            println!("0")
        }
    }
}


The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:  Operation ++ increases the value of variable x by 1.  Operation -- decreases the value of variable x by 1. A statement in language Bit++ is a sequence, consisting of exactly one operation and one variable x. The statement is written without spaces, that is, it can only contain characters "+", "-", "X". Executing a statement means applying the operation it contains.A programme in Bit++ is a sequence of statements, each of them needs to be executed. Executing a programme means executing all the statements it contains.You're given a programme in language Bit++. The initial value of x is 0. Execute the programme and find its final value (the value of the variable when this programme is executed).

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let num = buf.trim().parse::<u8>().unwrap();
    let mut result = 0;
    buf.clear();
    for _ in 0..num {
        io::stdin().read_line(&mut buf).unwrap();
    }

    for c in buf.chars() {
        if c == '+' {
            result += 1;
        }
        if c == '-' {
            result -= 1;
        }
    }
    println!("{}", result / 2);
}


Polycarp has an array $$$a$$$ consisting of $$$n$$$ integers.He wants to play a game with this array. The game consists of several moves. On the first move he chooses any element and deletes it (after the first move the array contains $$$n-1$$$ elements). For each of the next moves he chooses any element with the only restriction: its parity should differ from the parity of the element deleted on the previous move. In other words, he alternates parities (even-odd-even-odd-... or odd-even-odd-even-...) of the removed elements. Polycarp stops if he can't make a move.Formally:   If it is the first move, he chooses any element and deletes it;  If it is the second or any next move:   if the last deleted element was odd, Polycarp chooses any even element and deletes it;  if the last deleted element was even, Polycarp chooses any odd element and deletes it.   If after some move Polycarp cannot make a move, the game ends. Polycarp's goal is to minimize the sum of non-deleted elements of the array after end of the game. If Polycarp can delete the whole array, then the sum of non-deleted elements is zero.Help Polycarp find this value.

int solution() {
  int n;
  int even = 0;
  scanf("%d", &n);
  int ara[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &ara[i]);
    if (ara[i] % 2 == 0) {
      even++;
    }
  }
  int odd = n - even;
  if (odd == even || odd + 1 == even || even + 1 == odd) {
    printf("0\n");
  } else if (odd > even) {
    int len = n - (2 * even) - 1;
    for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
        if (ara[i] > ara[j]) {
          int tmp = ara[i];
          ara[i] = ara[j];
          ara[j] = tmp;
        }
      }
    }
    int sum = 0;
    for (int i = 0; i < len; i++) {
      if (ara[i] % 2 == 1) {
        sum += ara[i];
      } else {
        len++;
      }
    }
    printf("%d\n", sum);
  } else {
    int len = n - (2 * odd) - 1;
    for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
        if (ara[i] > ara[j]) {
          int tmp = ara[i];
          ara[i] = ara[j];
          ara[j] = tmp;
        }
      }
    }
    int sum = 0;
    for (int i = 0; i < len; i++) {
      if (ara[i] % 2 == 0) {
        sum += ara[i];
      } else {
        len++;
      }
    }
    printf("%d\n", sum);
  }
  return 0;
}

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

    io::stdin().read_line(&mut input).unwrap();
    let a: Vec<isize> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let (mut even, mut odd): (Vec<isize>, Vec<isize>) = a.into_iter().partition(|&x| x % 2 == 0);

    even.sort();
    even.reverse();
    odd.sort();
    odd.reverse();

    let diff = (odd.len() as isize - even.len() as isize).abs();

    let mut diff_vec = vec![];
    if diff > 1 {
        for _ in 0..diff as usize {
            if even.len() > odd.len() {
                diff_vec.push(even.pop().unwrap());
            } else if odd.len() > even.len() {
                diff_vec.push(odd.pop().unwrap());
            }
        }
    }
    diff_vec.pop();

    let sum = diff_vec.iter().sum::<isize>();
    println!("{}", sum);
}


The only difference between easy and hard versions are constraints on $$$n$$$ and $$$k$$$.You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most $$$k$$$ most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals $$$0$$$).Each conversation is between you and some of your friends. There is at most one conversation with any of your friends. So each conversation is uniquely defined by your friend.You (suddenly!) have the ability to see the future. You know that during the day you will receive $$$n$$$ messages, the $$$i$$$-th message will be received from the friend with ID $$$id_i$$$ ($$$1 \le id_i \le 10^9$$$).If you receive a message from $$$id_i$$$ in the conversation which is currently displayed on the smartphone then nothing happens: the conversations of the screen do not change and do not change their order, you read the message and continue waiting for new messages.Otherwise (i.e. if there is no conversation with $$$id_i$$$ on the screen):  Firstly, if the number of conversations displayed on the screen is $$$k$$$, the last conversation (which has the position $$$k$$$) is removed from the screen.  Now the number of conversations on the screen is guaranteed to be less than $$$k$$$ and the conversation with the friend $$$id_i$$$ is not displayed on the screen.  The conversation with the friend $$$id_i$$$ appears on the first (the topmost) position on the screen and all the other displayed conversations are shifted one position down. Your task is to find the list of conversations (in the order they are displayed on the screen) after processing all $$$n$$$ messages.

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

    let mut result = Vec::new();

    let parts: Vec<u32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .split_whitespace()
        .filter(|s| !s.is_empty())
        .map(|s| s.parse::<u32>().unwrap())
        .collect();

    let screen_size = parts[1];

    let message_conv_ids: Vec<u32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .split_whitespace()
        .filter(|s| !s.is_empty())
        .map(|s| s.parse::<u32>().unwrap())
        .collect();

    for mc_id in message_conv_ids {
        if !result.is_empty() && result[0] == mc_id {
            continue;
        }

        if result.contains(&mc_id) {
            continue;
        }
        result.insert(0, mc_id);

        if result.len() > screen_size as usize {
            result.pop();
        }
    }

    println!("{}", result.len());
    for val in result {
        print!("{} ", val);
    }
    println!();
}


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s_1 s_2 \ldots s_n$$$. It is necessary to make this string non-decreasing in the least number of operations. In other words, each character should be not less than the previous. In one operation, you can do the following: Select an arbitrary index $$$1 \leq i \leq n$$$ in the string; For all $$$j \geq i$$$, change the value in the $$$j$$$-th position to the opposite, that is, if $$$s_j = 1$$$, then make $$$s_j = 0$$$, and vice versa.What is the minimum number of operations needed to make the string non-decreasing?

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

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

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

        let mut ans = 0;

        if s[0] == '1' {
            ans += 1;
        }

        for i in 1..n {
            if s[i] != s[i - 1] {
                ans += 1;
            }
        }

        ans -= 1;

        if ans < 0 {
            ans = 0;
        }

        println!("{ans:?}");
    }
}


Score : <var>100</var> points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a <var>4</var>-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code <var>S</var>. If <var>S</var> is hard to enter, print Bad; otherwise, print Good.

Constraints

<var>S</var> is a <var>4</var>-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so <var>3776</var> is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so <var>8080</var> is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad

int solution() {
  char str[5];
  scanf("%s", str);
  if (str[0] != str[1] && str[1] != str[2] && str[2] != str[3]) {
    printf("Good\n");
  } else {
    printf("Bad\n");
  }
  return 0;
}

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

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

    let vecs: Vec<char> = s.chars().collect();

    let mut isNotInputtable: bool = false;

    for i in 0..(vecs.len() - 1) {
        if vecs[i] == vecs[i + 1] {
            isNotInputtable = true;
        }
    }

    if isNotInputtable {
        println!("Bad");
    } else {
        println!("Good");
    }
}


ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.

int solution()

{
  int i = 0;
  int count = 0;
  int n = 0;
  int c = 0;
  int t[111111];
  scanf("%d %d", &n, &c);

  for (i = 0; i < n; i++) {
    scanf("%d", &t[i]);
    if (i >= 1) {
      if (t[i] - t[i - 1] <= c) {
        count++;
      } else {
        count = 1;
      }
    }

    if (i == 0) {
      count++;
    }
  }

  printf("%d", count);
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let mut ints = s.split_whitespace().map(|x| x.parse::<usize>().unwrap());
    let n = ints.next().unwrap();
    let t = ints.next().unwrap();
    let mut r = String::new();
    std::io::stdin().read_line(&mut r).unwrap();
    let ints: Vec<usize> = r
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap())
        .collect();
    let mut count = 1;
    for i in (1..n).rev() {
        if ints[i] - ints[i - 1] > t {
            break;
        }
        count += 1;
    }
    println!("{}", count);
}


The King of Berland Polycarp LXXXIV has $$$n$$$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $$$n$$$ other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from $$$1$$$ to $$$n$$$ and the kingdoms from $$$1$$$ to $$$n$$$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $$$n$$$-th daughter.For example, let there be $$$4$$$ daughters and kingdoms, the lists daughters have are $$$[2, 3]$$$, $$$[1, 2]$$$, $$$[3, 4]$$$, $$$[3]$$$, respectively.  In that case daughter $$$1$$$ marries the prince of kingdom $$$2$$$, daughter $$$2$$$ marries the prince of kingdom $$$1$$$, daughter $$$3$$$ marries the prince of kingdom $$$3$$$, leaving daughter $$$4$$$ nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer $$$t$$$ independent test cases.

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

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

    long long int pos[n];
    long long int k[n];
    for (long long int i = 0; i < n; ++i) {
      pos[i] = -1;
      k[i] = -1;
    }
    long long int pr[n + 1];
    long long int alfa = -5;
    long long int beta = -5;
    for (long long int i = 0; i < n; ++i) {
      long long int r = 0;
      do {
        scanf("%lld", &pr[r]);
        ++r;
      } while (getchar() != '\n');

      for (long long int j = 1; j <= pr[0]; ++j) {
        if (pos[pr[j] - 1] == -1) {
          k[i] = pr[j];
          pos[pr[j] - 1] = 1;
          break;
        }
      }
    }
    for (long long int j = 0; j < n; ++j) {
      if (pos[j] == -1) {
        alfa = j + 1;
        break;
      }
    }

    for (long long int j = 0; j < n; ++j) {
      if (k[j] == -1) {
        beta = j + 1;
        break;
      }
    }

    if (alfa != -5 && beta != -5) {
      printf("IMPROVE\n");
      printf("%lld %lld\n", beta, alfa);
    } else {
      printf("OPTIMAL\n");
    }

    --t;
  } while (t != 0);
}

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

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

        let mut choices: Vec<Vec<usize>> = Vec::with_capacity(n);

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

            choices.push(
                line.split_whitespace()
                    .skip(1)
                    .map(|x| x.parse::<usize>().unwrap() - 1)
                    .collect(),
            );
        }

        let mut princesses = vec![false; n];
        let mut kingdoms = vec![false; n];

        for (i, p) in choices.iter().enumerate() {
            for &k in p {
                if !kingdoms[k] {
                    princesses[i] = true;
                    kingdoms[k] = true;

                    break;
                }
            }
        }

        let p = princesses.into_iter().position(|x| !x);
        let k = kingdoms.into_iter().position(|x| !x);

        if let Some(p) = p {
            if let Some(k) = k {
                println!("IMPROVE");
                println!("{} {}", p + 1, k + 1);
            } else {
                println!("OPTIMAL");
            }
        } else {
            println!("OPTIMAL");
        }
    }
}


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

int solution(void) {
  int t;
  scanf("%d", &t);
  for (; t > 0; t--) {
    int n;
    long long sum = 0;
    int x = 0;
    long long y = 0;
    int flag2 = 0;
    scanf("%d", &n);
    long long a[n];
    for (int i = 0; i < n; i++) {
      scanf("%lld", &a[i]);
      sum = sum + a[i];
    }
    if (sum == 0) {
      for (int i = n - 1; i > -1; i--) {
        if (a[i] != 0) {
          x = i;
          break;
        }
        x = i;
      }
      if (x == 0) {
        printf("YES\n");
      } else if (x == 1 && a[0] > 0) {
        printf("YES");
      } else if (a[x] >= 0) {
        printf("NO\n");
      } else if (a[0] > 0 && a[x] < 0) {
        y = a[x];
        x--;
        for (int i = x; i > 0; i--) {
          y = y + a[i];
          if (y >= 0) {
            flag2 = 1;
          }
        }
        if (flag2 == 1) {
          printf("NO\n");
        } else {
          printf("YES\n");
        }
      } else {
        printf("NO\n");
      }
    } else {
      printf("NO\n");
    }
  }
}

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();
    'cycle: for _ in 0..num_tests {
        let _n: i32 = lines.next().unwrap().parse().unwrap();
        let a: Vec<i64> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse().unwrap())
            .collect();
        if a.iter().sum::<i64>() != 0 {
            println!("No");
            continue;
        }
        let mut prefix_sum = 0i64;
        let mut observed_zero = false;
        for x in a {
            prefix_sum += x;
            if prefix_sum < 0 {
                println!("No");
                continue 'cycle;
            } else if prefix_sum == 0 {
                observed_zero = true;
            } else if observed_zero {
                println!("No");
                continue 'cycle;
            }
        }
        println!("Yes");
    }
}


Acacius is studying strings theory. Today he came with the following problem.You are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once?Each question mark should be replaced with exactly one lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc".Occurrence of a string $$$t$$$ of length $$$m$$$ in the string $$$s$$$ of length $$$n$$$ as a substring is a index $$$i$$$ ($$$1 \leq i \leq n - m + 1$$$) such that string $$$s[i..i+m-1]$$$ consisting of $$$m$$$ consecutive symbols of $$$s$$$ starting from $$$i$$$-th equals to string $$$t$$$. For example string "ababa" has two occurrences of a string "aba" as a substring with $$$i = 1$$$ and $$$i = 3$$$, but there are no occurrences of a string "aba" in the string "acba" as a substring.Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once.

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

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

        let abacaba = ['a', 'b', 'a', 'c', 'a', 'b', 'a'];
        let mut count = 0;
        for i in 0..(n - 6) {
            let mut ok = true;
            for j in 0..7 {
                if s[i + j] != abacaba[j] {
                    ok = false;
                    break;
                }
            }
            if ok {
                count += 1;
            }
        }
        if count == 0 {
            let mut ok = false;
            'outer: for i in 0..(n - 6) {
                for j in 0..7 {
                    if s[i + j] != '?' && s[i + j] != abacaba[j] {
                        continue 'outer;
                    }
                }
                if i >= 6 {
                    let mut ng = true;
                    for j in 0..6 {
                        if s[i + j - 6] != abacaba[j] {
                            ng = false;
                        }
                    }
                    if ng {
                        continue 'outer;
                    }
                }
                if i >= 4 {
                    let mut ng = true;
                    for j in 0..4 {
                        if s[i + j - 4] != abacaba[j] {
                            ng = false;
                        }
                    }
                    if ng {
                        continue 'outer;
                    }
                }
                if i + 10 < n {
                    let mut ng = true;
                    for j in 0..4 {
                        if s[i + j + 7] != abacaba[j + 3] {
                            ng = false;
                        }
                    }
                    if ng {
                        continue 'outer;
                    }
                }
                if i + 12 < n {
                    let mut ng = true;
                    for j in 0..6 {
                        if s[i + j + 7] != abacaba[j + 1] {
                            ng = false;
                        }
                    }
                    if ng {
                        continue 'outer;
                    }
                }
                for j in 0..7 {
                    s[i + j] = abacaba[j];
                }
                ok = true;
                break;
            }
            if ok {
                let ans: String = { s.iter().map(|&c| if c == '?' { 'd' } else { c }).collect() };
                println!("Yes\n{}", ans);
            } else {
                println!("No");
            }
        } else if count == 1 {
            let ans: String = { s.iter().map(|&c| if c == '?' { 'd' } else { c }).collect() };
            println!("Yes\n{}", ans);
        } else {
            println!("No");
        }
    }
}


Score : <var>100</var> points

Problem Statement

Let <var>N</var> be a positive odd number.

There are <var>N</var> coins, numbered <var>1, 2, \ldots, N</var>.
For each <var>i</var> (<var>1 \leq i \leq N</var>), when Coin <var>i</var> is tossed, it comes up heads with probability <var>p_i</var> and tails with probability <var>1 - p_i</var>.

Taro has tossed all the <var>N</var> coins.
Find the probability of having more heads than tails.

Constraints

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

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

<var>p_i</var> is a real number and has two decimal places.

<var>0 < p_i < 1</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>p_1</var> <var>p_2</var> <var>\ldots</var> <var>p_N</var>

Output

Print the probability of having more heads than tails.
The output is considered correct when the absolute error is not greater than <var>10^{-9}</var>.

Sample Input 1

3
0.30 0.60 0.80

Sample Output 1

0.612

The probability of each case where we have more heads than tails is as follows:

The probability of having <var>(Coin 1, Coin 2, Coin 3) = (Head, Head, Head)</var> is <var>0.3 × 0.6 × 0.8 = 0.144</var>;

The probability of having <var>(Coin 1, Coin 2, Coin 3) = (Tail, Head, Head)</var> is <var>0.7 × 0.6 × 0.8 = 0.336</var>;

The probability of having <var>(Coin 1, Coin 2, Coin 3) = (Head, Tail, Head)</var> is <var>0.3 × 0.4 × 0.8 = 0.096</var>;

The probability of having <var>(Coin 1, Coin 2, Coin 3) = (Head, Head, Tail)</var> is <var>0.3 × 0.6 × 0.2 = 0.036</var>.

Thus, the probability of having more heads than tails is <var>0.144 + 0.336 + 0.096 + 0.036 = 0.612</var>.

Sample Input 2

1
0.50

Sample Output 2

0.5

Outputs such as 0.500, 0.500000001 and 0.499999999 are also considered correct.

Sample Input 3

5
0.42 0.01 0.42 0.99 0.42

Sample Output 3

0.3821815872

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: Vec<f64> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();

    let mut dp: Vec<Vec<f64>> = vec![vec![0.0; n + 1]; n + 1];
    dp[0][0] = 1.0;
    for i in 0..n {
        for num in 0..i + 1 {
            dp[i + 1][num + 1] += dp[i][num] * a[i];
            dp[i + 1][num] += dp[i][num] * (1.0 - a[i]);
        }
    }

    let mut ans: f64 = 0.0;
    for omote in 0..n + 1 {
        if omote > (n - omote) {
            ans += dp[n][omote];
        }
    }
    println!("{:.10}", ans);
}