You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

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

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

    let pow2 = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048];
    for _ in 0..t {
        let mut vals = [0u8; 12];
        let mut _input = String::new();
        io::stdin()
            .read_line(&mut _input)
            .expect("failed to read input");

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        for n in input.split_whitespace() {
            let n = n.parse::<u32>().unwrap();
            if n <= 2048 {
                let log_n = pow2.binary_search(&n).unwrap();
                vals[log_n] += 1;
            }
        }

        let mut rem = 1u16;
        for n in vals.iter().rev() {
            if rem <= *n as u16 {
                rem = 0;
                break;
            } else {
                rem -= *n as u16;
                rem *= 2;
            }
        }

        if rem == 0 {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. $$$2 \cdot n$$$ students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly $$$n$$$ people in each row). Students are numbered from $$$1$$$ to $$$n$$$ in each row in order from left to right.  Now Demid wants to choose a team to play basketball. He will choose players from left to right, and the index of each chosen player (excluding the first one taken) will be strictly greater than the index of the previously chosen player. To avoid giving preference to one of the rows, Demid chooses students in such a way that no consecutive chosen students belong to the same row. The first student can be chosen among all $$$2n$$$ students (there are no additional constraints), and a team can consist of any number of students. Demid thinks, that in order to compose a perfect team, he should choose students in such a way, that the total height of all chosen students is maximum possible. Help Demid to find the maximum possible total height of players in a team he can choose.

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

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

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

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

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

    let mut x = 0;
    let mut y = 0;
    let mut z = 0;
    let mut tempx;
    let mut tempy;

    for i in 0..n as usize {
        tempx = x;
        tempy = y;
        x = max(y + a[i], z + a[i]);
        y = max(tempx + b[i], z + b[i]);
        z = max(tempx, tempy);
    }

    println!("{}", max(x, max(y, z)));
}


You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.  Space can be represented as the $$$XY$$$ plane. You are starting at point $$$(0, 0)$$$, and Planetforces is located in point $$$(p_x, p_y)$$$.The piloting system of your spaceship follows its list of orders which can be represented as a string $$$s$$$. The system reads $$$s$$$ from left to right. Suppose you are at point $$$(x, y)$$$ and current order is $$$s_i$$$:   if $$$s_i = \text{U}$$$, you move to $$$(x, y + 1)$$$;  if $$$s_i = \text{D}$$$, you move to $$$(x, y - 1)$$$;  if $$$s_i = \text{R}$$$, you move to $$$(x + 1, y)$$$;  if $$$s_i = \text{L}$$$, you move to $$$(x - 1, y)$$$. Since string $$$s$$$ could be corrupted, there is a possibility that you won't reach Planetforces in the end. Fortunately, you can delete some orders from $$$s$$$ but you can't change their positions.Can you delete several orders (possibly, zero) from $$$s$$$ in such a way, that you'll reach Planetforces after the system processes all orders?

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    let mut i = i.lock().lines().skip(1);

    while let Some(l1) = i.next() {
        if let [xf, yf] = l1
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<i32>().unwrap())
            .collect::<Vec<_>>()[..]
        {
            let xd = if xf < 0 { 'L' } else { 'R' };
            let yd = if yf < 0 { 'D' } else { 'U' };
            let (x, y) = i
                .next()
                .unwrap()
                .unwrap()
                .chars()
                .filter(|&c| c == xd || c == yd)
                .fold((0, 0), |(x, y), c| match c {
                    'U' | 'D' => (x, y + 1),
                    _ => (x + 1, y),
                });
            writeln!(
                o,
                "{}",
                if xf.abs() <= x && yf.abs() <= y {
                    "YES"
                } else {
                    "NO"
                }
            )
            .ok();
        }
    }
}


Score : <var>200</var> points

Problem Statement

In some other world, today is the day before Christmas Eve.

Mr. Takaha is buying <var>N</var> items at a department store. The regular price of the <var>i</var>-th item <var>(1 \leq i \leq N)</var> is <var>p_i</var> yen (the currency of Japan).

He has a discount coupon, and can buy one item with the highest price for half the regular price. The remaining <var>N-1</var> items cost their regular prices. What is the total amount he will pay?

Constraints

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

<var>100 \leq p_i \leq 10000</var>

<var>p_i</var> is an even number.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>p_1</var>
<var>p_2</var>
<var>:</var>
<var>p_N</var>

Output

Print the total amount Mr. Takaha will pay.

Sample Input 1

3
4980
7980
6980

Sample Output 1

15950

The <var>7980</var>-yen item gets the discount and the total is <var>4980 + 7980 / 2 + 6980 = 15950</var> yen.

Note that outputs such as 15950.0 will be judged as Wrong Answer.

Sample Input 2

4
4320
4320
4320
4320

Sample Output 2

15120

Only one of the four items gets the discount and the total is <var>4320 / 2 + 4320 + 4320 + 4320 = 15120</var> yen.

int solution() {
  int n = 0;
  scanf("%d\n", &n);
  int max = 0;
  int sum = 0;
  int buf = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &buf);
    sum += buf;
    if (buf > max) {
      max = buf;
    }
  }
  printf("%d\n", sum - (max / 2));
  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 p: Vec<i64> = (0..N)
        .map(|_| {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        })
        .collect();

    let ans = p.iter().sum::<i64>() - p.iter().max().unwrap() / 2;

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


Amugae has a hotel consisting of $$$10$$$ rooms. The rooms are numbered from $$$0$$$ to $$$9$$$ from left to right.The hotel has two entrances — one from the left end, and another from the right end. When a customer arrives to the hotel through the left entrance, they are assigned to an empty room closest to the left entrance. Similarly, when a customer arrives at the hotel through the right entrance, they are assigned to an empty room closest to the right entrance.One day, Amugae lost the room assignment list. Thankfully Amugae's memory is perfect, and he remembers all of the customers: when a customer arrived, from which entrance, and when they left the hotel. Initially the hotel was empty. Write a program that recovers the room assignment list from Amugae's memory.

int solution() {
  char kamar[11];
  int num;
  char in[100000];
  for (int i = 0; i <= 9; i++) {
    kamar[i] = '0';
  }
  scanf("%d", &num);
  getchar();
  for (int i = 1; i <= num; i++) {
    scanf("%c", &in[i]);
  }
  int nom = 0;
  int nim = 9;
  for (int i = 1; i <= num; i++) {
    if (in[i] == 'L') {
      while (kamar[nom] == '1') {
        nom++;
      }
      kamar[nom] = '1';
    } else if (in[i] == 'R') {
      while (kamar[nim] == '1') {
        nim--;
      }
      kamar[nim] = '1';
    } else if (in[i] >= '0' && in[i] <= '9') {
      int nom = in[i] - 48;
      kamar[nom] = '0';
    }
    nom = 0;
    nim = 9;
  }
  for (int i = 0; i <= 9; i++) {
    printf("%c", kamar[i]);
  }
  printf("\n");
  return 0;
}

fn solution() {
    let mut _input = String::new();
    io::stdin()
        .read_line(&mut _input)
        .expect("failed to read input");
    let mut rooms: Vec<bool> = vec![false; 10];
    let mut l: usize = 0;
    let mut r: usize = 9;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    for i in input.trim().chars() {
        match i {
            'L' => {
                rooms[l] = true;
                if l == r {
                    l = 9;
                    r = 0;
                } else {
                    l = ((l + 1)..10).find(|&x| !rooms[x]).unwrap_or(9);
                }
            }
            'R' => {
                rooms[r] = true;
                if l == r {
                    l = 9;
                    r = 0;
                } else {
                    r = (0..r).rev().find(|&x| !rooms[x]).unwrap_or(0);
                }
            }
            _ => {
                let room = (i as usize) - ('0' as usize);
                rooms[room] = false;

                if room < l {
                    l = room;
                }
                if room > r {
                    r = room;
                }
            }
        }
    }

    rooms
        .iter()
        .for_each(|&x| print!("{}", if x { 1 } else { 0 }));
    println!();
}


Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

fn solution() {
    let input_handle = io::stdin();
    let input = &mut String::new();
    input_handle.read_line(input);
    let ad = &mut input
        .split_whitespace()
        .map(|word| word.parse::<f64>().unwrap());
    let (a, d) = (ad.next().unwrap(), ad.next().unwrap());
    let input = &mut String::new();
    input_handle.read_line(input);
    let n = input
        .split_whitespace()
        .map(|word| word.parse::<usize>().unwrap())
        .next()
        .unwrap();

    let mut answer = String::new();
    let mut pos = 0f64;
    for _n in 0..n {
        pos += d;
        pos %= 4f64 * a;
        if pos > 3f64 * a {
            answer += "0 ";
            answer += &((4f64 * a - pos).to_string());
        } else if pos > 2f64 * a {
            answer += &((3f64 * a - pos).to_string());
            answer += " ";
            answer += &(a.to_string());
        } else if pos > a {
            answer += &(a.to_string());
            answer += " ";
            answer += &((pos - a).to_string());
        } else {
            answer += &((pos).to_string());
            answer += " 0";
        }
        answer += "\n";
    }
    print!("{}", answer);
}


New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

int solution() {

  int numberOfCells = 0;
  int wantToMove = 0;

  scanf("%d", &numberOfCells);
  scanf("%d", &wantToMove);

  int flag = 0;
  int movable = 1;

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

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

    if (i == movable) {

      movable = (i + temp);

      if (wantToMove == movable) {
        flag = 1;
      }
    }
  }

  if (flag) {
    printf("YES");
  } else {
    printf("NO");
  }

  return 0;
}

fn solution() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };
    let (n, t) = (v[0], v[1]);
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };

    let mut current = 0;
    while current != t - 1 && current < n - 1 {
        current += v[current as usize];
    }
    println!("{}", if current == t - 1 { "YES" } else { "NO" });
}


Score : <var>400</var> points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered <var>1, 2, \cdots, N</var>. Square <var>i</var> has an integer <var>C_i</var> written on it. Also, he is given a permutation of <var>1, 2, \cdots, N</var>: <var>P_1, P_2, \cdots, P_N</var>.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between <var>1</var> and <var>K</var> (inclusive):

In one move, if the piece is now on Square <var>i</var> <var>(1 \leq i \leq N)</var>, move it to Square <var>P_i</var>. Here, his score increases by <var>C_{P_i}</var>.

Help him by finding the maximum possible score at the end of the game. (The score is <var>0</var> at the beginning of the game.)

Constraints

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

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

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

<var>P_i \neq i</var>

<var>P_1, P_2, \cdots, P_N</var> are all different.

<var>-10^9 \leq C_i \leq 10^9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>P_1</var> <var>P_2</var> <var>\cdots</var> <var>P_N</var>
<var>C_1</var> <var>C_2</var> <var>\cdots</var> <var>C_N</var>

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square <var>1</var>, making one move sends the piece to Square <var>2</var>, after which the score is <var>4</var>. Making another move sends the piece to Square <var>4</var>, after which the score is <var>4 + (-8) = -4</var>.

If we start at Square <var>2</var>, making one move sends the piece to Square <var>4</var>, after which the score is <var>-8</var>. Making another move sends the piece to Square <var>1</var>, after which the score is <var>-8 + 3 = -5</var>.

If we start at Square <var>3</var>, making one move sends the piece to Square <var>5</var>, after which the score is <var>8</var>. Making another move sends the piece to Square <var>3</var>, after which the score is <var>8 + (-10) = -2</var>.

If we start at Square <var>4</var>, making one move sends the piece to Square <var>1</var>, after which the score is <var>3</var>. Making another move sends the piece to Square <var>2</var>, after which the score is <var>3 + 4 = 7</var>.

If we start at Square <var>5</var>, making one move sends the piece to Square <var>3</var>, after which the score is <var>-10</var>. Making another move sends the piece to Square <var>5</var>, after which the score is <var>-10 + 8 = -2</var>.

The maximum score achieved is <var>8</var>.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.

int solution(void) {
  int N;
  int K = 0;
  scanf("%d %d", &N, &K);
  int PList[N];
  int CList[N];
  int i = 0;
  for (i = 0; i < N; i++) {
    scanf("%d", &PList[i]);
  }
  for (i = 0; i < N; i++) {
    scanf("%d", &CList[i]);
  }
  long long ans = -1e18;
  int si = 0;
  for (si = 0; si < N; si++) {
    int x = si;
    int s[N];
    long long total = 0;
    long long l = 0;
    int idx = -1;
    while (1) {
      x = PList[x] - 1;
      s[++idx] = CList[x];
      l += 1;
      total += CList[x];
      if (x == si) {
        break;
      }
    }
    long long t = 0;
    for (i = 0; i < l; i++) {
      t += s[i];
      if (i + 1 > K) {
        break;
      }
      long long now = t;
      if (total > 0) {
        long long e = (K - (i + 1)) / l;
        now += total * e;
      }
      if (ans < now) {
        ans = now;
      }
    }
  }
  printf("%lld", ans);
  return 0;
}

fn solution() {
    let (n, k): (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(),
        )
    };

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

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

    let mut ans = std::i64::MIN;
    for mut i in 0..n {
        let mut v = vec![0; n + 1];
        let mut w = vec![0; n];
        let mut check = vec![false; n];
        let mut d = 0;
        for j in 0..n {
            check[i] = true;
            v[j + 1] = v[j] + c[p[i]];
            w[j] = c[p[i]];
            i = p[i];
            if check[i] {
                d = j + 1;
                break;
            }
        }

        let res = {
            if k <= d {
                (1..=(cmp::min(k, d))).fold(std::i64::MIN, |acc, j| cmp::max(acc, v[j]))
            } else if v[d] <= 0 {
                (1..=(cmp::min(k, d))).fold(std::i64::MIN, |acc, j| cmp::max(acc, v[j]))
            } else {
                let p = (k - d) % d;
                let (mut max, mut sum) = (0, 0);
                for j in 0..d {
                    sum += w[(j + p) % d];
                    max = cmp::max(max, sum);
                }
                v[d] * ((k - d) / d) as i64 + v[p] + max
            }
        };
        ans = cmp::max(ans, res);
    }
    println!("{}", ans);
}


You have a deck of $$$n$$$ cards, and you'd like to reorder it to a new one.Each card has a value between $$$1$$$ and $$$n$$$ equal to $$$p_i$$$. All $$$p_i$$$ are pairwise distinct. Cards in a deck are numbered from bottom to top, i. e. $$$p_1$$$ stands for the bottom card, $$$p_n$$$ is the top card. In each step you pick some integer $$$k > 0$$$, take the top $$$k$$$ cards from the original deck and place them, in the order they are now, on top of the new deck. You perform this operation until the original deck is empty. (Refer to the notes section for the better understanding.)Let's define an order of a deck as $$$\sum\limits_{i = 1}^{n}{n^{n - i} \cdot p_i}$$$.Given the original deck, output the deck with maximum possible order you can make using the operation above.

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

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

    io::stdin().read_line(&mut testcases).expect("");

    let testcases: usize = testcases.trim().parse().unwrap();

    for _testcase in 0..testcases {
        let mut input: String = String::new();

        let mut deck: Vec<usize> = Vec::new();
        let mut result: Vec<usize> = Vec::new();
        let mut indexes: HashMap<usize, usize> = HashMap::new();

        io::stdin().read_line(&mut input).expect("");

        let size: usize = input.trim().parse().unwrap();

        input.clear();
        io::stdin().read_line(&mut input).expect("");

        for (index, item) in input.trim().split(" ").enumerate() {
            let n: usize = item.parse().unwrap();
            deck.push(n);
            indexes.insert(n, index);
        }

        let mut current_pos: usize = size;

        for i in (1..size + 1).rev() {
            let pos: usize = indexes.get(&i).unwrap().to_owned();
            if pos < current_pos {
                result.extend_from_slice(&deck[pos..current_pos]);

                current_pos = pos;
            }
        }

        for n in result {
            print!("{} ", n);
        }

        println!();
    }
}


Score : <var>300</var> points

Problem Statement

You are given a string <var>s</var>.
Among the different substrings of <var>s</var>, print the <var>K</var>-th lexicographically smallest one.

A substring of <var>s</var> is a string obtained by taking out a non-empty contiguous part in <var>s</var>.
For example, if <var>s</var> <var>=</var> ababc, a, bab and ababc are substrings of <var>s</var>, while ac, z and an empty string are not.
Also, we say that substrings are different when they are different as strings.

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

Constraints

<var>1</var> <var>≤</var> <var>|s|</var> <var>≤</var> <var>5000</var>

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

<var>1</var> <var>≤</var> <var>K</var> <var>≤</var> <var>5</var>

<var>s</var> has at least <var>K</var> different substrings.

Partial Score

<var>200</var> points will be awarded as a partial score for passing the test set satisfying <var>|s|</var> <var>≤</var> <var>50</var>.

Input

Input is given from Standard Input in the following format:

<var>s</var>
<var>K</var>

Output

Print the <var>K</var>-th lexicographically smallest substring of <var>K</var>.

Sample Input 1

aba
4

Sample Output 1

b

<var>s</var> has five substrings: a, b, ab, ba and aba.
Among them, we should print the fourth smallest one, b.
Note that we do not count a twice.

Sample Input 2

atcoderandatcodeer
5

Sample Output 2

andat

Sample Input 3

z
1

Sample Output 3

z

int solution() {
  char s[5001];
  scanf("%s", s);
  int K;
  scanf("%d", &K);

  int l = strlen(s);
  int c = 0;
  for (int i = 0; i < K; i++) {
    c += l - i;
  }

  char sub[c][K + 1];

  int cc = 0;
  for (int i = 1; i <= K; i++) {
    for (int j = 0; j < l - i + 1; j++) {
      for (int k = 0; k < i; k++) {
        sub[cc][k] = s[j + k];
        if (k == i - 1) {
          for (k; k < K; k++) {
            sub[cc][k + 1] = '\0';
          }
        }
      }
      cc++;
    }
  }

  int r = c;
  int swapped = 0;
  while (r > 1 || swapped == 1) {
    if (r > 1) {
      r = r * 10 / 13;
    }
    swapped = 0;
    for (int i = 0; i + r < c; i++) {
      if (strcmp(sub[i], sub[i + r]) > 0) {
        char tmp[K + 1];
        for (int j = 0; j < K + 1; j++) {
          tmp[j] = sub[i][j];
        }
        for (int j = 0; j < K + 1; j++) {
          sub[i][j] = sub[i + r][j];
        }
        for (int j = 0; j < K + 1; j++) {
          sub[i + r][j] = tmp[j];
        }
        swapped = 1;
      }
    }
  }

  int k = 1;
  for (int i = 0; i < c; i++) {
    if (i > 0 && strcmp(sub[i - 1], sub[i]) != 0) {
      k++;
    }
    if (k == K) {
      printf("%s\n", sub[i]);
      return 0;
    }
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let s = lines.next().unwrap().unwrap();
    let k: usize = lines.next().unwrap().unwrap().parse().unwrap();
    let mut ss: BTreeSet<&str> = BTreeSet::new();
    for i in 0..s.len() {
        let len = min(5, s.len() - i);
        for j in 0..len {
            ss.insert(&s[i..(i + j + 1)]);
        }
    }
    let mut it = ss.iter();
    for _ in 0..(k - 1) {
        it.next();
    }
    println!("{}", it.next().unwrap());
}


You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.  For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.

int solution(void) {
  int test = 0;

  scanf("%d", &test);

  while (test--) {
    int a;
    int b;
    scanf("%d %d", &a, &b);
    long long n = a;
    long long m = b;
    long long r = (m * n * (n + 1) + m * m - m) / 2;

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

  return 0;
}

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

    let round: usize = round.trim().parse().expect("parsing");
    let mut i = 1;

    while i <= round {
        let mut size = String::new();
        io::stdin().read_line(&mut size).expect("loop input");

        let space_index = size.find(" ").expect(" ");
        let n: usize = size[..space_index].trim().parse().expect("loop parsing");
        let m: usize = size[space_index..].trim().parse().expect("loop parsing");

        let mut sum = 0;
        let mut j = 1;
        let mut k = 2;

        while j <= m {
            sum += j;
            j += 1;
        }

        while k <= n {
            sum += k * m;
            k += 1;
        }

        println!("{}", sum);
        i += 1;
    }
}


You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second:  Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int c;
    scanf("%d", &c);
    long long a;
    long long cMax = 9223372036854775807 * -1;
    int bitMax = 0;
    for (int j = 0; j < c; j++) {
      scanf("%lli", &a);
      if (a >= cMax) {
        cMax = a;
      } else {
        long long diff = cMax - a;
        int bitDiff = (int)log2(diff) + 1;

        if (bitDiff > bitMax) {
          bitMax = bitDiff;
        }
      }
    }
    printf("%d\n", bitMax);
  }
}

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();
        let mut ans: usize = 0;
        for i in 1..n {
            if xs[i - 1] > xs[i] {
                let mut count: usize = 0;
                let mut d = xs[i - 1] - xs[i];
                while d > 0 {
                    d >>= 1;
                    count += 1;
                }
                ans = max(ans, count);
                xs[i] = xs[i - 1];
            }
        }
        println!("{}", ans);
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi received otoshidama (New Year's money gifts) from <var>N</var> of his relatives.

You are given <var>N</var> values <var>x_1, x_2, ..., x_N</var> and <var>N</var> strings <var>u_1, u_2, ..., u_N</var> as input. Each string <var>u_i</var> is either JPY or BTC, and <var>x_i</var> and <var>u_i</var> represent the content of the otoshidama from the <var>i</var>-th relative.

For example, if <var>x_1 =</var> 10000 and <var>u_1 =</var> JPY, the otoshidama from the first relative is <var>10000</var> Japanese yen; if <var>x_2 =</var> 0.10000000 and <var>u_2 =</var> BTC, the otoshidama from the second relative is <var>0.1</var> bitcoins.

If we convert the bitcoins into yen at the rate of <var>380000.0</var> JPY per <var>1.0</var> BTC, how much are the gifts worth in total?

Constraints

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

<var>u_i =</var> JPY or BTC.

If <var>u_i =</var> JPY, <var>x_i</var> is an integer such that <var>1 \leq x_i \leq 10^8</var>.

If <var>u_i =</var> BTC, <var>x_i</var> is a decimal with <var>8</var> decimal digits, such that <var>0.00000001 \leq x_i \leq 100.00000000</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>x_1</var> <var>u_1</var>
<var>x_2</var> <var>u_2</var>
<var>:</var>
<var>x_N</var> <var>u_N</var>

Output

If the gifts are worth <var>Y</var> yen in total, print the value <var>Y</var> (not necessarily an integer).

Output will be judged correct when the absolute or relative error from the judge's output is at most <var>10^{-5}</var>.

Sample Input 1

2
10000 JPY
0.10000000 BTC

Sample Output 1

48000.0

The otoshidama from the first relative is <var>10000</var> yen. The otoshidama from the second relative is <var>0.1</var> bitcoins, which is worth <var>38000.0</var> yen if converted at the rate of <var>380000.0</var> JPY per <var>1.0</var> BTC. The sum of these is <var>48000.0</var> yen.

Outputs such as 48000 and 48000.1 will also be judged correct.

Sample Input 2

3
100000000 JPY
100.00000000 BTC
0.00000001 BTC

Sample Output 2

138000000.0038

In this case, outputs such as 138001000 and 1.38e8 will also be judged correct.

int solution(void) {
  int N = 0;
  scanf("%d", &N);
  double x = 0;
  char u[4];
  double sum = 0;
  for (int i = 0; i < N; i++) {
    scanf("%lf %s", &x, u);
    if (u[0] == 'J' && u[1] == 'P' && u[2] == 'Y') {
      sum += x;
    } else {
      sum += 380000.0 * x;
    }
  }
  printf("%f\n", sum);
  return 0;
}

fn solution() {
    let input = {
        use std::io::*;
        let mut input = String::new();
        let _ = stdin().read_to_string(&mut input);
        input
            .replace("JPY", "1.0")
            .replace("BTC", "380000.0")
            .split_whitespace()
            .skip(1)
            .map(|w| w.parse::<f64>().unwrap())
            .collect::<Vec<_>>()
    };
    let total = input.chunks(2).fold(0.0, |r, x| r + x[0] * x[1]);
    println!("{:?}", total);
}


Polycarp has a string $$$s$$$ consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string $$$s$$$ from left to right and for each letter Polycarp considers its number in the alphabet:  if the letter number is single-digit number (less than $$$10$$$), then just writes it out;  if the letter number is a two-digit number (greater than or equal to $$$10$$$), then it writes it out and adds the number 0 after. For example, if the string $$$s$$$ is code, then Polycarp will encode this string as follows:  'c' — is the $$$3$$$-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3);  'o' — is the $$$15$$$-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150);  'd' — is the $$$4$$$-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504);  'e' — is the $$$5$$$-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string $$$t$$$ resulting from encoding the string $$$s$$$. Your task is to decode it (get the original string $$$s$$$ by $$$t$$$).

fn solution() {
    let mut num = String::new();
    io::stdin().read_line(&mut num).expect("panic input num");
    let trimmed = num.trim().parse::<u32>().unwrap();
    let alph: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
    for _ in 0..trimmed {
        let mut _ln: String = String::new();
        io::stdin().read_line(&mut _ln).unwrap();

        let mut row = String::new();
        io::stdin().read_line(&mut row).unwrap();

        row = row.trim().to_string();

        let mut n: Vec<u32> = row.chars().map(|chr| chr.to_digit(10).unwrap()).collect();

        n = n.into_iter().rev().collect();
        let mut c: u8 = 0;
        let mut res: String = String::new();
        for i in 0..n.len() {
            if c != 0 {
                c -= 1;
                continue;
            }
            if n[i] == 0 {
                res.push(alph[(n[i + 1] + n[i + 2] * 10 - 1) as usize]);
                c = 2;
            } else {
                res.push(alph[(n[i] - 1) as usize]);
            }
        }
        res = res.chars().rev().collect::<String>();
        println!("{}", res);
    }
}


Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".Sergey is very busy and asks you to help him and write the required program.

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

    std::io::stdin()
        .read_line(&mut n)
        .expect("Reading n error!");

    let _n: u32 = n.trim().parse().expect("Error while parsing!");

    let mut cur_line = String::new();
    std::io::stdin()
        .read_line(&mut cur_line)
        .expect("Can't get current line!");

    let mut d = '!';
    let mut t = 0;

    for (_i, c) in cur_line.chars().enumerate() {
        if d != c {
            if t == 2 && (d == 'e' || d == 'o') {
                print!("{}", d);
            }

            if c == 'a' {
                print!("{}", c);
            }
            if c == 'e' {
                print!("{}", c);
            }
            if c == 'i' {
                print!("{}", c);
            }
            if c == 'o' {
                print!("{}", c);
            }
            if c == 'u' {
                print!("{}", c);
            }
            if c == 'y' {
                print!("{}", c);
            }

            d = c;
            t = 1;
        } else {
            t += 1;
        }

        if c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u' && c != 'y' {
            print!("{}", c);
        }
    }
    if t == 2 && (d == 'e' || d == 'o') {
        print!("{}", d);
    }
}


Score : <var>200</var> points

Problem Statement

You are given an image <var>A</var> composed of <var>N</var> rows and <var>N</var> columns of pixels, and a template image <var>B</var> composed of <var>M</var> rows and <var>M</var> columns of pixels.

A pixel is the smallest element of an image, and in this problem it is a square of size <var>1×1</var>.

Also, the given images are binary images, and the color of each pixel is either white or black.

In the input, every pixel is represented by a character: . corresponds to a white pixel, and # corresponds to a black pixel.

The image <var>A</var> is given as <var>N</var> strings <var>A_1,...,A_N</var>.

The <var>j</var>-th character in the string <var>A_i</var> corresponds to the pixel at the <var>i</var>-th row and <var>j</var>-th column of the image <var>A</var> <var>(1≦i,j≦N)</var>.

Similarly, the template image <var>B</var> is given as <var>M</var> strings <var>B_1,...,B_M</var>.

The <var>j</var>-th character in the string <var>B_i</var> corresponds to the pixel at the <var>i</var>-th row and <var>j</var>-th column of the template image <var>B</var> <var>(1≦i,j≦M)</var>.

Determine whether the template image <var>B</var> is contained in the image <var>A</var> when only parallel shifts can be applied to the images.

Constraints

<var>1≦M≦N≦50</var>

<var>A_i</var> is a string of length <var>N</var> consisting of # and ..

<var>B_i</var> is a string of length <var>M</var> consisting of # and ..

Input

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

<var>N</var> <var>M</var>
<var>A_1</var>
<var>A_2</var>
<var>:</var>
<var>A_N</var>
<var>B_1</var>
<var>B_2</var>
<var>:</var>
<var>B_M</var>

Output

Print Yes if the template image <var>B</var> is contained in the image <var>A</var>. Print No otherwise.

Sample Input 1

3 2
#.#
.#.
#.#
#.
.#

Sample Output 1

Yes

The template image <var>B</var> is identical to the upper-left <var>2 × 2</var> subimage and the lower-right <var>2 × 2</var> subimage of <var>A</var>. Thus, the output should be Yes.

Sample Input 2

4 1
....
....
....
....
#

Sample Output 2

No

The template image <var>B</var>, composed of a black pixel, is not contained in the image <var>A</var> composed of white pixels.

int solution(void) {

  int m = 1;
  int n = 1;
  int dif = 0;
  int match = 0;
  scanf("%d %d", &n, &m);

  dif = n - m;
  char a[n][51];
  char b[m][51];

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

  for (int i = 0; i <= dif; i++) {
    for (int j = 0; j <= dif; j++) {
      for (int k = 0; k < m; k++) {
        for (int l = 0; l < m; l++) {
          if (a[i + k][j + l] == b[k][l]) {
            match++;
          } else {
            match = 0;
            break;
          }
          if (match == (m * m)) {
            break;
          }
        }
        if (match == 0 || match == (m * m)) {
          break;
        }
      }
      if (match == (m * m)) {
        break;
      }
    }
    if (match == (m * m)) {
      break;
    }
  }

  if (match == (m * m)) {
    printf("Yes");
  } else {
    printf("No");
  }
  return 0;
}

fn solution() {
    let mut stdin = io::stdin();
    let mut lines = String::new();
    let _ = stdin.read_to_string(&mut lines);
    let vec = lines.lines().collect::<Vec<&str>>();
    let firstline = vec[0].split(' ').collect::<Vec<&str>>();
    let n: usize = firstline[0].trim().parse().unwrap();
    let m: usize = firstline[1].trim().parse().unwrap();
    let mkono1: u64 = (1 << m) - 1;
    let mut a: Vec<u64> = Vec::new();
    for i in 0..n {
        let mut thisline: u64 = 0;
        for (j, c) in vec[i + 1].trim().chars().enumerate() {
            if c == '#' {
                thisline += 1 << j;
            }
        }
        a.push(thisline);
    }
    let a = a;
    let mut b: Vec<u64> = Vec::new();
    for i in 0..m {
        let mut thisline: u64 = 0;
        for (j, c) in vec[i + n + 1].trim().chars().enumerate() {
            if c == '#' {
                thisline += 1 << j;
            }
        }
        b.push(thisline);
    }
    let b = b;
    'tate: for i in 0..(n - m + 1) {
        'yoko: for j in 0..(n - m + 1) {
            'chekku: for k in 0..m {
                let bline = b[k];
                let aline = (a[k + i] >> j) & mkono1;
                if aline ^ bline != 0 {
                    continue 'yoko;
                }
            }
            println!("Yes");
            return;
        }
    }
    println!("No");
}


マルバツスタンプ (Circle Cross Stamps)

問題文

JOI 君はマルスタンプ，バツスタンプ，マルバツスタンプの3種類のスタンプをそれぞれ <var>0</var> 個以上持っている．これらはマルやバツのマークを紙に印字することができるスタンプである．

マルスタンプを使うとマルが <var>1</var> つ印字され，バツスタンプを使うとバツが <var>1</var> つ印字される．マルバツスタンプを使うとマルとバツが横一列に <var>1</var> つずつ印字され，スタンプの向きを変えることで，マルの右にバツが来るようにも，バツの右にマルが来るようにも印字できる．

JOI 君は，持っているスタンプをそれぞれちょうど <var>1</var> 回ずつ適当な順番で使い，紙に横一列にマルとバツを印字した．印字されたマルとバツの列は文字列 <var>S</var> で表される．<var>S</var> は O と X から構成された長さ <var>N</var> の文字列であり，<var>S_i = </var> O ならば JOI 君が印字したマークのうち左から <var>i</var> 番目のものがマルであることを表し，<var>S_i =</var> X ならばそれがバツであることを表す (<var>1 ≦ i ≦ N</var>)．

あなたは，JOI 君が持っているスタンプの個数は分からないが，JOI 君が印字したマルとバツの列は知っている．印字されたマルとバツの列から，JOI 君が持っているマルバツスタンプの個数としてあり得るもののうち最大値を求めよ．

 制約

<var>1 ≦ N ≦ 100000 (= 10^5)</var>

<var>S</var> は長さ <var>N</var> の文字列である．

<var>S</var> の各文字は O か X である．

 入力・出力

入力

入力は以下の形式で標準入力から与えられる．

<var>N</var>

<var>S</var>

出力

JOI 君が持っているマルバツスタンプの個数としてあり得るもののうち最大値を出力せよ．

入出力例

入力例 1

5
OXXOX

出力例 1

2

JOI 君が印字したマークは，左から順に，マル，バツ，バツ，マル，バツである．JOI 君がマルスタンプ，バツスタンプ，マルバツスタンプをそれぞれ <var>0, 1, 2</var> 個持っているとすると，以下の順番でスタンプを使えば，そのようにマークを印字することができる．

<var>1</var> つ目のマルバツスタンプを使ってマルとバツをこの順に印字する．

この右に，<var>2</var> つ目のマルバツスタンプを使ってバツとマルをこの順に印字する．

最後に，この右に，バツスタンプを使ってバツを印字する．

マルバツスタンプを <var>3</var> 個以上持っているケースは考えられないので，<var>2</var> を出力する．

入力例 2

14
OXOXOXOXXOXOXO

出力例 2

7

入力例 3

10
OOOOOOOOOO

出力例 3

0

情報オリンピック日本委員会作 『第 18 回日本情報オリンピック JOI 2018/2019 予選競技課題』

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

    lock.read_to_string(&mut buf);

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let s: Vec<u8> = iter.next().unwrap().into();

    let mut i = 1;
    let mut answer = 0;
    while i < n {
        if s[i - 1] != s[i] {
            answer += 1;
            i += 2;
        } else {
            i += 1;
        }
    }

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


Score : <var>200</var> points

Problem Statement

Takahashi has <var>N</var> days of summer vacation.

His teacher gave him <var>M</var> summer assignments. It will take <var>A_i</var> days for him to do the <var>i</var>-th assignment.

He cannot do multiple assignments on the same day, or hang out on a day he does an assignment.

What is the maximum number of days Takahashi can hang out during the vacation if he finishes all the assignments during this vacation?

If Takahashi cannot finish all the assignments during the vacation, print -1 instead.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>...</var> <var>A_M</var>

Output

Print the maximum number of days Takahashi can hang out during the vacation, or -1.

Sample Input 1

41 2
5 6

Sample Output 1

30

For example, he can do the first assignment on the first <var>5</var> days, hang out on the next <var>30</var> days, and do the second assignment on the last <var>6</var> days of the vacation. In this way, he can safely spend <var>30</var> days hanging out.

Sample Input 2

10 2
5 6

Sample Output 2

-1

He cannot finish his assignments.

Sample Input 3

11 2
5 6

Sample Output 3

0

He can finish his assignments, but he will have no time to hang out.

Sample Input 4

314 15
9 26 5 35 8 9 79 3 23 8 46 2 6 43 3

Sample Output 4

9

int solution() {
  int time = 0;
  int NumTask = 0;
  scanf("%d %d", &time, &NumTask);
  int temp = 0;
  for (int i = 0; i < NumTask; i++) {
    scanf("%d", &temp);
    time -= temp;
  }
  if (time >= 0) {
    printf("%d", time);
  } else {
    printf("-1");
  }
}

fn solution() {
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let (n, _m) = {
        let nm: Vec<_> = st
            .trim()
            .split(" ")
            .map(|x| x.parse::<i64>().unwrap())
            .collect();
        (nm[0], nm[1])
    };
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let a: Vec<i64> = st.trim().split(" ").map(|x| x.parse().unwrap()).collect();
    let result: i64 = a.iter().sum();
    if result <= n {
        println!("{}", n - result);
    } else {
        println!("-1");
    };
}


Score : <var>300</var> points

Problem Statement

There is a sequence of length <var>N</var>: <var>A_1, A_2, ..., A_N</var>. Initially, this sequence is a permutation of <var>1, 2, ..., N</var>.

On this sequence, Snuke can perform the following operation:

Choose <var>K</var> consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.

Snuke would like to make all the elements in this sequence equal by repeating the operation above some number of times.
Find the minimum number of operations required.
It can be proved that, Under the constraints of this problem, this objective is always achievable.

Constraints

<var>2 \leq K \leq N \leq 100000</var>

<var>A_1, A_2, ..., A_N</var> is a permutation of <var>1, 2, ..., N</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>...</var> <var>A_N</var>

Output

Print the minimum number of operations required.

Sample Input 1

4 3
2 3 1 4

Sample Output 1

2

One optimal strategy is as follows:

In the first operation, choose the first, second and third elements. The sequence <var>A</var> becomes <var>1, 1, 1, 4</var>.

In the second operation, choose the second, third and fourth elements. The sequence <var>A</var> becomes <var>1, 1, 1, 1</var>.

Sample Input 2

3 3
1 2 3

Sample Output 2

1

Sample Input 3

8 3
7 3 1 8 4 6 2 5

Sample Output 3

4

int solution(void) {
  int n = 0;
  int k = 0;
  int count = 0;
  scanf("%d %d", &n, &k);
  while (n > 0) {
    count++;
    n -= k;
    if (n) {
      n++;
    }
  }
  printf("%d\n", count);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: u32 = iter.next().unwrap().parse().unwrap();
    let k: u32 = iter.next().unwrap().parse().unwrap();
    let ans = (n - 1) / (k - 1) + if (n - 1).is_multiple_of(k - 1) { 0 } else { 1 };
    println!("{}", ans);
}


Score : <var>300</var> points

Problem Statement

Two foxes Jiro and Saburo are playing a game called 1D Reversi. This game is played on a board, using black and white stones. On the board, stones are placed in a row, and each player places a new stone to either end of the row. Similarly to the original game of Reversi, when a white stone is placed, all black stones between the new white stone and another white stone, turn into white stones, and vice versa.

In the middle of a game, something came up and Saburo has to leave the game. The state of the board at this point is described by a string <var>S</var>. There are |S| (the length of <var>S</var>) stones on the board, and each character in <var>S</var> represents the color of the <var>i</var>-th (<var>1 ≦ i ≦ |S|</var>) stone from the left. If the <var>i</var>-th character in <var>S</var> is B, it means that the color of the corresponding stone on the board is black. Similarly, if the <var>i</var>-th character in <var>S</var> is W, it means that the color of the corresponding stone is white.

Jiro wants all stones on the board to be of the same color. For this purpose, he will place new stones on the board according to the rules. Find the minimum number of new stones that he needs to place.

Constraints

<var>1 ≦ |S| ≦ 10^5</var>

Each character in <var>S</var> is B or W.

Input

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

<var>S</var>

Output

Print the minimum number of new stones that Jiro needs to place for his purpose.

Sample Input 1

BBBWW

Sample Output 1

1

By placing a new black stone to the right end of the row of stones, all white stones will become black. Also, by placing a new white stone to the left end of the row of stones, all black stones will become white.

In either way, Jiro's purpose can be achieved by placing one stone.

Sample Input 2

WWWWWW

Sample Output 2

0

If all stones are already of the same color, no new stone is necessary.

Sample Input 3

WBWBWBWBWB

Sample Output 3

9

int solution() {
  char S[100000];
  int i = 0;
  int count = 0;
  while (1) {
    scanf("%c", &S[i]);
    if (S[i] == '\n') {
      break;
    }

    if (i != 0 && S[i - 1] != S[i]) {
      count++;
    }
    i++;
  }

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

  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let mut reader = std::io::BufReader::new(stdin.lock());

    let mut s = String::new();
    reader.read_line(&mut s).unwrap();
    let mut s: Vec<char> = s.trim().chars().collect();

    s.dedup();

    println!("{}", s.len() - 1);
}


Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example,  if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

  Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1

int solution(void) {
  int i = 0;

  int n = 0;

  int maxv = 0;
  int minv = 0;

  int buf = 0;

  scanf("%d", &n);

  scanf("%d", &minv);

  for (i = 1; i < n; i++) {
    scanf("%d", &buf);

    if (i == 1) {
      maxv = buf - minv;
    }

    maxv = maxv > buf - minv ? maxv : buf - minv;
    minv = minv < buf ? minv : buf;
  }

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

  return 0;
}

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

    let mut buf: String = String::new();

    stdin.lock().read_line(&mut buf).expect("read_line()");
    stdin.lock().read_line(&mut buf).expect("read_line()");
    let vec: Vec<&str> = buf.split_whitespace().collect();

    let n = vec[0].parse().unwrap();

    let mut r_old: i32 = vec[1].parse().unwrap();

    let mut min = r_old;

    let mut gain_max: i32 = -1000000000;

    let mut gain = 0;

    let mut buf = String::new();
    for _t in 1..n {
        stdin.lock().read_line(&mut buf).expect("read_line()");
    }
    let r_series: Vec<&str> = buf.split_whitespace().collect();
    for t in 1..n {
        let rt = r_series[t - 1].parse().unwrap();
        let diff = rt - r_old;
        if min > rt {
            min = rt;
            if gain_max < diff {
                gain_max = diff;
            }
            gain = 0;
        } else {
            gain += diff;
            if gain_max < gain {
                gain_max = gain;
            }
        }
        r_old = rt;
    }
    println!("{}", gain_max);
}


Score : <var>300</var> points

Problem Statement

You are given three integers <var>A</var>, <var>B</var> and <var>C</var>. Find the minimum number of operations required to make <var>A</var>, <var>B</var> and <var>C</var> all equal by repeatedly performing the following two kinds of operations in any order:

Choose two among <var>A</var>, <var>B</var> and <var>C</var>, then increase both by <var>1</var>.

Choose one among <var>A</var>, <var>B</var> and <var>C</var>, then increase it by <var>2</var>.

It can be proved that we can always make <var>A</var>, <var>B</var> and <var>C</var> all equal by repeatedly performing these operations.

Constraints

<var>0 \leq A,B,C \leq 50</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>

Output

Print the minimum number of operations required to make <var>A</var>, <var>B</var> and <var>C</var> all equal.

Sample Input 1

2 5 4

Sample Output 1

2

We can make <var>A</var>, <var>B</var> and <var>C</var> all equal by the following operations:

Increase <var>A</var> and <var>C</var> by <var>1</var>. Now, <var>A</var>, <var>B</var>, <var>C</var> are <var>3</var>, <var>5</var>, <var>5</var>, respectively.

Increase <var>A</var> by <var>2</var>. Now, <var>A</var>, <var>B</var>, <var>C</var> are <var>5</var>, <var>5</var>, <var>5</var>, respectively.

Sample Input 2

2 6 3

Sample Output 2

5

Sample Input 3

31 41 5

Sample Output 3

23

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

    let max = a[2] * 3;
    let sum = a.iter().sum::<usize>();
    if (max - sum).is_multiple_of(2) {
        println!("{}", (max - sum) / 2);
    } else {
        println!("{}", (max - sum) / 2 + 2);
    }
}


Ashish has an array $$$a$$$ of consisting of $$$2n$$$ positive integers. He wants to compress $$$a$$$ into an array $$$b$$$ of size $$$n-1$$$. To do this, he first discards exactly $$$2$$$ (any two) elements from $$$a$$$. He then performs the following operation until there are no elements left in $$$a$$$:   Remove any two elements from $$$a$$$ and append their sum to $$$b$$$. The compressed array $$$b$$$ has to have a special property. The greatest common divisor ($$$\mathrm{gcd}$$$) of all its elements should be greater than $$$1$$$.Recall that the $$$\mathrm{gcd}$$$ of an array of positive integers is the biggest integer that is a divisor of all integers in the array.It can be proven that it is always possible to compress array $$$a$$$ into an array $$$b$$$ of size $$$n-1$$$ such that $$$gcd(b_1, b_2..., b_{n-1}) > 1$$$. Help Ashish find a way to do so.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int arr[2 * n];
    int check[2 * n];
    for (int i = 0; i < 2 * n; ++i) {
      check[i] = 0;
    }
    int parity[2 * n];
    int n_o = 0;
    int n_e = 0;
    for (int i = 0; i < 2 * n; ++i) {
      scanf("%d", &arr[i]);
      if (arr[i] % 2 == 0) {
        parity[i] = 0;

      } else {
        parity[i] = 1;
      }

      if (arr[i] % 2) {
        n_o++;
      } else {
        n_e++;
      }
    }

    if (n_o % 2 == 1) {
      for (int i = 0; i < 2 * n; ++i) {
        if (parity[i] && check[i] == 0) {

          check[i] = 1;
          n_o--;
          break;
        }
      }
      for (int i = 0; i < 2 * n; ++i) {
        if (parity[i] == 0 && check[i] == 0) {

          check[i] = 1;
          n_e--;
          break;
        }
      }

    } else {
      if (n_o) {
        for (int i = 0; i < 2 * n; ++i) {
          if (parity[i] && check[i] == 0) {

            check[i] = 1;
            n_o--;
            break;
          }
        }
        for (int i = 0; i < 2 * n; ++i) {
          if (parity[i] && check[i] == 0) {

            check[i] = 1;
            n_o--;
            break;
          }
        }
      } else {
        for (int i = 0; i < 2 * n; ++i) {
          if ((!parity[i]) && check[i] == 0) {

            check[i] = 1;
            n_e--;
            break;
          }
        }
        for (int i = 0; i < 2 * n; ++i) {
          if ((!parity[i]) && check[i] == 0) {

            check[i] = 1;
            n_e--;
            break;
          }
        }
      }
    }
    for (int j = 1; j <= n_e / 2; ++j) {
      for (int i = 0; i < 2 * n; ++i) {
        if (parity[i] == 0 && check[i] == 0) {
          printf("%d ", i + 1);
          check[i] = 1;
          break;
        }
      }
      for (int i = 0; i < 2 * n; ++i) {
        if (parity[i] == 0 && check[i] == 0) {
          printf("%d ", i + 1);
          check[i] = 1;
          break;
        }
      }
      printf("\n");
    }
    for (int j = 1; j <= n_o / 2; ++j) {
      for (int i = 0; i < 2 * n; ++i) {
        if (parity[i] != 0 && check[i] == 0) {
          printf("%d ", i + 1);
          check[i] = 1;
          break;
        }
      }
      for (int i = 0; i < 2 * n; ++i) {
        if (parity[i] != 0 && check[i] == 0) {
          printf("%d ", i + 1);
          check[i] = 1;
          break;
        }
      }
      printf("\n");
    }
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let _: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let evens: Vec<(usize, usize)> = xs
            .iter()
            .cloned()
            .enumerate()
            .filter(|x| x.1 % 2 == 0)
            .collect();
        let odds: Vec<(usize, usize)> = xs
            .iter()
            .cloned()
            .enumerate()
            .filter(|x| x.1 % 2 == 1)
            .collect();
        if evens.len().is_multiple_of(2) {
            if !evens.is_empty() {
                for i in 1..(evens.len() / 2) {
                    println!("{} {}", evens[i * 2].0 + 1, evens[i * 2 + 1].0 + 1);
                }
                for i in 0..(odds.len() / 2) {
                    println!("{} {}", odds[i * 2].0 + 1, odds[i * 2 + 1].0 + 1);
                }
            } else {
                for i in 0..(evens.len() / 2) {
                    println!("{} {}", evens[i * 2].0 + 1, evens[i * 2 + 1].0 + 1);
                }
                for i in 1..(odds.len() / 2) {
                    println!("{} {}", odds[i * 2].0 + 1, odds[i * 2 + 1].0 + 1);
                }
            }
        } else {
            for i in 0..(evens.len() / 2) {
                println!("{} {}", evens[i * 2 + 1].0 + 1, evens[i * 2 + 2].0 + 1);
            }
            for i in 0..(odds.len() / 2) {
                println!("{} {}", odds[i * 2 + 1].0 + 1, odds[i * 2 + 2].0 + 1);
            }
        }
    }
}


Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0.

int solution() {
  int n;
  int x;
  long long s = 0;
  long long min = 1e10;
  scanf("%d", &n);
  while (n--) {
    scanf("%d", &x);
    s += x;
    if (x & 1 && x < min) {
      min = x;
    }
  }
  if (s & 1) {
    s -= min;
  }
  printf("%lld\n", s);
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let n = s.trim().parse::<u64>().unwrap();
    s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let mut ints = s.split_whitespace().map(|x| x.parse::<u64>().unwrap());

    let mut odd_count = 0u64;
    let mut minodd = 1u64 << (64 - 1);
    let mut sum = 0u64;

    for _i in 0..n {
        let a = ints.next().unwrap();
        if a % 2 == 0 {
            sum += a;
        } else {
            odd_count = (odd_count + 1) % 2;
            if a < minodd {
                minodd = a;
            }
            sum += a;
        }
    }
    println!("{}", if odd_count == 1 { sum - minodd } else { sum });
}


Score : <var>500</var> points

Problem Statement

Let us denote by <var>f(x, m)</var> the remainder of the Euclidean division of <var>x</var> by <var>m</var>.

Let <var>A</var> be the sequence that is defined by the initial value <var>A_1=X</var> and the recurrence relation <var>A_{n+1} = f(A_n^2, M)</var>.
Find <var>\displaystyle{\sum_{i=1}^N A_i}</var>.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>X</var> <var>M</var>

Output

Print <var>\displaystyle{\sum_{i=1}^N A_i}</var>.

Sample Input 1

6 2 1001

Sample Output 1

1369

The sequence <var>A</var> begins <var>2,4,16,256,471,620,\ldots</var> Therefore, the answer is <var>2+4+16+256+471+620=1369</var>.

Sample Input 2

1000 2 16

Sample Output 2

6

The sequence <var>A</var> begins <var>2,4,0,0,\ldots</var> Therefore, the answer is <var>6</var>.

Sample Input 3

10000000000 10 99959

Sample Output 3

492443256176507

int solution(void) {

  long long N;
  long long X;
  long long M;

  scanf("%lld%lld%lld", &N, &X, &M);

  long long c[M];

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

  long long x = X;
  long long f = 0;
  long long t = 0;
  long long a = 1;
  long long s;

  while (1) {
    if (c[x % M] > 0) {
      t = a - 1;
      s = x % M;
      break;
    }
    a++;
    c[x % M] = 1;
    x = (x * x) % M;
  }

  long long y = X;
  a = 1;

  while (1) {
    if (y % M == s) {
      f = a - 1;
      break;
    }
    a++;
    y = (y * y) % M;
  }

  long long ans = 0;

  for (long long i = 0; i < f; i++) {
    ans += X % M;
    X = (X * X) % M;
  }

  long long z = X;

  long long k = 0;
  for (long long i = f; i < t; i++) {
    k += X % M;
    X = (X * X) % M;
  }

  ans += k * ((N - f) / (t - f));

  for (long long j = 1; j <= (N - f) % (t - f); j++) {
    ans += z % M;
    z = (z * z) % M;
  }

  printf("%lld\n", ans);

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

    let mut used: Vec<bool> = vec![false; m];
    let mut cycle: Vec<usize> = vec![];

    let mut start = 0;
    let mut now = x;
    for _ in 0..n {
        used[now] = true;
        cycle.push(now);
        now = now * now % m;
        if used[now] {
            for j in 0..cycle.len() {
                if cycle[j] == now {
                    start = j;
                    break;
                }
            }
            break;
        }
    }

    let mut s1 = 0;
    let mut s2 = 0;
    let len = cycle.len() - start;
    for i in 0..start {
        s1 += cycle[i];
    }
    for i in start..cycle.len() {
        s2 += cycle[i];
    }

    let mut ans = s1 + (n - start) / len * s2;
    for _ in 0..(n - start) % len {
        ans += now;
        now = now * now % m;
    }
    println!("{}", ans);
}


The city where Mocha lives in is called Zhijiang. There are $$$n+1$$$ villages and $$$2n-1$$$ directed roads in this city. There are two kinds of roads:  $$$n-1$$$ roads are from village $$$i$$$ to village $$$i+1$$$, for all $$$1\leq i \leq n-1$$$.  $$$n$$$ roads can be described by a sequence $$$a_1,\ldots,a_n$$$. If $$$a_i=0$$$, the $$$i$$$-th of these roads goes from village $$$i$$$ to village $$$n+1$$$, otherwise it goes from village $$$n+1$$$ to village $$$i$$$, for all $$$1\leq i\leq n$$$. Mocha plans to go hiking with Taki this weekend. To avoid the trip being boring, they plan to go through every village exactly once. They can start and finish at any villages. Can you help them to draw up a plan?

int solution() {
  int t;
  int n[20];
  int one[20];
  int temp;

  scanf("%d", &t);

  for (int i = 0; i < t; i++) {
    int got_one = 0;
    scanf("%d", &n[i]);
    one[i] = n[i];
    for (int j = 0; j < n[i]; j++) {

      scanf("%d", &temp);

      if (temp == 1 && got_one == 0) {
        one[i] = j;
        got_one = 1;
      }
    }
  }

  for (int i = 0; i < t; i++) {
    int gone_n = 0;
    for (int j = 0; j < n[i]; j++) {
      if (gone_n == 0 && j == one[i]) {
        printf("%d ", n[i] + 1);
        j--;
        gone_n = 1;
      } else {
        printf("%d ", j + 1);
      }
    }
    if (gone_n == 0) {
      printf("%d ", n[i] + 1);
    }
    printf("\n");
  }

  return 0;
}

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

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

    let mut lines = input.lines().map(|r| r.unwrap());
    let t = lines.next().unwrap().parse::<usize>().unwrap();

    'cases: for _ in 0..t {
        let n = lines.next().unwrap().parse::<usize>().unwrap();
        let s = lines.next().unwrap();

        let a: Vec<_> = s.split_whitespace().map(|s| s == "1").collect();

        if a.first().cloned().unwrap() {
            write!(&mut output, "{}", n + 1).unwrap();
            for i in 1..=n {
                write!(&mut output, " {}", i).unwrap()
            }
        } else if !a.last().cloned().unwrap() {
            for i in 1..=n {
                write!(&mut output, "{} ", i).unwrap()
            }
            write!(&mut output, "{}", n + 1).unwrap();
        } else {
            let i = a.into_iter().position(|x| x).unwrap();
            for j in 0..i {
                write!(&mut output, "{} ", j + 1).unwrap()
            }
            write!(&mut output, "{}", n + 1).unwrap();
            for j in i..n {
                write!(&mut output, " {}", j + 1).unwrap();
            }
        }

        writeln!(&mut output).unwrap();
    }
}


You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times:  Select an index $$$i$$$ ($$$1\leq i\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i. e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero).

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let t: i32 = line.trim().parse().unwrap();
    for _i in 0..t {
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let _n: i32 = line.trim().parse().unwrap();
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let a: Vec<i32> = line
            .split_ascii_whitespace()
            .map(|t| t.parse().unwrap())
            .collect();
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let b: Vec<i32> = line
            .split_ascii_whitespace()
            .map(|t| t.parse().unwrap())
            .collect();
        let c = a.iter().zip(b.iter()).map(|(x, y)| x.max(y)).max().unwrap();
        let d = a.iter().zip(b.iter()).map(|(x, y)| x.min(y)).max().unwrap();
        println!("{}", c * d);
    }
}


You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$:  Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \le i, j \le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$.  Select any arbitrary index $$$i$$$ ($$$1 \le i \le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.

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

    handle.read_to_string(&mut buffer).expect("stdin");

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

    let _n = *arr.get(0).unwrap();

    let s1 = arr.get(1).unwrap().chars().collect::<Vec<_>>();
    let s2 = arr.get(2).unwrap().chars().collect::<Vec<_>>();

    let mut dp = vec![0];
    for (i, v) in s1.iter().enumerate() {
        if s2[i] != *v {
            let val = *dp.last().unwrap() + 1;
            dp.push(val);
        } else {
            let val = *dp.last().unwrap();
            dp.push(val);
        }

        if i >= 1 && s1[i - 1] == s2[i] && s1[i] == s2[i - 1] {
            let index_one_based = i + 1;
            use std::cmp;
            dp[index_one_based] = cmp::min(dp[index_one_based - 2] + 1, dp[index_one_based]);
        }
    }

    let ans = *dp.last().unwrap();

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


Score : <var>300</var> points

Problem Statement

There are <var>N</var> people standing in a row from west to east.
Each person is facing east or west.
The directions of the people is given as a string <var>S</var> of length <var>N</var>.
The <var>i</var>-th person from the west is facing east if <var>S_i =</var> E, and west if <var>S_i =</var> W.

You will appoint one of the <var>N</var> people as the leader, then command the rest of them to face in the direction of the leader.
Here, we do not care which direction the leader is facing.

The people in the row hate to change their directions, so you would like to select the leader so that the number of people who have to change their directions is minimized.
Find the minimum number of people who have to change their directions.

Constraints

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

<var>|S| = N</var>

<var>S_i</var> is E or W.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum number of people who have to change their directions.

Sample Input 1

5
WEEWW

Sample Output 1

1

Assume that we appoint the third person from the west as the leader.
Then, the first person from the west needs to face east and has to turn around.
The other people do not need to change their directions, so the number of people who have to change their directions is <var>1</var> in this case.
It is not possible to have <var>0</var> people who have to change their directions, so the answer is <var>1</var>.

Sample Input 2

12
WEWEWEEEWWWE

Sample Output 2

4

Sample Input 3

8
WWWWWEEE

Sample Output 3

3

int solution() {
  int Num = 0;
  char chara[3 * 100000];
  int Sum[3 * 100000] = {0};
  scanf("%d", &Num);
  scanf("%s", chara);
  for (int i = 0; i < Num; i++) {
    if (i == 0) {
      for (int j = 1; j < Num; j++) {
        if (chara[j] == 'E') {
          Sum[i]++;
        }
      }
    } else {
      Sum[i] = Sum[i - 1];
      if (chara[i - 1] == 'W') {
        Sum[i]++;
      }
      if (chara[i] == 'E') {
        Sum[i]--;
      }
    }
  }

  int minimum = 3 * 100000;

  for (int i = 0; i < Num; i++) {
    if (minimum > Sum[i]) {
      minimum = Sum[i];
    }
  }
  printf("%d\n", minimum);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let _: usize = buf.trim().parse().unwrap();
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut s = buf.trim().chars().collect::<Vec<_>>();

    let mut east_cost = vec![0];
    let mut west_cost = vec![0];

    let mut cost = 0;
    for &c in &s {
        if c == 'W' {
            cost += 1;
        }
        east_cost.push(cost);
    }
    cost = 0;
    s.reverse();
    for &c in &s {
        if c == 'E' {
            cost += 1;
        }
        west_cost.push(cost);
    }
    east_cost.pop();
    west_cost.pop();
    west_cost.reverse();
    println!(
        "{}",
        east_cost
            .iter()
            .zip(west_cost.iter())
            .map(|(a, b)| a + b)
            .min()
            .unwrap()
    );
}


Once upon a time there was only one router in the well-known company Bmail. Years went by and over time new routers were purchased. Every time they bought a new router, they connected it to one of the routers bought before it. You are given the values $$$p_i$$$ — the index of the router to which the $$$i$$$-th router was connected after being purchased ($$$p_i < i$$$).There are $$$n$$$ routers in Boogle in total now. Print the sequence of routers on the path from the first to the $$$n$$$-th router.

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

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

  int k = n;
  int way[n + 1];

  for (int i = 1; i <= n; i++) {
    way[i] = 0;
  }

  while (k != 1) {
    way[k] = 1;

    k = a[k];
  }

  way[1] = 1;

  for (int i = 1; i <= n; i++) {
    if (way[i] == 1) {
      printf("%d ", i);
    }
  }

  return 0;
}

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

    handle.read_to_string(&mut buffer).expect("stdin");

    let arr: Vec<_> = buffer.split_whitespace().collect();
    let n = arr[0].parse::<usize>().unwrap();
    let mut p: [usize; 200010] = [0; 200010];
    for i in 2..=n {
        p[i] = arr[i - 1].parse::<usize>().unwrap();
    }
    let mut x: usize = n;
    let mut buf: VecDeque<usize> = VecDeque::new();
    buf.push_front(x);
    while x != 1 {
        x = p[x];
        buf.push_front(x);
    }
    for i in buf.iter() {
        println!("{}", *i);
    }
}


We have a point $$$A$$$ with coordinate $$$x = n$$$ on $$$OX$$$-axis. We'd like to find an integer point $$$B$$$ (also on $$$OX$$$-axis), such that the absolute difference between the distance from $$$O$$$ to $$$B$$$ and the distance from $$$A$$$ to $$$B$$$ is equal to $$$k$$$.  The description of the first test case. Since sometimes it's impossible to find such point $$$B$$$, we can, in one step, increase or decrease the coordinate of $$$A$$$ by $$$1$$$. What is the minimum number of steps we should do to make such point $$$B$$$ exist?

fn solution() {
    let mut inp = String::new();
    io::stdin().read_line(&mut inp).expect("Input Error");
    let t: u32 = inp.trim().parse().expect("Input Error");
    for _ in 0..t {
        inp = String::new();
        io::stdin().read_line(&mut inp).expect("Input Error");
        let v: Vec<&str> = inp.trim().split(' ').collect();
        let n: u32 = v[0].parse().expect("Error");
        let k: u32 = v[1].parse().expect("Error");
        if n < k {
            println!("{}", k - n);
        } else if (n + k).is_multiple_of(2) {
            println!("{}", 0);
        } else {
            println!("{}", 1);
        }
    }
}


You are given a number $$$n$$$ (divisible by $$$3$$$) and an array $$$a[1 \dots n]$$$. In one move, you can increase any of the array elements by one. Formally, you choose the index $$$i$$$ ($$$1 \le i \le n$$$) and replace $$$a_i$$$ with $$$a_i + 1$$$. You can choose the same index $$$i$$$ multiple times for different moves.Let's denote by $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ the number of numbers from the array $$$a$$$ that have remainders $$$0$$$, $$$1$$$ and $$$2$$$ when divided by the number $$$3$$$, respectively. Let's say that the array $$$a$$$ has balanced remainders if $$$c_0$$$, $$$c_1$$$ and $$$c_2$$$ are equal.For example, if $$$n = 6$$$ and $$$a = [0, 2, 5, 5, 4, 8]$$$, then the following sequence of moves is possible:   initially $$$c_0 = 1$$$, $$$c_1 = 1$$$ and $$$c_2 = 4$$$, these values are not equal to each other. Let's increase $$$a_3$$$, now the array $$$a = [0, 2, 6, 5, 4, 8]$$$;  $$$c_0 = 2$$$, $$$c_1 = 1$$$ and $$$c_2 = 3$$$, these values are not equal. Let's increase $$$a_6$$$, now the array $$$a = [0, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 3$$$, $$$c_1 = 1$$$ and $$$c_2 = 2$$$, these values are not equal. Let's increase $$$a_1$$$, now the array $$$a = [1, 2, 6, 5, 4, 9]$$$;  $$$c_0 = 2$$$, $$$c_1 = 2$$$ and $$$c_2 = 2$$$, these values are equal to each other, which means that the array $$$a$$$ has balanced remainders. Find the minimum number of moves needed to make the array $$$a$$$ have balanced remainders.

int solution() {
  int t = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    scanf("%d", &n);

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

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

    if (remainders[0] > n / 3) {
      count = count + remainders[0] - (n / 3);

      remainders[1] += (remainders[0] - n / 3);
      remainders[0] = n / 3;
    }
    if (remainders[1] > n / 3) {
      count += (remainders[1] - n / 3);

      remainders[2] += (remainders[1] - n / 3);
      remainders[1] = n / 3;
    }
    if (remainders[2] > n / 3) {
      count += (remainders[2] - n / 3);

      remainders[0] += (remainders[2] - n / 3);
      remainders[2] = n / 3;
    }
    if (remainders[0] > n / 3) {
      count += (remainders[0] - n / 3);

      remainders[1] += (remainders[0] - n / 3);
      remainders[0] = n / 3;
    }
    printf("%d\n", count);
  }
}

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

    let tc: usize = sc.next();
    for _ in 0..tc {
        let n: usize = sc.next();
        let mut c: Vec<usize> = vec![0, 0, 0];
        (0..n).for_each(|_| c[sc.next::<usize>() % 3] += 1);
        let x: usize = n / 3;
        let mut ans: usize = 0;

        for i in 0..6 {
            let a = min(c[i % 3], x);
            ans += c[i % 3] - a;
            c[(i + 1) % 3] += c[i % 3] - a;
            c[i % 3] = a;
        }
        writeln!(out, "{}", ans).unwrap();
    }
}


How many ways?

  Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to <var>n</var>.

A total sum of the three integers is <var>x</var>.

  For example, there are two combinations for <var>n</var> = 5 and <var>x</var> = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

  The input consists of multiple datasets. For each dataset, two integers <var>n</var> and <var>x</var> are given in a line.

  The input ends with two zeros for <var>n</var> and <var>x</var> respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ <var>n</var> ≤ 100

0 ≤ <var>x</var> ≤ 300

Output

  For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説

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

        let mut iter = line.split_whitespace().map(|i| i.parse::<i32>().unwrap());
        let n = iter.next().unwrap();
        let x = iter.next().unwrap();

        if n == 0 && x == 0 {
            break;
        }

        let combos = (1..n - 1)
            .flat_map(|a| (a + 1..n).flat_map(move |b| (b + 1..n + 1).map(move |c| (a, b, c))))
            .filter(|&(a, b, c)| a + b + c == x);

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


Score : <var>400</var> points

Problem Statement

Give a pair of integers <var>(A, B)</var> such that <var>A^5-B^5 = X</var>.
It is guaranteed that there exists such a pair for the given integer <var>X</var>.

Constraints

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

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

There exists a pair of integers <var>(A, B)</var> satisfying the condition in Problem Statement.

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

Print <var>A</var> and <var>B</var>, with space in between.
If there are multiple pairs of integers <var>(A, B)</var> satisfying the condition, you may print any of them.

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

Sample Input 1

33

Sample Output 1

2 -1

For <var>A=2</var> and <var>B=-1</var>, <var>A^5-B^5 = 33</var>.

Sample Input 2

1

Sample Output 2

0 -1

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

  for (long long a = 0; a >= 0; a++) {
    if (a < 64) {
      for (long long b = -64; b <= a; b++) {
        if (a * a * a * a * a - b * b * b * b * b == x) {
          printf("%lld %lld", a, b);
          return 0;
        }
      }
    }
    if (a >= 64) {
      for (long long b = 1; b <= 2 * a; b++) {
        if (a * a * a * a * a - b * b * b * b * b == x) {
          printf("%lld %lld", a, b);
          return 0;
        }
      }
    }
  }
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let x: i128 = s.trim().parse().unwrap();

    'outer: for i in -10000i128..=10000 {
        let mut l: i128 = -10000;
        let mut r: i128 = 10000;
        let mut m: i128;
        while l < r {
            m = (l + r) / 2;
            let t = i.pow(5) - m.pow(5);
            if t == x {
                println!("{} {}", i, m);

                break 'outer;
            } else if m == r || m == l {
                break;
            } else if t < x {
                r = m;
            } else {
                l = m;
            }
        }
    }
}


This problem is interactive.We decided to play a game with you and guess the number $$$x$$$ ($$$1 \le x < n$$$), where you know the number $$$n$$$.You can make queries like this: + c: this command assigns $$$x = x + c$$$ ($$$1 \le c < n$$$) and then returns you the value $$$\lfloor\frac{x}{n}\rfloor$$$ ($$$x$$$ divide by $$$n$$$ and round down).You win if you guess the current number with no more than $$$10$$$ queries.

int solution() {
  int i;
  int n;
  int ask;
  int ans1;
  int ans2;
  int lower;
  int upper;
  int middle;
  int sum;
  scanf("%d", &n);
  lower = 1;
  upper = n;
  ans1 = sum = 0;
  for (i = 0; i < 11; i++) {
    if (upper == lower + 1) {
      printf("! %d\n", lower + sum);
      fflush(stdout);
      break;
    }

    middle = (upper + lower) / 2;
    ask = (ans1 + 1) * n - sum - middle;
    sum += ask;

    printf("+ %d\n", ask);
    fflush(stdout);
    scanf("%d", &ans2);
    if (ans2 == ans1 + 1) {
      lower = middle;
    } else {
      upper = middle;
    }
    ans1 = ans2;
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n = lines.next().unwrap().unwrap().parse::<i32>().unwrap();
    let mut pre_num = 0;
    let mut candinates: Vec<i32> = (1..n).collect::<Vec<_>>();
    loop {
        if candinates.len() == 1 {
            println!("! {}", candinates[0]);
            break;
        }
        let mid = candinates.len() / 2;
        let add_num = n - (candinates[mid] % n);
        println!("+ {}", add_num);
        io::stdout().flush().unwrap();
        let round_num = lines.next().unwrap().unwrap().parse::<i32>().unwrap();
        let size = candinates.len();
        if round_num == pre_num {
            candinates = candinates[0..(size / 2)].to_vec();
        } else if round_num == pre_num + 1 {
            candinates = candinates[(size / 2)..].to_vec();
            pre_num = round_num;
        }
        candinates
            .iter_mut()
            .for_each(|canndinate| *canndinate += add_num);
    }
}


AquaMoon has two binary sequences $$$a$$$ and $$$b$$$, which contain only $$$0$$$ and $$$1$$$. AquaMoon can perform the following two operations any number of times ($$$a_1$$$ is the first element of $$$a$$$, $$$a_2$$$ is the second element of $$$a$$$, and so on): Operation 1: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{min}(a_1,a_2)$$$, and remove the first element of $$$a$$$. Operation 2: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{max}(a_1,a_2)$$$, and remove the first element of $$$a$$$.Note that after a removal of the first element of $$$a$$$, the former $$$a_2$$$ becomes the first element of $$$a$$$, the former $$$a_3$$$ becomes the second element of $$$a$$$ and so on, and the length of $$$a$$$ reduces by one.Determine if AquaMoon can make $$$a$$$ equal to $$$b$$$ by using these operations.

int solution() {
  int t;
  int m;
  int n;
  scanf("%d", &t);
  while (t--) {
    scanf("%d %d", &n, &m);
    char a[n + 1];
    char b[m + 1];
    scanf("%s", a);
    scanf("%s", b);
    int j = n - 1;
    int last_equal = 1;
    for (int i = m - 1; i > 0; i--) {
      if (b[i] != a[j--]) {
        last_equal = 0;
        break;
      }
    }
    int first_equal = 0;
    for (int i = 0; i < n - m + 1; i++) {
      if (a[i] == b[0]) {
        first_equal = 1;
        break;
      }
    }
    if (first_equal == 1 && last_equal == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let input = stdin();
    let mut line = String::new();
    let mut res: Vec<String> = vec![];

    let _ = input.read_line(&mut line);
    let num: i32 = line.trim().parse().unwrap();
    for _ in 0..num {
        let mut line = String::new();
        let _ = input.read_line(&mut line);
        let mut a = String::new();
        let mut b = String::new();
        let _ = input.read_line(&mut a);
        let _ = input.read_line(&mut b);
        a = a.trim().to_string();
        b = b.trim().to_string();
        let mut condition: bool = false;
        while a.len() >= b.len() {
            if b == a {
                condition = true;
                break;
            }
            let c: char;
            if a.chars().next().unwrap() == b.chars().next().unwrap() {
                c = a.chars().next().unwrap();
            } else {
                if a.len() <= 1 {
                    break;
                }
                c = a.chars().nth(1).unwrap();
            }
            if a.len() >= 2 {
                a = a[2..].to_string();
            } else if a.len() == 1 {
                a = a[1..].to_string();
            } else {
                break;
            }
            a.insert(0, c);
        }
        if condition {
            res.push("YES".to_string());
        } else {
            res.push("NO".to_string());
        }
    }
    for word in res {
        println!("{}", word)
    }
}


気象予報士 (Weather Forecaster)

問題

JOI 市は南北方向に H キロメートル，東西方向に W キロメートルの長方形の形をしており，H × W 個の 1 キロメートル四方の小区画に区切られている．北から i 番目，西から j 番目の小区画を (i, j) と表す．

各小区画は上空に雲があるか雲がないかのどちらかである．すべての雲は，1 分経つごとに 1 キロメートル東に移動する．今日は実に天気が良いため，JOI 市の外から JOI 市内に雲が移動してくることはない．

今，各小区画の上空に雲があるかないかがわかっている．気象予報士であるあなたは，各小区画について，今から何分後に初めてその小区画の上空に雲が来るかを予測することになった．

各小区画について，今から何分後に初めてその小区画の上空に雲が来るか求めよ．

入力

入力は 1 + H 行からなる．

1 行目には，整数 H, W (1 ≤ H ≤ 100, 1 ≤ W ≤ 100) が空白を区切りとして書かれている．これは，JOI 市が H × W 個の 1 キロメートル四方の小区画に区切られていることを表す．

続く H 行のうちの i 行目 (1 ≤ i ≤ H) には W 文字からなる文字列が書かれている．W 文字のうちの j 文字目 (1 ≤ j ≤ W) は，小区画 (i, j) の上空に，今，雲があるかどうかを表す．雲がある場合は文字 'c' (英小文字) が，雲がない場合は文字 '.' (ピリオド) が書かれている．

出力

出力は H 行からなり，それぞれの行は空白を区切りとした W 個の整数からなる．出力の i 行目の j 番目の整数 (1 ≤ i ≤ H, 1 ≤ j ≤ W) は，今から何分後に初めて小区画 (i, j) の上空に雲が来るかを表さなければならない．ただし，今すでに小区画 (i, j) の上空に雲がある場合は 0 を，何分経っても小区画 (i, j) の上空に雲が来ない場合は -1 を出力せよ．

出力の各行の行頭と行末には余計な空白を入れないこと．

入出力例

入力例 1

3 4
c..c
..c.
....

出力例 1

0 1 2 0
-1 -1 0 1
-1 -1 -1 -1

入力例 2

6 8
.c......
........
.ccc..c.
....c...
..c.cc..
....c...

出力例 2

-1 0 1 2 3 4 5 6
-1 -1 -1 -1 -1 -1 -1 -1
-1 0 0 0 1 2 0 1
-1 -1 -1 -1 0 1 2 3
-1 -1 0 1 0 0 1 2
-1 -1 -1 -1 0 1 2 3

入出力例 1 では，JOI 市は 3 × 4 個の小区画に区切られている．今の JOI 市の雲の状況は以下の通りである．図の上が北を表す．

この後，1 分ごとに雲は以下のように移動する．

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

int solution(void) {
  int H;
  int W;
  scanf("%d %d\n", &H, &W);

  char weather;

  int i;
  int j;
  for (i = 0; i < H; ++i) {
    scanf("%c", &weather);

    int out = -1;
    for (j = 1; j <= W; ++j) {
      if (weather == 'c') {
        out = 0;
      }

      else {
        ++out;

        if (out < 1) {
          out = -1;
        }
      }

      printf("%d", out);

      if (j == W) {
        printf("\n");
      } else {
        printf(" ");
      }

      scanf("%c", &weather);
    }
  }

  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 (h, w) = {
        let line = lines.next().unwrap();
        let mut iter = line.split(' ').map(|s| s.parse::<usize>().unwrap());

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

    let mut result = String::with_capacity(h * w * 3);

    for line in lines.take(h) {
        let mut cnt = -1;

        for ch in line.bytes() {
            if ch == b'c' {
                cnt = 0;
                result.push_str("0 ");
            } else {
                if cnt == -1 {
                    result.push_str("-1 ");
                } else {
                    cnt += 1;
                    write!(result, "{} ", cnt);
                }
            }
        }
        result.pop();
        result.push('\n');
    }
    print!("{}", result);
}


Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    long long a[n];
    long long sum = 0;
    for (int i = 0; i < n; i++) {
      scanf("%lld", &a[i]);
      sum += a[i];
    }
    long long rest = sum % n;
    printf("%lld\n", rest * (n - rest) < rest * (n - 1) ? rest * (n - rest)
                                                        : rest * (n - 1));
  }
}

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();

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

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

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

        let s = it.sum::<u64>();

        let x = s % n;

        let ans = x * (n - x);

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


In the $$$2022$$$ year, Mike found two binary integers $$$a$$$ and $$$b$$$ of length $$$n$$$ (both of them are written only by digits $$$0$$$ and $$$1$$$) that can have leading zeroes. In order not to forget them, he wanted to construct integer $$$d$$$ in the following way:   he creates an integer $$$c$$$ as a result of bitwise summing of $$$a$$$ and $$$b$$$ without transferring carry, so $$$c$$$ may have one or more $$$2$$$-s. For example, the result of bitwise summing of $$$0110$$$ and $$$1101$$$ is $$$1211$$$ or the sum of $$$011000$$$ and $$$011000$$$ is $$$022000$$$;  after that Mike replaces equal consecutive digits in $$$c$$$ by one digit, thus getting $$$d$$$. In the cases above after this operation, $$$1211$$$ becomes $$$121$$$ and $$$022000$$$ becomes $$$020$$$ (so, $$$d$$$ won't have equal consecutive digits). Unfortunately, Mike lost integer $$$a$$$ before he could calculate $$$d$$$ himself. Now, to cheer him up, you want to find any binary integer $$$a$$$ of length $$$n$$$ such that $$$d$$$ will be maximum possible as integer.Maximum possible as integer means that $$$102 > 21$$$, $$$012 < 101$$$, $$$021 = 21$$$ and so on.

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

    let mut out = BufWriter::new(stdout());

    for _i in 0..t {
        let mut n = String::new();
        let mut b = String::new();

        stdin().read_line(&mut n).unwrap();
        stdin().read_line(&mut b).unwrap();
        let b = b.trim();
        let mut a = String::new();

        let mut before = 3;
        for i in b.chars() {
            if i == '0' {
                if before != 1 {
                    a.push('1');
                    before = 1;
                } else {
                    a.push('0');
                    before = 0;
                }
            } else {
                if before != 2 {
                    a.push('1');
                    before = 2;
                } else {
                    a.push('0');
                    before = 1;
                }
            }
        }
        writeln!(out, "{}", a).unwrap();
    }
}


Score : <var>100</var> points

Problem Statement

Shichi-Go-San (literally "Seven-Five-Three") is a traditional event in a certain country to celebrate the growth of seven-, five- and three-year-old children.

Takahashi is now <var>X</var> years old. Will his growth be celebrated in Shichi-Go-San this time?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

If Takahashi's growth will be celebrated, print YES; if it will not, print NO.

Sample Input 1

5

Sample Output 1

YES

The growth of a five-year-old child will be celebrated.

Sample Input 2

6

Sample Output 2

NO

See you next year.

fn solution() {
    let mut x = String::new();
    stdin().read_line(&mut x).unwrap();
    println!(
        "{}",
        match x.trim() {
            "7" | "5" | "3" => "YES",
            _ => "NO",
        }
    );
}