Burenka and Tonya are playing an old Buryat game with a chip on a board of $$$n \times m$$$ cells.At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any odd number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way).    Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.

int solution() {
  long long int t;
  long long int i;
  scanf("%lld", &t);
  int n[t];
  int m[t];
  for (i = 0; i < t; i++) {
    scanf("%d%d", &n[i], &m[i]);
    if ((n[i] % 2 == 0 && m[i] % 2 == 0) || (n[i] % 2 != 0 && m[i] % 2 != 0)) {
      printf("Tonya\n");
    } else {
      printf("Burenka\n");
    }
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut iterator = stdin.lock().lines();
    let line = iterator.next().unwrap().unwrap();
    let amount = line.parse::<i32>().unwrap();
    for _i in 0..amount {
        let line = iterator.next().unwrap().unwrap();
        let strings: Vec<&str> = line.split(" ").collect();
        let sum = strings.get(1).unwrap().parse::<i32>().unwrap()
            + strings.first().unwrap().parse::<i32>().unwrap();
        if sum % 2 == 0 {
            println!("Tonya");
        } else {
            println!("Burenka");
        }
    }
}


Heat Stroke

We have had record hot temperatures this summer. To avoid heat stroke, you decided to buy a quantity of drinking water at the nearby supermarket. Two types of bottled water, 1 and 0.5 liter, are on sale at respective prices there. You have a definite quantity in your mind, but are willing to buy a quantity larger than that if: no combination of these bottles meets the quantity, or, the total price becomes lower.

  Given the prices for each bottle of water and the total quantity needed, make a program to seek the lowest price to buy greater than or equal to the quantity required.

Input

The input is given in the following format.

$A$ $B$ $X$

  The first line provides the prices for a 1-liter bottle $A$ ($1\leq A \leq 1000$), 500-milliliter bottle $B$ ($1 \leq B \leq 1000$), and the total water quantity needed $X$ ($1 \leq X \leq 20000$). All these values are given as integers, and the quantity of water in milliliters.

Output

  Output the total price.

Sample Input 1

180 100 2400

Sample Output 1

460

Sample Input 2

200 90 2018

Sample Output 2

450

fn solution() {
    let stdin = stdin();
    let line = stdin.lock().lines().next().unwrap().unwrap();
    let mut iter = line.split_whitespace().map(|s| s.parse::<u32>().unwrap());

    let (a, b, x) = (
        iter.next().unwrap(),
        iter.next().unwrap(),
        iter.next().unwrap() as f64,
    );

    let amount = if a <= b {
        a * ((x / 1000.0).ceil() as u32)
    } else if a < b * 2 {
        let u = (x / 500.0).ceil() as u32;
        a * (u / 2) + b * (u % 2)
    } else {
        b * ((x / 500.0).ceil() as u32)
    };

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


Graph

There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation.

  An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, the adjacency list $Adj[u]$ contains all vertices $v$ such that there is an edge $(u, v) \in E$. That is, $Adj[u]$ consists of all vertices adjacent to $u$ in $G$.

  An adjacency-matrix representation consists of $|V| \times |V|$ matrix $A = a_{ij}$ such that $a_{ij} = 1$ if $(i, j) \in E$, $a_{ij} = 0$ otherwise.

  Write a program which reads a directed graph $G$ represented by the adjacency list, and prints its adjacency-matrix representation. $G$ consists of $n\; (=|V|)$ vertices identified by their IDs $1, 2,.., n$ respectively.

Input

  In the first line, an integer $n$ is given. In the next $n$ lines, an adjacency list $Adj[u]$ for vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

 $u$ is vertex ID and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.

Output

  As shown in the following sample output, print the adjacent-matrix representation of $G$. Put a single space character between $a_{ij}$.

Constraints

$1 \leq n \leq 100$

Sample Input

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

Sample Output

0 1 0 1
0 0 0 1
0 0 0 0
0 0 1 0

fn solution() {
    let stdin = io::stdin();
    let lock = stdin.lock();
    let mut lines = lock.lines();
    let n = lines.next().unwrap().unwrap().parse().unwrap();
    let mut a = vec![vec![0; n]; n];

    for line in lines {
        let parsed: Vec<usize> = line
            .unwrap()
            .split_whitespace()
            .map(|s| s.parse().unwrap())
            .collect();

        let i = parsed[0];
        let adj = parsed[2..].iter();

        for j in adj {
            a[i - 1][j - 1] = 1;
        }
    }

    for line in a {
        println!(
            "{}",
            line.iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        );
    }
}


You are given two integers $$$x$$$ and $$$y$$$. You want to choose two strictly positive (greater than zero) integers $$$a$$$ and $$$b$$$, and then apply the following operation to $$$x$$$ exactly $$$a$$$ times: replace $$$x$$$ with $$$b \cdot x$$$.You want to find two positive integers $$$a$$$ and $$$b$$$ such that $$$x$$$ becomes equal to $$$y$$$ after this process. If there are multiple possible pairs, you can choose any of them. If there is no such pair, report it.For example:   if $$$x = 3$$$ and $$$y = 75$$$, you may choose $$$a = 2$$$ and $$$b = 5$$$, so that $$$x$$$ becomes equal to $$$3 \cdot 5 \cdot 5 = 75$$$;  if $$$x = 100$$$ and $$$y = 100$$$, you may choose $$$a = 3$$$ and $$$b = 1$$$, so that $$$x$$$ becomes equal to $$$100 \cdot 1 \cdot 1 \cdot 1 = 100$$$;  if $$$x = 42$$$ and $$$y = 13$$$, there is no answer since you cannot decrease $$$x$$$ with the given operations.

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).ok();
    let mut output = String::new();
    let mut input = input.split_ascii_whitespace().flat_map(str::parse);
    let t = input.next().unwrap();
    for _ in 0..t {
        let x = input.next().unwrap();
        let y = input.next().unwrap();
        if y % x == 0 {
            writeln!(output, "1 {}", y / x).ok();
        } else {
            output.push_str("0 0\n");
        }
    }
    print!("{output}");
}


Score : <var>200</var> points

Problem Statement

Takahashi has <var>A</var> untasty cookies containing antidotes, <var>B</var> tasty cookies containing antidotes and <var>C</var> tasty cookies containing poison.

Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death.
As he wants to live, he cannot eat one in such a situation.
Eating a cookie containing antidotes while having a stomachache cures it, and there is no other way to cure stomachaches.

Find the maximum number of tasty cookies that Takahashi can eat.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum number of tasty cookies that Takahashi can eat.

Sample Input 1

3 1 4

Sample Output 1

5

We can eat all tasty cookies, in the following order:

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

A tasty cookie containing antidotes

A tasty cookie containing poison

An untasty cookie containing antidotes

A tasty cookie containing poison

Sample Input 2

5 2 9

Sample Output 2

10

Sample Input 3

8 8 1

Sample Output 3

9

int solution() {
  int A = 0;
  int B = 0;
  int C = 0;
  scanf("%d%d%d", &A, &B, &C);
  if (A + B >= C) {
    printf("%d", B + C);
  }
  if (A + B < C) {
    printf("%d", A + (2 * B) + 1);
  }
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let a = it.next().unwrap().parse::<i32>().unwrap();
    let b = it.next().unwrap().parse::<i32>().unwrap();
    let c = it.next().unwrap().parse::<i32>().unwrap();
    println!("{}", b + std::cmp::min(a + b + 1, c));
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> balls placed in a row.
AtCoDeer the deer is painting each of these in one of the <var>K</var> colors of his paint cans.
For aesthetic reasons, any two adjacent balls must be painted in different colors.

Find the number of the possible ways to paint the balls.

Constraints

<var>1≦N≦1000</var>

<var>2≦K≦1000</var>

The correct answer is at most <var>2^{31}-1</var>.

Input

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

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

Output

Print the number of the possible ways to paint the balls.

Sample Input 1

2 2

Sample Output 1

2

We will denote the colors by <var>0</var> and <var>1</var>. There are two possible ways: we can either paint the left ball in color <var>0</var> and the right ball in color <var>1</var>, or paint the left in color <var>1</var> and the right in color <var>0</var>.

Sample Input 2

1 10

Sample Output 2

10

Since there is only one ball, we can use any of the ten colors to paint it. Thus, the answer is ten.

int solution() {

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

  if (N == 1) {
    val = K;
  } else if (N == 2) {
    val = K * (K - 1);
  } else {
    val = K * pow(K - 1, N - 1);
  }

  printf("%d", val);

  return 0;
}

fn solution() {
    let (n, k): (u32, u32) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).ok();
        let nk: Vec<u32> = buf
            .split_whitespace()
            .map(|e| e.trim().parse().ok().unwrap())
            .collect();
        (nk[0], nk[1])
    };
    println!("{}", k * (k - 1).pow(n - 1));
}


You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$n$$$ is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are greater than or equal to $$$0$$$.  At least $$$\frac{n - 1}{2}$$$ of the adjacent differences $$$a_{i + 1} - a_i$$$ for $$$i = 1, 2, \dots, n - 1$$$ are less than or equal to $$$0$$$. Find any valid way to flip the signs. It can be shown that under the given constraints, there always exists at least one choice of signs to flip that satisfies the required condition. If there are several solutions, you can find any of them.

int solution() {
  int T;
  scanf("%d", &T);
  int n[T];
  int **b = (int **)calloc(T, sizeof(int *));
  for (int i = 0; i < T; i++) {
    scanf("%d", &n[i]);
    int a[n[i]];
    *(b + i) = (int *)calloc(n[i], sizeof(int));
    for (int j = 0; j < n[i]; j++) {
      scanf("%d", &a[j]);
      a[j] = abs(a[j]);
      if (j % 2) {
        a[j] = -a[j];
      }
    }
    for (int j = 0; j < n[i]; j++) {
      b[i][j] = a[j];
    }
  }
  for (int i = 0; i < T; i++) {
    for (int j = 0; j < n[i]; j++) {
      printf("%d ", b[i][j]);
    }
    printf("\n");
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let mut xs: Vec<i32> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        for i in 0..n {
            if (i % 2 == 0 && xs[i] < 0) || (i % 2 == 1 && xs[i] > 0) {
                xs[i] *= -1;
            }
        }
        for i in 0..n {
            print!("{} ", xs[i]);
        }
        println!();
    }
}


問題 1

　n 分間にわたり，
トンネルの入口と出口で，
1分間に通過する車の数を数えたデータがある．
そのデータは，
全部で n+2 行からなり，
各行には次の内容が書かれている．

 第1行目には，正整数 n が書かれており，
      調査時間が n 分間であったことを表している．

 第2行目には，正整数 m が書かれており，
      調査開始時におけるトンネル内の車の台数が m であったことを表している．

 第(2+i)行目（ i = 1, 2, ... , n ) には，
      調査開始後 (i-1) 分経過した時点から i 分経過するまでの1分間に，
      入口を通過した車の台数と出口を通過した車の台数が
      １つの空白で区切られて書かれている．

調査開始後 j 分経過した時点 ( j=0, 1, 2, ... , n )
におけるトンネル内の車の台数を Sj とする．
Sj の最大値を出力しなさい．
また，
トンネル内の車の台数が負になることは考えられないので，
Sj が一度でも負になった場合は，
「エラー」の意味で 0 を出力しなさい．
ただし，
n は 10000 以下で，
トンネルの入口および出口を1分間に通過する車の台数は 100 以下である．

　出力ファイルにおいては，
出力の最後の行にも改行コードを入れること．

入出力例

入力例１

3
2
2 3
2 3
4 1

出力例１

3

入力例２

3
2
2 3
2 4
4 1

出力例２

0

入力例３

3
2
2 3
2 3
1 0

出力例３

2

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

int solution() {
  int n;
  int m;
  int i;
  scanf("%d%d", &n, &m);
  int MAX = m;
  int a[2][n];
  for (i = 0; i < n; i++) {
    scanf("%d%d", &a[0][i], &a[1][i]);
  }
  for (i = 0; i < n; i++) {
    m = m + a[0][i] - a[1][i];
    if (m > MAX) {
      MAX = m;
    }
    if (m < 0) {
      MAX = 0;
      break;
    }
  }
  printf("%d\n", MAX);
  return 0;
}

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

    let n = lines.next().unwrap().parse().unwrap();
    let mut m = lines.next().unwrap().parse().unwrap();

    let mut max = m;

    for line in lines.take(n) {
        let mut iter = line.split(' ').map(|s| s.parse().unwrap());
        let (i, o) = (iter.next().unwrap(), iter.next().unwrap());

        let (s, err) = usize::overflowing_sub(m + i, o);
        if err {
            max = 0;
            break;
        }
        m = s;
        if max < s {
            max = s;
        }
    }

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


When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a $$$2 \times n$$$ grid where each row is a permutation of the numbers $$$1,2,3,\ldots,n$$$.The goal of Little Alawn's puzzle is to make sure no numbers on the same column or row are the same (we'll call this state of the puzzle as solved), and to achieve this he is able to swap the numbers in any column. However, after solving the puzzle many times, Little Alawn got bored and began wondering about the number of possible solved configurations of the puzzle he could achieve from an initial solved configuration only by swapping numbers in a column.Unfortunately, Little Alawn got stuck while trying to solve this harder problem, so he was wondering if you could help him with it. Find the answer modulo $$$10^9+7$$$.

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

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

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

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

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

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

        let p = 1_000_000_007;

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

        let s = lines.next().unwrap();
        let it = s
            .split_whitespace()
            .map(|s| s.parse::<usize>().unwrap())
            .map(|x| (x, 0, false));
        a.extend(it);

        let s = lines.next().unwrap();
        let it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());
        for (x, y) in it.zip(a.iter_mut()) {
            y.1 = x;
        }

        a.sort();

        let mut c = 0u64;

        for i in 0..n {
            if a[i].2 {
                continue;
            }
            c += 1;
            let mut j = a[i].1 - 1;
            while !a[j].2 {
                a[j].2 = true;
                j = a[j].1 - 1;
            }
        }

        let ans = {
            let mut r = 1;
            let mut x = 2u64;
            while c > 0 {
                if c % 2 == 1 {
                    r = (r * x) % p;
                }
                c /= 2;
                x = (x * x) % p;
            }
            r
        };
        writeln!(&mut output, "{}", ans).unwrap();
    }
}


You want to perform the combo on your opponent in one popular fighting game. The combo is the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in $$$s$$$. I.e. if $$$s=$$$"abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend $$$m$$$ wrong tries to perform the combo and during the $$$i$$$-th try you will make a mistake right after $$$p_i$$$-th button ($$$1 \le p_i < n$$$) (i.e. you will press first $$$p_i$$$ buttons right and start performing the combo from the beginning). It is guaranteed that during the $$$m+1$$$-th try you press all buttons right and finally perform the combo.I.e. if $$$s=$$$"abca", $$$m=2$$$ and $$$p = [1, 3]$$$ then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int m;
    scanf("%d %d", &n, &m);
    char s[n + 1];
    scanf("%s", s);
    int p[m];
    for (int i = 0; i < m; i++) {
      scanf("%d", &p[i]);
      p[i]--;
    }
    int counter[26];
    int ctr[n];
    for (int i = 0; i < 26; i++) {
      counter[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      ctr[i] = 0;
    }
    for (int i = 0; i < m; i++) {
      ctr[p[i]]++;
    }
    for (int i = 0; s[i] != '\0'; i++) {
      counter[s[i] - 'a']++;
    }
    int c = 0;
    for (int i = n - 1; i >= 0; i--) {
      c += ctr[i];
      counter[s[i] - 'a'] += c;
    }
    for (int i = 0; i < 26; i++) {
      printf("%d ", counter[i]);
    }
    printf("\n");
  }
}

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

    let arr = buffer.split_whitespace().collect::<Vec<_>>();

    let mut it = arr.iter();
    let t = it.next().unwrap().parse::<usize>().unwrap();
    for _ in 0..t {
        let n = it.next().unwrap().parse::<usize>().unwrap();
        let m = it.next().unwrap().parse::<usize>().unwrap();
        let s = *it.next().unwrap();
        let ps = (0..m)
            .map(|_| it.next().unwrap().parse::<usize>().unwrap() - 1)
            .collect::<Vec<_>>();

        let mut count = vec![[0usize; 26]; n];
        let ss = s
            .chars()
            .map(|x| x as usize - 'a' as usize)
            .collect::<Vec<_>>();
        for (idx, &v) in ss.iter().enumerate() {
            count[idx][v] += 1;
        }

        for idx in 1..n {
            for v in 0..26 {
                count[idx][v] += count[idx - 1][v]
            }
        }

        let mut sum = [0; 26];
        for &i in ps.iter() {
            for v in 0..26 {
                sum[v] += count[i][v];
            }
        }
        for &i in ss.iter() {
            sum[i] += 1;
        }
        for &i in sum.iter() {
            print!("{} ", i);
        }
        println!();
    }
}


Score : <var>400</var> points

Problem Statement

Joisino is planning to record <var>N</var> TV programs with recorders.

The TV can receive <var>C</var> channels numbered <var>1</var> through <var>C</var>.

The <var>i</var>-th program that she wants to record will be broadcast from time <var>s_i</var> to time <var>t_i</var> (including time <var>s_i</var> but not <var>t_i</var>) on Channel <var>c_i</var>.

Here, there will never be more than one program that are broadcast on the same channel at the same time.

When the recorder is recording a channel from time <var>S</var> to time <var>T</var> (including time <var>S</var> but not <var>T</var>), it cannot record other channels from time <var>S-0.5</var> to time <var>T</var> (including time <var>S-0.5</var> but not <var>T</var>).

Find the minimum number of recorders required to record the channels so that all the <var>N</var> programs are completely recorded.

Constraints

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

<var>1≤C≤30</var>

<var>1≤s_i<t_i≤10^5</var>

<var>1≤c_i≤C</var>

If <var>c_i=c_j</var> and <var>i≠j</var>, either <var>t_i≤s_j</var> or <var>s_i≥t_j</var>.

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>C</var>
<var>s_1</var> <var>t_1</var> <var>c_1</var>
<var>:</var>
<var>s_N</var> <var>t_N</var> <var>c_N</var>

Output

When the minimum required number of recorders is <var>x</var>, print the value of <var>x</var>.

Sample Input 1

3 2
1 7 2
7 8 1
8 12 1

Sample Output 1

2

Two recorders can record all the programs, for example, as follows:

With the first recorder, record Channel <var>2</var> from time <var>1</var> to time <var>7</var>. The first program will be recorded. Note that this recorder will be unable to record other channels from time <var>0.5</var> to time <var>7</var>.

With the second recorder, record Channel <var>1</var> from time <var>7</var> to time <var>12</var>. The second and third programs will be recorded. Note that this recorder will be unable to record other channels from time <var>6.5</var> to time <var>12</var>.

Sample Input 2

3 4
1 3 2
3 4 4
1 4 3

Sample Output 2

3

There may be a channel where there is no program to record.

Sample Input 3

9 4
56 60 4
33 37 2
89 90 3
32 43 1
67 68 3
49 51 3
31 32 3
70 71 1
11 12 3

Sample Output 3

2

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 c: usize = itr.next().unwrap().parse().unwrap();

    let mut event = Vec::new();
    for _ in 0..n {
        let s: usize = itr.next().unwrap().parse().unwrap();
        let t: usize = itr.next().unwrap().parse().unwrap();
        let a: usize = itr.next().unwrap().parse().unwrap();
        event.push((s, 0, a));
        event.push((t, 1, a));
    }
    event.sort();

    let mut ans = 0;
    let mut channel = vec![0; c + 1];
    for &x in event.iter() {
        let typ = x.1;
        let chn = x.2;
        if typ == 0 {
            channel[chn] += 1;
        } else {
            channel[chn] -= 1;
        }

        ans = max(
            ans,
            (1..c + 1).fold(0, |acc, x| if channel[x] > 0 { acc + 1 } else { acc }),
        );
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

Joisino wants to evaluate the formula "<var>A</var> <var>op</var> <var>B</var>".
Here, <var>A</var> and <var>B</var> are integers, and the binary operator <var>op</var> is either + or -.
Your task is to evaluate the formula instead of her.

Constraints

<var>1≦A,B≦10^9</var>

<var>op</var> is either + or -.

Input

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

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

Output

Evaluate the formula and print the result.

Sample Input 1

1 + 2

Sample Output 1

3

Since <var>1 + 2 = 3</var>, the output should be <var>3</var>.

Sample Input 2

5 - 7

Sample Output 2

-2

int solution() {
  int *a = malloc(sizeof(int));
  int *b = malloc(sizeof(int));
  char *op = malloc(sizeof(char));
  scanf("%d", a);
  scanf(" %c[^"
        "]",
        op);
  scanf("%d", b);
  if (*op == '+') {
    printf("%d\n", *a + *b);
  }
  if (*op == '-') {
    printf("%d\n", *a - *b);
  }
  free(a);
  free(b);
  free(op);
}

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

    let inputs: Vec<&str> = input_line.split_whitespace().collect();

    let a: i64 = inputs[0].parse::<i64>().unwrap();
    let b: i64 = inputs[2].parse::<i64>().unwrap();
    let operand = inputs[1];

    if operand == "+" {
        print!("{}", a + b);
    } else if operand == "-" {
        print!("{}", a - b);
    }
}


Santa has to send presents to the kids. He has a large stack of $$$n$$$ presents, numbered from $$$1$$$ to $$$n$$$; the topmost present has number $$$a_1$$$, the next present is $$$a_2$$$, and so on; the bottom present has number $$$a_n$$$. All numbers are distinct.Santa has a list of $$$m$$$ distinct presents he has to send: $$$b_1$$$, $$$b_2$$$, ..., $$$b_m$$$. He will send them in the order they appear in the list.To send a present, Santa has to find it in the stack by removing all presents above it, taking this present and returning all removed presents on top of the stack. So, if there are $$$k$$$ presents above the present Santa wants to send, it takes him $$$2k + 1$$$ seconds to do it. Fortunately, Santa can speed the whole process up — when he returns the presents to the stack, he may reorder them as he wishes (only those which were above the present he wanted to take; the presents below cannot be affected in any way).What is the minimum time required to send all of the presents, provided that Santa knows the whole list of presents he has to send and reorders the presents optimally? Santa cannot change the order of presents or interact with the stack of presents in any other way.Your program has to answer $$$t$$$ different test cases.

int solution() {
  int t;
  int n;
  int m;
  scanf("%d", &t);
  while (t--) {
    scanf("%d %d", &n, &m);
    int a[n];
    int b[m];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    for (int i = 0; i < m; i++) {
      scanf("%d", &b[i]);
    }
    int c[n + 1];
    for (int i = 0; i < n; i++) {
      c[a[i]] = i;
    }
    long long int sum = 0;
    int count = 0;
    int max = c[b[0]];
    sum = c[b[0]] * 2 + 1;

    for (int i = 1; i < m; i++) {
      if (c[b[i]] > max) {
        max = c[b[i]];
        count++;
        sum += (c[b[i]] - count) * 2 + 1;
      } else {
        sum += 1;
        count++;
      }
    }
    printf("%lld\n", sum);
  }
  return 0;
}

fn solution() {
    ioset! { inp, buf }
    input! { inp, t: usize, }
    for _ in 0..t {
        input! { inp, n: usize, m: usize, a: [usize; n], b: [usize; m], }
        let mut MAX = 0i64;
        let mut idx = vec![0i64; n];
        for i in 0..n {
            idx[a[i] - 1] = i as i64;
        }
        let mut ans = 0i64;
        for i in 0..m {
            if idx[b[i] - 1] <= MAX {
                ans += 1;
            } else {
                MAX = idx[b[i] - 1];
                ans += (idx[b[i] - 1] - i as i64) * 2 + 1;
            }
        }
        output! { buf, "{}\n", ans }
    }
}


Score : <var>300</var> points

Problem Statement

You are given two integer sequences of length <var>N</var>: <var>a_1,a_2,..,a_N</var> and <var>b_1,b_2,..,b_N</var>.
Determine if we can repeat the following operation zero or more times so that the sequences <var>a</var> and <var>b</var> become equal.

Operation: Choose two integers <var>i</var> and <var>j</var> (possibly the same) between <var>1</var> and <var>N</var> (inclusive), then perform the following two actions simultaneously:

Add <var>2</var> to <var>a_i</var>.

Add <var>1</var> to <var>b_j</var>.

Constraints

<var>1 ≤ N ≤ 10</var> <var>000</var>

<var>0 ≤ a_i,b_i ≤ 10^9</var> (<var>1 ≤ i ≤ N</var>)

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> <var>..</var> <var>a_N</var>
<var>b_1</var> <var>b_2</var> <var>..</var> <var>b_N</var>

Output

If we can repeat the operation zero or more times so that the sequences <var>a</var> and <var>b</var> become equal, print Yes; otherwise, print No.

Sample Input 1

3
1 2 3
5 2 2

Sample Output 1

Yes

For example, we can perform three operations as follows to do our job:

First operation: <var>i=1</var> and <var>j=2</var>. Now we have <var>a = \{3,2,3\}</var>, <var>b = \{5,3,2\}</var>.

Second operation: <var>i=1</var> and <var>j=2</var>. Now we have <var>a = \{5,2,3\}</var>, <var>b = \{5,4,2\}</var>.

Third operation: <var>i=2</var> and <var>j=3</var>. Now we have <var>a = \{5,4,3\}</var>, <var>b = \{5,4,3\}</var>.

Sample Input 2

5
3 1 4 1 5
2 7 1 8 2

Sample Output 2

No

Sample Input 3

5
2 7 1 8 2
3 1 4 1 5

Sample Output 3

No

int solution() {
  long long N;
  scanf("%lld", &N);
  long long a[N];
  long long b[N];
  long long a_sum = 0;
  long long b_sum = 0;
  long long ap = 0;
  long long bp = 0;
  for (long long i = 0; i < N; i++) {
    scanf("%lld", &a[i]);
    a_sum += a[i];
  }
  for (long long i = 0; i < N; i++) {
    scanf("%lld", &b[i]);
    b_sum += b[i];
  }
  long long dif = b_sum - a_sum;
  for (long long i = 0; i < N; i++) {
    if (a[i] >= b[i]) {
      bp += a[i] - b[i];
    } else {
      ap += (b[i] - a[i] + 1) / 2;
    }
  }
  if (ap <= dif && bp <= dif) {
    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 n: usize = itr.next().unwrap().parse().unwrap();
    let a: Vec<i64> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();
    let b: Vec<i64> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();

    let mut da = 0i64;
    let mut db = 0i64;
    for i in 0..n {
        if a[i] > b[i] {
            db += a[i] - b[i];
        }
        if a[i] < b[i] {
            da += (b[i] - a[i]) / 2;
        }
    }
    if db <= da {
        println!("Yes");
    } else {
        println!("No");
    }
}


Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed.    Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally:   if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$);  if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots:   1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 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 grid: Vec<Vec<char>> = (0..n)
            .map(|_| itr.next().unwrap().chars().collect())
            .collect();

        let mut ok = true;
        for i in 0..n - 1 {
            for j in 0..n - 1 {
                if grid[i][j] == '1' && grid[i][j + 1] == '0' && grid[i + 1][j] == '0' {
                    ok = false;
                    break;
                }
            }
            if !ok {
                break;
            }
        }
        writeln!(out, "{}", if ok { "YES" } else { "NO" }).ok();
    }
    stdout().write_all(&out).unwrap();
}


Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.Let's call a rooted tree a spruce if its every non-leaf vertex has at least 3 leaf children. You are given a rooted tree, check whether it's a spruce.The definition of a rooted tree can be found here.

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

    let n = get!(usize);

    let mut tree = vec![vec![]; n + 2];

    for i in 0..n - 1 {
        let v = i + 2;
        let p = get!(usize);
        tree[p].push(v);
    }

    for children in &tree[1..] {
        if children.is_empty() {
            continue;
        }
        let mut leaf = 0;
        for &child in children {
            if tree[child].is_empty() {
                leaf += 1;
            }
        }
        if leaf < 3 {
            println!("No");
            return;
        }
    }
    println!("Yes");
}


Score : <var>100</var> points

Problem Statement

You are given a string <var>S</var> as input. This represents a valid date in the year <var>2019</var> in the yyyy/mm/dd format. (For example, April <var>30</var>, <var>2019</var> is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by <var>S</var> is not later than April <var>30</var>, <var>2019</var>, and prints TBD otherwise.

Constraints

<var>S</var> is a string that represents a valid date in the year <var>2019</var> in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print Heisei if the date represented by <var>S</var> is not later than April <var>30</var>, <var>2019</var>, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let s: Vec<isize> = s.trim().split('/').flat_map(str::parse).collect();
    let y = s[0];
    let m = s[1];
    let _d = s[2];
    if y > 2019 || (y == 2019 && m >= 5) {
        println!("TBD");
    } else {
        println!("Heisei");
    }
}


Score : <var>100</var> points

Problem Statement

Dolphin loves programming contests. Today, he will take part in a contest in AtCoder.

In this country, 24-hour clock is used. For example, <var>9:00</var> p.m. is referred to as "<var>21</var> o'clock".

The current time is <var>A</var> o'clock, and a contest will begin in exactly <var>B</var> hours.
When will the contest begin? Answer in 24-hour time.

Constraints

<var>0 \leq A,B \leq 23</var>

<var>A</var> and <var>B</var> are integers.

Input

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

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

Output

Print the hour of the starting time of the contest in 24-hour time.

Sample Input 1

9 12

Sample Output 1

21

In this input, the current time is <var>9</var> o'clock, and <var>12</var> hours later it will be <var>21</var> o'clock in 24-hour time.

Sample Input 2

19 0

Sample Output 2

19

The contest has just started.

Sample Input 3

23 2

Sample Output 3

1

The contest will begin at <var>1</var> o'clock the next day.

int solution() {

  int sum = 0;
  int a = 0;
  int b = 0;
  scanf("%d %d", &a, &b);
  sum = a + b;
  if (sum > 23) {
    printf("%d", sum - 24);
  } else {
    printf("%d", sum);
  }

  return 0;
}

fn solution() {
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .expect("faild to read line");
    let mut sum: u64 = 0;
    for elem in line.split_whitespace() {
        sum += elem.trim().parse::<u64>().unwrap();
    }
    println!("{}", sum % 24);
}


Score: <var>200</var> points

Problem Statement

M-kun has the following three cards:

A red card with the integer <var>A</var>.

A green card with the integer <var>B</var>.

A blue card with the integer <var>C</var>.

He is a genius magician who can do the following operation at most <var>K</var> times:

Choose one of the three cards and multiply the written integer by <var>2</var>.

His magic is successful if both of the following conditions are satisfied after the operations:

The integer on the green card is strictly greater than the integer on the red card.

The integer on the blue card is strictly greater than the integer on the green card.

Determine whether the magic can be successful.

Constraints

<var>1 \leq A, B, C \leq 7</var>

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If the magic can be successful, print Yes; otherwise, print No.

Sample Input 1

7 2 5
3

Sample Output 1

Yes

The magic will be successful if, for example, he does the following operations:

First, choose the blue card. The integers on the red, green, and blue cards are now <var>7</var>, <var>2</var>, and <var>10</var>, respectively.

Second, choose the green card. The integers on the red, green, and blue cards are now <var>7</var>, <var>4</var>, and <var>10</var>, respectively.

Third, choose the green card. The integers on the red, green, and blue cards are now <var>7</var>, <var>8</var>, and <var>10</var>, respectively.

Sample Input 2

7 4 2
3

Sample Output 2

No

He has no way to succeed in the magic with at most three operations.

fn solution() {
    let (a, mut b, mut c): (usize, usize, usize) = {
        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 k: usize = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

    let mut count = 0;
    while a >= b {
        b *= 2;
        count += 1;
    }
    while b >= c {
        c *= 2;
        count += 1;
    }

    if count <= k {
        println!("Yes");
    } else {
        println!("No");
    }
}


Little C loves number «3» very much. He loves all things about it.Now he has a positive integer $$$n$$$. He wants to split $$$n$$$ into $$$3$$$ positive integers $$$a,b,c$$$, such that $$$a+b+c=n$$$ and none of the $$$3$$$ integers is a multiple of $$$3$$$. Help him to find a solution.

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

    let arr: Vec<_> = buffer
        .split_whitespace()
        .map(|x| x.parse::<u32>().unwrap())
        .collect();
    let n = arr[0];
    let a = n / 3;
    let mut b = [a + n % 3, a, a];
    for i in 0..3 {
        if b[i] % 3 == 0 {
            if i < 2 {
                b[i] -= 1;
                b[i + 1] += 1;
            } else {
                b[2] += 1;
                b[0] -= 1;
            }
        }
    }
    println!("{} {} {}", b[0], b[1], b[2]);
}


Score : <var>100</var> points

Problem Statement

You are given two integers <var>a</var> and <var>b</var>.
Determine if <var>a+b=15</var> or <var>a\times b=15</var> or neither holds.

Note that <var>a+b=15</var> and <var>a\times b=15</var> do not hold at the same time.

Constraints

<var>1 \leq a,b \leq 15</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If <var>a+b=15</var>, print +;
if <var>a\times b=15</var>, print *;
if neither holds, print x.

Sample Input 1

4 11

Sample Output 1

+

<var>4+11=15</var>.

Sample Input 2

3 5

Sample Output 2

*

<var>3\times 5=15</var>.

Sample Input 3

1 1

Sample Output 3

x

<var>1+1=2</var> and <var>1\times 1=1</var>, neither of which is <var>15</var>.

int solution(void) {
  int a = 0;
  int b = 0;

  scanf("%d %d", &a, &b);

  if (a + b == 15) {
    printf("+\n");
  } else if (a * b == 15) {
    printf("*\n");
  } else {
    printf("x\n");
  }

  return 0;
}

fn solution() {
    let mut ab = String::new();
    std::io::stdin().read_line(&mut ab).ok();
    let mut it = ab.split_whitespace().map(|n| usize::from_str(n).unwrap());
    let (a, b) = (it.next().unwrap(), it.next().unwrap());
    if a + b == 15 {
        println!("+");
    } else if a * b == 15 {
        println!("*");
    } else {
        println!("x");
    }
}


Ring

  Write a program which finds a pattern $p$ in a ring shaped text $s$.

Input

  In the first line, the text $s$ is given.

  In the second line, the pattern $p$ is given.

Output

  If $p$ is in $s$, print Yes in a line, otherwise No.

Constraints

$1 \leq $ length of $p \leq $ length of $s \leq 100$

$s$ and $p$ consists of lower-case letters

Sample Input 1

vanceknowledgetoad
advance

Sample Output 1

Yes

Sample Input 2

vanceknowledgetoad
advanced

Sample Output 2

No

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

    let mut line = String::new();
    let _ = scan.read_line(&mut line);

    let mut line2 = String::new();
    let _ = scan.read_line(&mut line2);

    let s = [line.trim(), line.trim()].concat();

    if !s.contains(line2.trim()) {
        println!("No");
    } else {
        println!("Yes");
    }
}


The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps.

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

  while (testcase--) {
    long long x;
    long long n;
    scanf("%lld%lld", &x, &n);

    long long remainder = n % 4;
    long long cycle = (n / 4) + 1;
    if (x % 2 == 0) {
      switch (remainder) {
      case 0:
        x = x;
        break;
      case 1:
        x = x - n;
        break;
      case 2:
        x = x + 1;
        break;
      case 3:
        x = x + 4 * cycle;
        break;
      }
    } else {
      switch (remainder) {
      case 0:
        x = x;
        break;
      case 1:
        x = x + n;
        break;
      case 2:
        x = x - 1;
        break;
      case 3:
        x = x - 4 * cycle;
        break;
      }
    }

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

  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    for _ in 0..(line.trim().parse().unwrap()) {
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let nums: Vec<i64> = line.trim().split(" ").map(|x| x.parse().unwrap()).collect();
        let mut ans: i64 = nums[0];
        for i in nums[1] / 4 * 4 + 1..=nums[1] {
            if ans % 2 == 0 {
                ans -= i;
            } else {
                ans += i;
            }
        }
        println!("{}", ans);
    }
}


Score : <var>600</var> points

Problem Statement

We have a sequence of length <var>N</var> consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes <var>N-1</var> or smaller.

Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element by <var>N</var>, and increase each of the other elements by <var>1</var>.

It can be proved that the largest element in the sequence becomes <var>N-1</var> or smaller after a finite number of operations.

You are given an integer <var>K</var>. Find an integer sequence <var>a_i</var> such that the number of times we will perform the above operation is exactly <var>K</var>. It can be shown that there is always such a sequence under the constraints on input and output in this problem.

Constraints

<var>0 ≤ K ≤ 50 \times 10^{16}</var>

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print a solution in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> ... <var>a_N</var>

Here, <var>2 ≤ N ≤ 50</var> and <var>0 ≤ a_i ≤ 10^{16} + 1000</var> must hold.

Sample Input 1

0

Sample Output 1

4
3 3 3 3

Sample Input 2

1

Sample Output 2

3
1 0 3

Sample Input 3

2

Sample Output 3

2
2 2

The operation will be performed twice: [2, 2] -> [0, 3] -> [1, 1].

Sample Input 4

3

Sample Output 4

7
27 0 0 0 0 0 0

Sample Input 5

1234567894848

Sample Output 5

10
1000 193 256 777 0 1 1192 1234567891011 48 425

int solution() {
  long long n;
  long long a;
  long long i;
  scanf("%lld", &n);
  a = n / 50;
  printf("50\n");
  if (a == 0) {
    for (i = 0; i < 50; i++) {
      if (i) {
        printf(" ");
      }
      if (i < n) {
        printf("50");
      } else {
        printf("0");
      }
    }
  } else {
    for (i = 0; i < 50; i++) {
      if (i) {
        printf(" ");
      }
      if (i < n % 50) {
        printf("%lld", a + 50);
      } else {
        printf("%lld", a + 49 - (n % 50));
      }
    }
  }
  printf("\n");
  return 0;
}

fn solution() {
    input!(k: usize);
    let n = 50;
    let mut b = vec![k / n; n];
    for i in 0..(k % n) {
        b[i] += 1;
    }

    assert_eq!(b.iter().sum::<usize>(), k);
    let mut upper_a = vec![0; n];
    let mut lower_a = vec![0; n];
    for i in 0..n {
        lower_a[i] = ((n + 1) * b[i]).saturating_sub(k);
        upper_a[i] = (n + 1) * b[i] + (n - 1) - k;
    }
    println!("{}", n);
    for i in 0..n {
        if i > 0 {
            print!(" ");
        }
        print!("{}", upper_a[i]);
    }
    println!();
}


Score: <var>300</var> points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City <var>1, 2, 3, 4, 5, 6</var>)!

There are five means of transport in this empire:

Train: travels from City <var>1</var> to <var>2</var> in one minute. A train can occupy at most <var>A</var> people.

Bus: travels from City <var>2</var> to <var>3</var> in one minute. A bus can occupy at most <var>B</var> people.

Taxi: travels from City <var>3</var> to <var>4</var> in one minute. A taxi can occupy at most <var>C</var> people.

Airplane: travels from City <var>4</var> to <var>5</var> in one minute. An airplane can occupy at most <var>D</var> people.

Ship: travels from City <var>5</var> to <var>6</var> in one minute. A ship can occupy at most <var>E</var> people.

For each of them, one vehicle leaves the city at each integer time (time <var>0</var>, <var>1</var>, <var>2</var>, <var>...</var>).

There is a group of <var>N</var> people at City <var>1</var>, and they all want to go to City <var>6</var>.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

<var>1 \leq N, A, B, C, D, E \leq 10^{15}</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum time required for all of the people to reach City <var>6</var>, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are <var>N = 5</var> people at City <var>1</var>, as shown in the following image:

In the first minute, three people travels from City <var>1</var> to City <var>2</var> by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City <var>1</var> to City <var>2</var> by train, and two of the three people who were already at City <var>2</var> travels to City <var>3</var> by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City <var>2</var> to City <var>3</var> by train, and another two people travels from City <var>3</var> to City <var>4</var> by taxi.

From then on, if they continue traveling without stopping until they reach City <var>6</var>, all of them can reach there in seven minutes.

There is no way for them to reach City <var>6</var> in <var>6</var> minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy <var>N = 10</var> people at a time.
Thus, if they continue traveling without stopping until they reach City <var>6</var>, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a <var>32</var>-bit integer type.

int solution() {
  long long int n;
  long long int vehicle[5];
  scanf("%lld %lld %lld %lld %lld %lld", &n, &vehicle[0], &vehicle[1],
        &vehicle[2], &vehicle[3], &vehicle[4]);
  long long int min = LLONG_MAX;
  for (int i = 0; i < 5; i++) {
    if (min > vehicle[i]) {
      min = vehicle[i];
    }
  }
  printf("%lld", ((n + (min - 1)) / min) + 4);

  return 0;
}

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

    a.sort();
    println!("{}", 5 + n.div_ceil(a[0]) - 1);
}


You are given three positive (i.e. strictly greater than zero) integers $$$x$$$, $$$y$$$ and $$$z$$$.Your task is to find positive integers $$$a$$$, $$$b$$$ and $$$c$$$ such that $$$x = \max(a, b)$$$, $$$y = \max(a, c)$$$ and $$$z = \max(b, c)$$$, or determine that it is impossible to find such $$$a$$$, $$$b$$$ and $$$c$$$.You have to answer $$$t$$$ independent test cases. Print required $$$a$$$, $$$b$$$ and $$$c$$$ in any (arbitrary) order.

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut count: i16 = line.trim().parse().unwrap();
    while count > 0 {
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        let first: u32 = iter.next().unwrap().parse().unwrap();
        let second: u32 = iter.next().unwrap().parse().unwrap();
        let third: u32 = iter.next().unwrap().parse().unwrap();
        match if first < second {
            second == third
        } else if first > second {
            first == third
        } else {
            first >= third
        } {
            true => println!(
                "YES\n{} {} 1",
                first,
                if first == second { third } else { second }
            ),
            false => println!("NO"),
        }
        count -= 1;
    }
}


Mike and Joe are playing a game with some stones. Specifically, they have $$$n$$$ piles of stones of sizes $$$a_1, a_2, \ldots, a_n$$$. These piles are arranged in a circle.The game goes as follows. Players take turns removing some positive number of stones from a pile in clockwise order starting from pile $$$1$$$. Formally, if a player removed stones from pile $$$i$$$ on a turn, the other player removes stones from pile $$$((i\bmod n) + 1)$$$ on the next turn.If a player cannot remove any stones on their turn (because the pile is empty), they lose. Mike goes first.If Mike and Joe play optimally, who will win?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int a;
    scanf("%d", &a);
    int A[a];

    int ind = 0;
    for (int i = 0; i < a; i++) {
      scanf("%d", &A[i]);
    }
    int min = A[0];
    for (int i = 1; i < a; i++) {
      if (A[i] < min) {
        min = A[i];
        ind = i;
      }
    }
    ind++;
    if (a % 2 == 0) {
      if ((min * a + (ind - 1)) % 2 == 0) {
        printf("Joe\n");
      } else {
        printf("Mike\n");
      }
    } else {
      printf("Mike\n");
    }
  }
  return 0;
}

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

    let mut n: i32;
    let mut aux: i32;
    let mut odd: bool = true;
    let mut min: i32;
    let mut idx: i32;

    stdin.read_line(&mut buffer).expect("bruh");
    let t: i32 = buffer.trim().parse().unwrap();

    for _ in 0..t {
        buffer.clear();
        stdin.read_line(&mut buffer).expect("bruh");
        n = buffer.trim().parse().unwrap();
        min = i32::MAX;

        buffer.clear();
        stdin.read_line(&mut buffer).expect("bruh");
        buffer = buffer.trim().to_string();
        idx = 1;
        for num in buffer.split(' ') {
            aux = num.parse::<i32>().unwrap();
            if min > aux {
                min = aux;
                odd = idx % 2 != 0;
            }
            idx += 1;
        }

        if n % 2 == 0 && odd {
            println!("Joe");
        } else {
            println!("Mike");
        }
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi is practicing shiritori alone again today.

Shiritori is a game as follows:

In the first turn, a player announces any one word.

In the subsequent turns, a player announces a word that satisfies the following conditions:

That word is not announced before.

The first character of that word is the same as the last character of the last word announced.

In this game, he is practicing to announce as many words as possible in ten seconds.

You are given the number of words Takahashi announced, <var>N</var>, and the <var>i</var>-th word he announced, <var>W_i</var>, for each <var>i</var>. Determine if the rules of shiritori was observed, that is, every word announced by him satisfied the conditions.

Constraints

<var>N</var> is an integer satisfying <var>2 \leq N \leq 100</var>.

<var>W_i</var> is a string of length between <var>1</var> and <var>10</var> (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>W_1</var>
<var>W_2</var>
<var>:</var>
<var>W_N</var>

Output

If every word announced by Takahashi satisfied the conditions, print Yes; otherwise, print No.

Sample Input 1

4
hoge
english
hoge
enigma

Sample Output 1

No

As hoge is announced multiple times, the rules of shiritori was not observed.

Sample Input 2

9
basic
c
cpp
php
python
nadesico
ocaml
lua
assembly

Sample Output 2

Yes

Sample Input 3

8
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaa
aaaaaaa

Sample Output 3

No

Sample Input 4

3
abc
arc
agc

Sample Output 4

No

int solution() {
  int n = 0;
  scanf("%d\n", &n);
  char s[n][12];
  for (int i = 0; i < n; i++) {
    fgets(s[i], 12, stdin);
    int length = strlen(s[i]);
    s[i][length - 1] = '\0';
    if (i == 0) {
      continue;
    }
    if (s[i][0] != s[i - 1][strlen(s[i - 1]) - 1]) {
      printf("No\n");
      return 0;
    }
    for (int j = 0; j < i; j++) {
      if (!strcmp(s[i], s[j])) {
        printf("No\n");
        return 0;
      }
    }
  }
  printf("Yes\n");
  return 0;
}

fn solution() {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).unwrap();
    let n: usize = n.trim().parse().unwrap();
    let mut p = std::collections::HashSet::<String>::new();
    let mut h = Vec::<String>::new();
    let mut r = true;

    for _ in 0..n {
        let mut word = String::new();
        std::io::stdin().read_line(&mut word).unwrap();
        let word: String = word.trim().into();
        if r && p.contains(&word) {
            r = false;
        } else {
            p.insert(word.clone());
            h.push(word);
        }
    }

    println!(
        "{}",
        if r && h
            .iter()
            .zip(h.iter().skip(1))
            .all(|(a, b)| a.chars().last().unwrap() == b.chars().next().unwrap())
        {
            "Yes"
        } else {
            "No"
        }
    );
}


Polycarp has $$$n$$$ friends, the $$$i$$$-th of his friends has $$$a_i$$$ candies. Polycarp's friends do not like when they have different numbers of candies. In other words they want all $$$a_i$$$ to be the same. To solve this, Polycarp performs the following set of actions exactly once:   Polycarp chooses $$$k$$$ ($$$0 \le k \le n$$$) arbitrary friends (let's say he chooses friends with indices $$$i_1, i_2, \ldots, i_k$$$);  Polycarp distributes their $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies among all $$$n$$$ friends. During distribution for each of $$$a_{i_1} + a_{i_2} + \ldots + a_{i_k}$$$ candies he chooses new owner. That can be any of $$$n$$$ friends. Note, that any candy can be given to the person, who has owned that candy before the distribution process. Note that the number $$$k$$$ is not fixed in advance and can be arbitrary. Your task is to find the minimum value of $$$k$$$.For example, if $$$n=4$$$ and $$$a=[4, 5, 2, 5]$$$, then Polycarp could make the following distribution of the candies:   Polycarp chooses $$$k=2$$$ friends with indices $$$i=[2, 4]$$$ and distributes $$$a_2 + a_4 = 10$$$ candies to make $$$a=[4, 4, 4, 4]$$$ (two candies go to person $$$3$$$). Note that in this example Polycarp cannot choose $$$k=1$$$ friend so that he can redistribute candies so that in the end all $$$a_i$$$ are equal.For the data $$$n$$$ and $$$a$$$, determine the minimum value $$$k$$$. With this value $$$k$$$, Polycarp should be able to select $$$k$$$ friends and redistribute their candies so that everyone will end up with the same number of candies.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int sum = 0;
    int a[n];
    int c = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    for (int i = 0; i < n; i++) {
      sum += a[i];
    }
    if (sum % n == 0 && n != 1) {
      for (int i = 0; i < n; i++) {
        if (a[i] > sum / n) {
          c++;
        }
      }
      printf("%d\n", c);
    } else if (n == 1) {
      printf("0\n");
    } else {
      printf("-1\n");
    }
  }
}

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

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

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

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

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

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

        let a: Vec<_> = it.collect();
        let s = a.iter().cloned().sum::<usize>();
        if s % n != 0 {
            writeln!(&mut output, "-1").unwrap();
        } else {
            let ans = a.into_iter().filter(|&x| x * n > s).count();
            writeln!(&mut output, "{}", ans).unwrap();
        }
    }
}


Score : <var>700</var> points

Problem Statement

Nuske has a grid with <var>N</var> rows and <var>M</var> columns of squares. The rows are numbered <var>1</var> through <var>N</var> from top to bottom, and the columns are numbered <var>1</var> through <var>M</var> from left to right.
Each square in the grid is painted in either blue or white. If <var>S_{i,j}</var> is <var>1</var>, the square at the <var>i</var>-th row and <var>j</var>-th column is blue; if <var>S_{i,j}</var> is <var>0</var>, the square is white.
For every pair of two blue square <var>a</var> and <var>b</var>, there is at most one path that starts from <var>a</var>, repeatedly proceeds to an adjacent (side by side) blue square and finally reaches <var>b</var>, without traversing the same square more than once.

Phantom Thnook, Nuske's eternal rival, gives <var>Q</var> queries to Nuske. The <var>i</var>-th query consists of four integers <var>x_{i,1}</var>, <var>y_{i,1}</var>, <var>x_{i,2}</var> and <var>y_{i,2}</var> and asks him the following: when the rectangular region of the grid bounded by (and including) the <var>x_{i,1}</var>-th row, <var>x_{i,2}</var>-th row, <var>y_{i,1}</var>-th column and <var>y_{i,2}</var>-th column is cut out, how many connected components consisting of blue squares there are in the region?

Process all the queries.

Constraints

<var>1 ≤ N,M ≤ 2000</var>

<var>1 ≤ Q ≤ 200000</var>

<var>S_{i,j}</var> is either <var>0</var> or <var>1</var>.

<var>S_{i,j}</var> satisfies the condition explained in the statement.

<var>1 ≤ x_{i,1} ≤ x_{i,2} ≤ N(1 ≤ i ≤ Q)</var>

<var>1 ≤ y_{i,1} ≤ y_{i,2} ≤ M(1 ≤ i ≤ Q)</var>

Input

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

<var>N</var> <var>M</var> <var>Q</var>
<var>S_{1,1}</var>..<var>S_{1,M}</var>
:
<var>S_{N,1}</var>..<var>S_{N,M}</var>
<var>x_{1,1}</var> <var>y_{i,1}</var> <var>x_{i,2}</var> <var>y_{i,2}</var>
:
<var>x_{Q,1}</var> <var>y_{Q,1}</var> <var>x_{Q,2}</var> <var>y_{Q,2}</var>

Output

For each query, print the number of the connected components consisting of blue squares in the region.

Sample Input 1

3 4 4
1101
0110
1101
1 1 3 4
1 1 3 1
2 2 3 4
1 2 2 4

Sample Output 1

3
2
2
2

In the first query, the whole grid is specified. There are three components consisting of blue squares, and thus <var>3</var> should be printed.

In the second query, the region within the red frame is specified. There are two components consisting of blue squares, and thus <var>2</var> should be printed.
Note that squares that belong to the same component in the original grid may belong to different components.

Sample Input 2

5 5 6
11010
01110
10101
11101
01010
1 1 5 5
1 2 4 5
2 3 3 4
3 3 3 3
3 1 3 5
1 1 3 4

Sample Output 2

3
2
1
1
3
2

fn solution() {
    let mut stdin = io::stdin();
    let mut lines_str = String::new();
    let _ = stdin.read_to_string(&mut lines_str);
    let mut lines = lines_str.lines();
    let mut line0itr = lines.next().expect("").split_whitespace();
    let n: usize = line0itr.next().expect("").trim().parse().unwrap();
    let m: usize = line0itr.next().expect("").trim().parse().unwrap();
    let q: usize = line0itr.next().expect("").trim().parse().unwrap();

    let mut dots: Vec<i32> = vec![0; (2 * n - 1) * (2 * m - 1)];

    for i in 0..n {
        let mut linei1itr = lines.next().expect("").chars();
        for j in 0..m {
            let c = linei1itr.next().expect("");
            if c != '1' {
                continue;
            }
            dots[2 * i * (2 * m - 1) + 2 * j] = 1;
            if j != 0 && dots[2 * i * (2 * m - 1) + 2 * (j - 1)] == 1 {
                dots[2 * i * (2 * m - 1) + 2 * j - 1] = -1;
            }
            if i != 0 && dots[2 * (i - 1) * (2 * m - 1) + 2 * j] == 1 {
                dots[(2 * i - 1) * (2 * m - 1) + 2 * j] = -1;
            }
        }
    }

    for k in 0..(2 * n - 1) {
        for l in 0..(2 * m - 1) {
            if l == 0 {
                dots[k * (2 * m - 1) + l] = dots[k * (2 * m - 1) + l];
            } else {
                dots[k * (2 * m - 1) + l] += dots[k * (2 * m - 1) + l - 1];
            }
        }
    }

    for k in 0..(2 * n - 1) {
        for l in 0..(2 * m - 1) {
            if k == 0 {
                dots[k * (2 * m - 1) + l] = dots[k * (2 * m - 1) + l];
            } else {
                dots[k * (2 * m - 1) + l] += dots[(k - 1) * (2 * m - 1) + l];
            }
        }
    }

    for _i in 0..q {
        let mut linein1itr = lines.next().expect("").split_whitespace();
        let x1: usize = linein1itr.next().expect("").trim().parse().unwrap();
        let y1: usize = linein1itr.next().expect("").trim().parse().unwrap();
        let x2: usize = linein1itr.next().expect("").trim().parse().unwrap();
        let y2: usize = linein1itr.next().expect("").trim().parse().unwrap();
        let x2y2 = dots[(2 * (x2 - 1)) * (2 * m - 1) + (2 * (y2 - 1))];
        let x1y2 = if x1 == 1 {
            0
        } else {
            dots[(2 * (x1 - 1) - 1) * (2 * m - 1) + (2 * (y2 - 1))]
        };
        let x2y1 = if y1 == 1 {
            0
        } else {
            dots[(2 * (x2 - 1)) * (2 * m - 1) + (2 * (y1 - 1) - 1)]
        };
        let x1y1 = if x1 == 1 || y1 == 1 {
            0
        } else {
            dots[(2 * (x1 - 1) - 1) * (2 * m - 1) + (2 * (y1 - 1) - 1)]
        };
        println!("{}", x2y2 + x1y1 - x1y2 - x2y1);
    }
}


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

fn solution() {
    let reader = BufReader::new(io::stdin());
    let lines = reader.lines().map(|x| x.unwrap()).collect::<Vec<_>>();
    let w = lines.iter().map(|x| x.len()).max().unwrap();
    println!("{}", "*".repeat(w + 2));
    let mut x = 0;
    for line in &lines {
        let w = w - line.len();
        let mut l = w / 2;
        let mut r = w - l;
        if l * 2 != w {
            l += x;
            r -= x;
            x = 1 - x;
        }
        println!("*{}{}{}*", " ".repeat(l), line, " ".repeat(r));
    }
    println!("{}", "*".repeat(w + 2));
}


You are given an array $$$a$$$, consisting of $$$n$$$ integers.Each position $$$i$$$ ($$$1 \le i \le n$$$) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearrange the values on the locked positions. You are allowed to leave the values in the same order as they were.For example, let $$$a = [-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$, the underlined positions are locked. You can obtain the following arrays:   $$$[-1, 1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[-4, -1, \underline{3}, 2, \underline{-2}, 1, 1, \underline{0}]$$$;  $$$[1, -1, \underline{3}, 2, \underline{-2}, 1, -4, \underline{0}]$$$;  $$$[1, 2, \underline{3}, -1, \underline{-2}, -4, 1, \underline{0}]$$$;  and some others. Let $$$p$$$ be a sequence of prefix sums of the array $$$a$$$ after the rearrangement. So $$$p_1 = a_1$$$, $$$p_2 = a_1 + a_2$$$, $$$p_3 = a_1 + a_2 + a_3$$$, $$$\dots$$$, $$$p_n = a_1 + a_2 + \dots + a_n$$$.Let $$$k$$$ be the maximum $$$j$$$ ($$$1 \le j \le n$$$) such that $$$p_j < 0$$$. If there are no $$$j$$$ such that $$$p_j < 0$$$, then $$$k = 0$$$.Your goal is to rearrange the values in such a way that $$$k$$$ is minimum possible.Output the array $$$a$$$ after the rearrangement such that the value $$$k$$$ for it is minimum possible. If there are multiple answers then print any of them.

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    int array[100];
    int lock[100];
    int record[100] = {0};
    scanf("%d", &n);
    for (int j = 0; j < n; j++) {
      scanf("%d", &array[j]);
    }
    for (int j = 0; j < n; j++) {
      scanf("%d", &lock[j]);
    }
    for (int l = 0; l < n; l++) {
      if (lock[l]) {
        printf("%d ", array[l]);
      } else {
        int max = -100001;
        int maxIndex = 0;
        for (int k = 0; k < n; k++) {
          if (array[k] > max && lock[k] == 0 && record[k] == 0) {
            max = array[k];
            maxIndex = k;
          }
        }
        printf("%d ", array[maxIndex]);
        record[maxIndex] = 1;
      }
    }
    printf("\n");
  }
}

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("err");
    let t: i32 = buffer.trim().parse().expect("parse err");
    for _ in 0..t {
        io::stdin().read_line(&mut buffer).expect("err");

        buffer.clear();
        io::stdin().read_line(&mut buffer).expect("err");
        let v: Vec<i32> = buffer
            .split_whitespace()
            .map(|s| s.parse().expect("parse error"))
            .collect();

        buffer.clear();
        io::stdin().read_line(&mut buffer).expect("err");
        let l: Vec<i32> = buffer
            .split_whitespace()
            .map(|s| s.parse().expect("parse error"))
            .collect();

        let mut mvec: Vec<i32> = Vec::new();
        for i in 0..v.len() {
            if l[i] == 0 {
                mvec.push(v[i]);
            }
        }
        mvec.sort_by(|a, b| b.cmp(a));
        let mut j = 0;
        for i in 0..v.len() {
            if l[i] == 0 {
                print!("{} ", mvec[j]);
                j += 1;
            } else {
                print!("{} ", v[i]);
            }
        }
        println!();
    }
}


Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.

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

  int a[t];
  int b[t];
  int p[t];
  for (int i = 0; i < t; i++) {
    scanf("%d %d\n", &a[i], &b[i]);
  }
  for (int j = 0; j < t; j++) {
    p[j] = a[j] * b[j];
    printf("%d\n", p[j]);
  }

  return 0;
}

fn solution() {
    let mut n = String::new();
    io::stdin().read_line(&mut n).unwrap();
    let n = n.trim().parse().unwrap();
    for _i in 0..n {
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        let values = s
            .split_whitespace()
            .map(|x| x.parse::<i32>())
            .collect::<Result<Vec<i32>, _>>()
            .unwrap();
        let (n, m) = (values[0], values[1]);
        let result = (m - 1) * n + n - 1 + 1;
        println!("{}", result);
    }
}


Score : <var>200</var> points

Problem Statement

Niwango-kun is an employee of Dwango Co., Ltd.

One day, he is asked to generate a thumbnail from a video a user submitted.

To generate a thumbnail, he needs to select a frame of the video according to the following procedure:

Get an integer <var>N</var> and <var>N</var> integers <var>a_0, a_1, ..., a_{N-1}</var> as inputs. <var>N</var> denotes the number of the frames of the video, and each <var>a_i</var> denotes the representation of the <var>i</var>-th frame of the video.

Select <var>t</var>-th frame whose representation <var>a_t</var> is nearest to the average of all frame representations.

If there are multiple such frames, select the frame with the smallest index.

Find the index <var>t</var> of the frame he should select to generate a thumbnail.

Constraints

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

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

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_{0}</var> <var>a_{1}</var> <var>...</var> <var>a_{N-1}</var>

Output

Print the answer.

Sample Input 1

3
1 2 3

Sample Output 1

1

Since the average of frame representations is <var>2</var>, Niwango-kun needs to select the index <var>1</var>, whose representation is <var>2</var>, that is, the nearest value to the average.

Sample Input 2

4
2 5 2 5

Sample Output 2

0

The average of frame representations is <var>3.5</var>.

In this case, every frame has the same distance from its representation to the average.

Therefore, Niwango-kun should select index <var>0</var>, the smallest index among them.

int solution(void) {
  int n;
  int ans = 0;
  int sum = 0;
  scanf("%d", &n);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    sum += a[i];
  }
  for (int i = 0; i < n; i++) {
    if (abs((a[ans] * n) - sum) > abs((a[i] * n) - sum)) {
      ans = i;
    }
  }
  printf("%d\n", ans);
  return 0;
}

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: i16 = s.next().unwrap().parse().unwrap();
    let a: Vec<i16> = s.map(|a| a.parse().unwrap()).collect();
    let s: i16 = a.iter().sum();
    let ans = a
        .into_iter()
        .enumerate()
        .fold((0, std::i16::MAX), |r, (i, a)| {
            if (a * n - s).abs() < r.1 {
                (i, (a * n - s).abs())
            } else {
                r
            }
        })
        .0;
    println!("{}", ans);
}


void solution(int *a, int n) {
  int i;
  int j;
  int temp;

  for (i = n / 2; i >= 1; i--) {
    temp = a[i];
    j = 2 * i;

    while (j <= n) {
      if (j < n && a[j + 1] > a[j]) {
        j++;
      }

      if (temp > a[j]) {
        break;
      }

      a[j / 2] = a[j];
      j = 2 * j;
    }

    a[j / 2] = temp;
  }

  for (i = n; i >= 2; i--) {
    temp = a[i];
    a[i] = a[1];
    a[1] = temp;

    int parent = 1;
    temp = a[parent];
    j = 2 * parent;

    while (j <= i - 1) {
      if (j < i - 1 && a[j + 1] > a[j]) {
        j++;
      }

      if (temp > a[j]) {
        break;
      }

      a[j / 2] = a[j];
      j = 2 * j;
    }

    a[j / 2] = temp;
  }
}

fn solution<T: Ord>(arr: &mut [T], ascending: bool) {
    if arr.len() <= 1 {
        return;
    }

    let comparator: fn(&T, &T) -> Ordering = if ascending {
        |a, b| a.cmp(b)
    } else {
        |a, b| b.cmp(a)
    };

    let mut i = (arr.len() - 1) / 2;
    loop {
        let mut root = i;

        loop {
            let mut idx = root;
            let l = 2 * root + 1;
            let r = 2 * root + 2;

            if l < arr.len() && comparator(&arr[l], &arr[idx]) == Ordering::Greater {
                idx = l;
            }

            if r < arr.len() && comparator(&arr[r], &arr[idx]) == Ordering::Greater {
                idx = r;
            }

            if idx == root {
                break;
            }

            arr.swap(root, idx);
            root = idx;
        }

        if i == 0 {
            break;
        }

        i -= 1;
    }

    let mut end = arr.len() - 1;

    while end > 0 {
        arr.swap(0, end);

        let mut root = 0;

        loop {
            let mut idx = root;
            let l = 2 * root + 1;
            let r = 2 * root + 2;

            if l < end && comparator(&arr[l], &arr[idx]) == Ordering::Greater {
                idx = l;
            }

            if r < end && comparator(&arr[r], &arr[idx]) == Ordering::Greater {
                idx = r;
            }

            if idx == root {
                break;
            }

            arr.swap(root, idx);
            root = idx;
        }

        end -= 1;
    }
}


In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23. Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.

int solution() {
  int n;
  char ch[20];
  scanf("%d", &n);

  while (n--) {
    scanf("%s", ch);
    int m = strlen(ch);
    int C = 1;

    while (C < m && isdigit(ch[C])) {
      ++C;
    }

    if (C > 1 && C < m) {
      int col = 0;
      for (int i = C + 1; i < m; ++i) {
        col = col * 10 + (ch[i] - '0');
      }

      int pow = 26;
      while (col > pow) {
        col -= pow;
        pow *= 26;
      }

      col -= 1;
      while (pow != 1) {
        pow /= 26;
        printf("%c", (col / pow) + 'A');
        col %= pow;
      }

      ch[C] = 0;
      printf("%s\n", ch + 1);
    } else {
      int col = 0;
      int val = 0;
      int pow = 1;
      int i = 0;
      while (isalpha(ch[i])) {
        col += pow;
        pow *= 26;
        val = val * 26 + ch[i] - 'A';
        i += 1;
      }
      col += val;
      printf("R%sC%d\n", ch + i, col);
    }
  }
  return 0;
}

fn solution() {
    let mut count_string: String = String::new();
    io::stdin()
        .read_line(&mut count_string)
        .expect("Read error!");

    let mut count: u64 = count_string.trim().parse::<u64>().expect("Not an integer!");

    while count > 0 {
        count -= 1;

        let mut input_value = String::new();
        io::stdin()
            .read_line(&mut input_value)
            .expect("Read error!");

        let trimmed_input: &str = input_value.trim();

        let mut found_tokens = 0;
        let mut is_numeric = false;
        let mut tokens: Vec<String> = vec!["".to_string(); 4];

        for chr in trimmed_input.chars() {
            if is_numeric {
                if chr.is_ascii_digit() {
                    tokens[found_tokens].push(chr);
                } else {
                    is_numeric = false;
                    found_tokens += 1;
                    tokens[found_tokens].push(chr);
                }
            } else {
                if !chr.is_ascii_digit() {
                    tokens[found_tokens].push(chr);
                } else {
                    is_numeric = true;
                    found_tokens += 1;
                    tokens[found_tokens].push(chr);
                }
            }
        }

        found_tokens += 1;

        if found_tokens == 2 {
            let mut col: u64 = 0;
            let row: u64 = tokens[1].parse::<u64>().expect("Not an integer!");
            for chr in tokens[0].to_uppercase().chars() {
                col = col * 26 + (chr as u64) - ('A' as u64) + 1;
            }
            println!("R{}C{}", row, col);
        } else if found_tokens == 4 {
            let row: u64 = tokens[1].parse::<u64>().expect("Not an integer!");
            let mut col: u64 = tokens[3].parse::<u64>().expect("Not an integer!");
            let mut output_value = String::new();
            while col > 0 {
                let rem = (col % 26) as u8;
                if rem != 0 {
                    output_value.push((rem + b'A' - 1) as char);
                } else {
                    output_value.push('Z');
                }
                col = (col - 1) / 26;
            }
            println!("{}{}", output_value.chars().rev().collect::<String>(), row);
        } else {
            panic!("Invalid number of tokens");
        }
    }
}


You play your favourite game yet another time. You chose the character you didn't play before. It has $$$str$$$ points of strength and $$$int$$$ points of intelligence. Also, at start, the character has $$$exp$$$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $$$1$$$ or raise intelligence by $$$1$$$).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.

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

  while (T-- > 0) {
    long s = 0;
    long i = 0;
    long x = 0;
    scanf("%ld %ld %ld", &s, &i, &x);

    long y = (int)floor((double)(i - s + x) / 2);

    if (x - y < 0) {
      printf("0\n");
    } else if (y < 0) {
      printf("%ld\n", x + 1);
    } else {
      printf("%ld\n", x - y);
    }
  }

  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let t = input.trim().parse::<u16>().unwrap();
    for _ in 0..t {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let mut input_iter = input.split_whitespace();
        let mut s = input_iter.next().unwrap().parse::<u32>().unwrap();
        let i = input_iter.next().unwrap().parse::<u32>().unwrap();
        let mut e = input_iter.next().unwrap().parse::<u32>().unwrap();

        if s < i {
            if i - s >= e {
                println!("0");
                continue;
            }

            e -= i - s + 1;
            s = i + 1;
        }

        if e >= s - i {
            println!("{}", s - i - 1 + (e - (s - i - 1)) / 2 + 1)
        } else {
            println!("{}", e + 1);
        }
    }
}


Score: <var>200</var> points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes <var>A</var> minutes to serve.

ARC Curry: takes <var>B</var> minutes to serve.

AGC Pasta: takes <var>C</var> minutes to serve.

APC Ramen: takes <var>D</var> minutes to serve.

ATC Hanbagu (hamburger patty): takes <var>E</var> minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of <var>10</var> (time <var>0</var>, <var>10</var>, <var>20</var>, <var>...</var>).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time <var>0</var>. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time <var>0</var>.

Constraints

<var>A, B, C, D</var> and <var>E</var> are integers between <var>1</var> and <var>123</var> (inclusive).

Input

Input is given from Standard Input in the following format:

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

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time <var>0</var>, which will be delivered at time <var>29</var>.

Order ARC Curry at time <var>30</var>, which will be delivered at time <var>50</var>.

Order AGC Pasta at time <var>50</var>, which will be delivered at time <var>57</var>.

Order ATC Hanbagu at time <var>60</var>, which will be delivered at time <var>180</var>.

Order APC Ramen at time <var>180</var>, which will be delivered at time <var>215</var>.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time <var>0</var>, which will be delivered at time <var>119</var>.

Order ARC Curry at time <var>120</var>, which will be delivered at time <var>206</var>.

Order ATC Hanbagu at time <var>210</var>, which will be delivered at time <var>267</var>.

Order APC Ramen at time <var>270</var>, which will be delivered at time <var>378</var>.

Order ABC Don at time <var>380</var>, which will be delivered at time <var>481</var>.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.

int solution(void) {
  int time[5];

  scanf("%d\n", &time[0]);
  scanf("%d\n", &time[1]);
  scanf("%d\n", &time[2]);
  scanf("%d\n", &time[3]);
  scanf("%d", &time[4]);

  int min = 10;
  int total = 0;
  for (int i = 0; i < 5; i++) {
    int remainder = time[i] % 10;
    if (remainder != 0 && remainder < min) {
      min = remainder;
    }
    total += (time[i] + 9) / 10 * 10;
  };

  total += min - 10;

  printf("%d", total);
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut iter = s.split_whitespace();
    let mut tm = Vec::new();
    for _ in 0..5 {
        tm.push(iter.next().unwrap().parse::<i32>().unwrap());
    }
    let mut nzmin = 10;
    for &i in tm.iter() {
        if i % 10 == 0 {
            continue;
        }
        nzmin = std::cmp::min(i % 10, nzmin);
    }
    let mut ans = 0;
    for &i in tm.iter() {
        ans += (i + 9) / 10 * 10;
    }
    if nzmin != 0 {
        ans -= 10 - nzmin
    };
    println!("{}", ans);
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> of length <var>N</var> consisting of lowercase English letters, and an integer <var>K</var>.
Print the string obtained by replacing every character in <var>S</var> that differs from the <var>K</var>-th character of <var>S</var>, with *.

Constraints

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

<var>S</var> is a string of length <var>N</var> consisting of lowercase English letters.

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the string obtained by replacing every character in <var>S</var> that differs from the <var>K</var>-th character of <var>S</var>, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of <var>S</var> is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**

int solution(void) {
  int n = 0;
  scanf("%d", &n);
  char a[n];
  scanf("%s", a);
  int k = 0;
  scanf("%d", &k);
  char b;
  b = a[k - 1];
  for (int i = 0; i < n; i++) {
    if (a[i] != b) {
      a[i] = '*';
    }
  }
  printf("%s", a);

  return 0;
}

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

    let ans = S
        .iter()
        .map(|&c| {
            if c == S[K - 1] {
                c.to_string()
            } else {
                "*".to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("");

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


Score : <var>100</var> points

Problem Statement

There is a set <var>A = \{ a_1, a_2, \ldots, a_N \}</var> consisting of <var>N</var> positive integers.
Taro and Jiro will play the following game against each other.

Initially, we have a pile consisting of <var>K</var> stones.
The two players perform the following operation alternately, starting from Taro:

Choose an element <var>x</var> in <var>A</var>, and remove exactly <var>x</var> stones from the pile.

A player loses when he becomes unable to play.
Assuming that both players play optimally, determine the winner.

Constraints

All values in input are integers.

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

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

<var>1 \leq a_1 < a_2 < \cdots < a_N \leq K</var>

Input

Input is given from Standard Input in the following format:

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

Output

If Taro will win, print First; if Jiro will win, print Second.

Sample Input 1

2 4
2 3

Sample Output 1

First

If Taro removes three stones, Jiro cannot make a move.
Thus, Taro wins.

Sample Input 2

2 5
2 3

Sample Output 2

Second

Whatever Taro does in his operation, Jiro wins, as follows:

If Taro removes two stones, Jiro can remove three stones to make Taro unable to make a move.

If Taro removes three stones, Jiro can remove two stones to make Taro unable to make a move.

Sample Input 3

2 7
2 3

Sample Output 3

First

Taro should remove two stones. Then, whatever Jiro does in his operation, Taro wins, as follows:

If Jiro removes two stones, Taro can remove three stones to make Jiro unable to make a move.

If Jiro removes three stones, Taro can remove two stones to make Jiro unable to make a move.

Sample Input 4

3 20
1 2 3

Sample Output 4

Second

Sample Input 5

3 21
1 2 3

Sample Output 5

First

Sample Input 6

1 100000
1

Sample Output 6

Second

int solution() {
  int n;
  int k;
  scanf("%d %d", &n, &k);
  int a[n];
  int i;
  int j;
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  int dp[k + 1];
  dp[0] = 0;
  for (i = 1; i <= k; i++) {
    int status = 0;
    for (j = 0; j < n; j++) {
      int p = i - a[j];
      if (p >= 0 && dp[p] == 0) {
        status = 1;
        break;
      }
    }
    dp[i] = status;
  }
  if (dp[k] == 1) {
    printf(" First ");
  } else {
    printf(" Second ");
  }
  return 0;
}

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

    let mut dp: Vec<bool> = vec![false; 200020];

    dp[0] = true;
    for i in 1..k + 1 {
        let mut make = true;
        for j in 0..n {
            if i >= a[j] && dp[i - a[j]] {
                make = false;
                break;
            }
        }
        dp[i] = make;
    }

    if dp[k] {
        println!("Second");
    } else {
        println!("First");
    }
}


Score : <var>200</var> points

Problem Statement

There is a kangaroo at coordinate <var>0</var> on an infinite number line that runs from left to right, at time <var>0</var>.
During the period between time <var>i-1</var> and time <var>i</var>, the kangaroo can either stay at his position, or perform a jump of length exactly <var>i</var> to the left or to the right.
That is, if his coordinate at time <var>i-1</var> is <var>x</var>, he can be at coordinate <var>x-i</var>, <var>x</var> or <var>x+i</var> at time <var>i</var>.
The kangaroo's nest is at coordinate <var>X</var>, and he wants to travel to coordinate <var>X</var> as fast as possible.
Find the earliest possible time to reach coordinate <var>X</var>.

Constraints

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

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

Input

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

<var>X</var>

Output

Print the earliest possible time for the kangaroo to reach coordinate <var>X</var>.

Sample Input 1

6

Sample Output 1

3

The kangaroo can reach his nest at time <var>3</var> by jumping to the right three times, which is the earliest possible time.

Sample Input 2

2

Sample Output 2

2

He can reach his nest at time <var>2</var> by staying at his position during the first second, and jumping to the right at the next second.

Sample Input 3

11

Sample Output 3

5

int solution() {
  long long x = 1;
  scanf("%lld", &x);

  long long i = 1;
  while (i * (i + 1) / 2 < x) {
    i++;
  }
  printf("%lld", i);
}

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 mut ok = 0;
    let mut ng = 1usize << 30;
    while ng - ok > 1 {
        let mid = (ok + ng) / 2;
        if mid * (mid + 1) / 2 < n {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    println!("{}", ok + 1);
}


A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larger than the middle car, and the middle car is strictly larger than the smallest car. Masha came to test these cars. She could climb into all cars, but she liked only the smallest car. It's known that a character with size a can climb into some car with size b if and only if a ≤ b, he or she likes it if and only if he can climb into this car and 2a ≥ b.You are given sizes of bears and Masha. Find out some possible integer non-negative sizes of cars.

fn solution() {
    let mut input = String::new();
    use std::io::prelude::*;
    std::io::stdin().read_to_string(&mut input).unwrap();
    let mut it = input.split_whitespace();

    let v1: u32 = it.next().unwrap().parse().unwrap();
    let v2: u32 = it.next().unwrap().parse().unwrap();
    let v3: u32 = it.next().unwrap().parse().unwrap();
    let vm: u32 = it.next().unwrap().parse().unwrap();

    let s1 = 2 * v1;

    if vm > s1 || 2 * vm >= s1 {
        println!("-1");
        return;
    }

    let s2 = std::cmp::min(2 * v2, s1 - 1);

    if v2 > s2 || vm > s2 || 2 * v2 < s2 || 2 * vm >= s2 {
        println!("-1");
        return;
    }

    let s3 = std::cmp::min(std::cmp::min(2 * v3, s2 - 1), 2 * vm);

    if v3 > s3 || vm > s3 || 2 * v3 < s3 || 2 * vm < s3 {
        println!("-1");
        return;
    }

    println!("{}\n{}\n{}", s1, s2, s3);
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> squares in a row.
The leftmost square contains the integer <var>A</var>, and the rightmost contains the integer <var>B</var>. The other squares are empty.

Aohashi would like to fill the empty squares with integers so that the following condition is satisfied:

For any two adjacent squares, the (absolute) difference of the two integers in those squares is between <var>C</var> and <var>D</var> (inclusive).

As long as the condition is satisfied, it is allowed to use arbitrarily large or small integers to fill the squares.
Determine whether it is possible to fill the squares under the condition.

Constraints

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

<var>0 \leq A \leq 10^9</var>

<var>0 \leq B \leq 10^9</var>

<var>0 \leq C \leq D \leq 10^9</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print YES if it is possible to fill the squares under the condition; print NO otherwise.

Sample Input 1

5 1 5 2 4

Sample Output 1

YES

For example, fill the squares with the following integers: <var>1</var>, <var>-1</var>, <var>3</var>, <var>7</var>, <var>5</var>, from left to right.

Sample Input 2

4 7 6 4 5

Sample Output 2

NO

Sample Input 3

48792 105960835 681218449 90629745 90632170

Sample Output 3

NO

Sample Input 4

491995 412925347 825318103 59999126 59999339

Sample Output 4

YES

int solution(void) {
  long long int N;
  long long int A;
  long long int B;
  long long int C;
  long long int D;
  scanf("%lld %lld %lld %lld %lld", &N, &A, &B, &C, &D);
  int flag = 0;
  for (int i = 0; i < N; i++) {
    if (i * D - (N - i - 1) * C >= B - A && i * C - (N - 1 - i) * D <= B - A) {
      flag = 1;
      break;
    }
  }
  if (flag == 1) {
    printf("YES");
  } else {
    printf("NO");
  }
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: i64 = itr.next().unwrap().parse().unwrap();
    let a: i64 = itr.next().unwrap().parse().unwrap();
    let b: i64 = itr.next().unwrap().parse().unwrap();
    let c: i64 = itr.next().unwrap().parse().unwrap();
    let d: i64 = itr.next().unwrap().parse().unwrap();

    for up in 0..n {
        let down = n - 1 - up;
        let max = a + d * up - c * down;
        let min = a + c * up - d * down;
        if min <= b && b <= max {
            println!("YES");
            return;
        }
    }
    println!("NO");
}