There are $$$n$$$ logs, the $$$i$$$-th log has a length of $$$a_i$$$ meters. Since chopping logs is tiring work, errorgorn and maomao90 have decided to play a game.errorgorn and maomao90 will take turns chopping the logs with errorgorn chopping first. On his turn, the player will pick a log and chop it into $$$2$$$ pieces. If the length of the chosen log is $$$x$$$, and the lengths of the resulting pieces are $$$y$$$ and $$$z$$$, then $$$y$$$ and $$$z$$$ have to be positive integers, and $$$x=y+z$$$ must hold. For example, you can chop a log of length $$$3$$$ into logs of lengths $$$2$$$ and $$$1$$$, but not into logs of lengths $$$3$$$ and $$$0$$$, $$$2$$$ and $$$2$$$, or $$$1.5$$$ and $$$1.5$$$.The player who is unable to make a chop will be the loser. Assuming that both errorgorn and maomao90 play optimally, who will be the winner?

int solution() {
  int n = 0;
  int m = 0;
  int x[100];
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &m);
    for (int f = 0; f < m; f++) {
      scanf("%d", &x[f]);
    }

    int count = 0;
    for (int k = 0; k < m; k++) {
      if (x[k] != 1) {
        count += x[k] - 1;
      }
    }

    if (count % 2 == 0) {
      printf("maomao90\n");
    } else {
      printf("errorgorn\n");
    }
  }
  return 0;
}

fn solution() {
    let mut str: String = String::new();
    io::stdin()
        .read_line(&mut str)
        .expect("failed to read input");
    let t: usize = str.trim().parse::<usize>().expect("could not parse T");
    let mut arr: [u32; 105] = [0; 105];
    for _t in 0..t {
        str.clear();
        io::stdin().read_line(&mut str).expect("failed to read n");
        let n: usize = str.trim().parse::<usize>().expect("could not parse n");
        str.clear();
        io::stdin().read_line(&mut str).expect("");
        let ok = str.split(' ');
        let mut idx: usize = 0;
        for val in ok {
            arr[idx] = val.trim().parse::<u32>().expect("could not parse value");
            idx += 1;
        }

        let mut res: u32 = 0;
        for i in 0..n {
            res ^= arr[i] - 1;
        }
        if res.is_multiple_of(2) {
            println!("maomao90");
        } else {
            println!("errorgorn");
        }
    }
}


Score : <var>200</var> points

Problem Statement

In Japan, people make offerings called hina arare, colorful crackers, on March <var>3</var>.

We have a bag that contains <var>N</var> hina arare. (From here, we call them arare.)

It is known that the bag either contains arare in three colors: pink, white and green, or contains arare in four colors: pink, white, green and yellow.

We have taken out the arare in the bag one by one, and the color of the <var>i</var>-th arare was <var>S_i</var>, where colors are represented as follows - pink: P, white: W, green: G, yellow: Y.

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Constraints

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

<var>S_i</var> is P, W, G or Y.

There always exist <var>i</var>, <var>j</var> and <var>k</var> such that <var>S_i=</var>P, <var>S_j=</var>W and <var>S_k=</var>G.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var> <var>S_2</var> <var>...</var> <var>S_N</var>

Output

If the number of colors of the arare in the bag was three, print Three; if the number of colors was four, print Four.

Sample Input 1

6
G W Y P Y W

Sample Output 1

Four

The bag contained arare in four colors, so you should print Four.

Sample Input 2

9
G W W G P W P G G

Sample Output 2

Three

The bag contained arare in three colors, so you should print Three.

Sample Input 3

8
P Y W G Y W Y Y

Sample Output 3

Four

int solution(void) {

  int n = 0;
  char hina[101] = {0};
  int i = 0;
  int cnt = 0;

  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%c", hina + i);
  }
  i = 0;

  while (hina[i] != '\0') {
    if (hina[i] == 'Y') {
      cnt++;
    }
    i++;
  }

  if (cnt > 0) {
    printf("Four\n");
  } else {
    printf("Three\n");
  }

  return 0;
}

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

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

    let mut hn = [false; 4];
    for s in buf.trim().split(' ') {
        match s {
            "P" => hn[0] = true,
            "W" => hn[1] = true,
            "G" => hn[2] = true,
            "Y" => hn[3] = true,
            _ => (),
        }
    }

    if hn.iter().all(|&x| x) {
        println!("Four");
        return;
    }
    println!("Three");
}


Score : <var>300</var> points

Problem Statement

Given an integer <var>N</var>, find the base <var>-2</var> representation of <var>N</var>.

Here, <var>S</var> is the base <var>-2</var> representation of <var>N</var> when the following are all satisfied:

<var>S</var> is a string consisting of 0 and 1.

Unless <var>S =</var> 0, the initial character of <var>S</var> is 1.

Let <var>S = S_k S_{k-1} ... S_0</var>, then <var>S_0 \times (-2)^0 + S_1 \times (-2)^1 + ... + S_k \times (-2)^k = N</var>.

It can be proved that, for any integer <var>M</var>, the base <var>-2</var> representation of <var>M</var> is uniquely determined.

Constraints

Every value in input is integer.

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the base <var>-2</var> representation of <var>N</var>.

Sample Input 1

-9

Sample Output 1

1011

As <var>(-2)^0 + (-2)^1 + (-2)^3 = 1 + (-2) + (-8) = -9</var>, 1011 is the base <var>-2</var> representation of <var>-9</var>.

Sample Input 2

123456789

Sample Output 2

11000101011001101110100010101

Sample Input 3

0

Sample Output 3

0

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let mut n: i32 = s.trim().parse().unwrap();
    if n == 0 {
        println!("0");
    } else {
        let mut ans = vec![];
        while n != 0 {
            ans.push(if n & 1 != 0 { '1' } else { '0' });
            n = (n & !1) / -2;
        }
        println!("{}", ans.into_iter().rev().collect::<String>());
    }
}


Petya has got an interesting flower. Petya is a busy person, so he sometimes forgets to water it. You are given $$$n$$$ days from Petya's live and you have to determine what happened with his flower in the end.The flower grows as follows:   If the flower isn't watered for two days in a row, it dies.  If the flower is watered in the $$$i$$$-th day, it grows by $$$1$$$ centimeter.  If the flower is watered in the $$$i$$$-th and in the $$$(i-1)$$$-th day ($$$i > 1$$$), then it grows by $$$5$$$ centimeters instead of $$$1$$$.  If the flower is not watered in the $$$i$$$-th day, it does not grow. At the beginning of the $$$1$$$-st day the flower is $$$1$$$ centimeter tall. What is its height after $$$n$$$ days?

int solution() {
  int t;
  int n;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    scanf("%d", &n);
    int a[n];
    int height = 1;
    for (int j = 0; j < n; j++) {
      scanf("%d", &a[j]);
      if (j > 0 && a[j] == 0 && a[j - 1] == 0) {
        height = -1;
        while (++j < n) {
          scanf("%d", &a[j]);
        }
        break;
      }
      if (j > 0 && a[j] == 1 && a[j - 1] == 1) {
        height += 5;
      } else if (a[j] == 1) {
        height += 1;
      }
    }
    printf("%d\n", height);
  }
  return 0;
}

fn solution() {
    let mut handle = std::io::BufWriter::new(std::io::stdout());
    let mut test_no = String::new();
    std::io::stdin().read_line(&mut test_no).unwrap();
    let test_no: u8 = test_no.trim().parse().unwrap();
    for _ in 0..test_no {
        let mut array_size = String::new();
        std::io::stdin().read_line(&mut array_size).unwrap();
        let array_size: u8 = array_size.trim().parse().unwrap();
        let mut array = String::new();
        std::io::stdin().read_line(&mut array).unwrap();
        let array: Vec<&str> = array.trim().split(' ').collect();
        let array: Vec<u8> = array.iter().map(|x| x.parse::<u8>().unwrap()).collect();
        let mut height: i16 = 1;
        if array[0] == 1 {
            height += 1
        }
        for i in 1..array_size {
            if array[i as usize] == 0 && array[(i - 1) as usize] == 0 {
                height = -1;
                break;
            } else if array[i as usize] == 1 {
                if array[(i - 1) as usize] == 1 {
                    height += 5;
                } else {
                    height += 1;
                }
            }
        }
        writeln!(handle, "{}", height).ok();
    }
}


Bob is a competitive programmer. He wants to become red, and for that he needs a strict training regime. He went to the annual meeting of grandmasters and asked $$$n$$$ of them how much effort they needed to reach red."Oh, I just spent $$$x_i$$$ hours solving problems", said the $$$i$$$-th of them. Bob wants to train his math skills, so for each answer he wrote down the number of minutes ($$$60 \cdot x_i$$$), thanked the grandmasters and went home. Bob could write numbers with leading zeroes — for example, if some grandmaster answered that he had spent $$$2$$$ hours, Bob could write $$$000120$$$ instead of $$$120$$$.Alice wanted to tease Bob and so she took the numbers Bob wrote down, and for each of them she did one of the following independently:   rearranged its digits, or  wrote a random number. This way, Alice generated $$$n$$$ numbers, denoted $$$y_1$$$, ..., $$$y_n$$$.For each of the numbers, help Bob determine whether $$$y_i$$$ can be a permutation of a number divisible by $$$60$$$ (possibly with leading zeroes).

int solution() {
  int n;
  scanf("%d", &n);
  while (n--) {
    char ISLA[150];
    scanf("%s", ISLA);
    char E = 0;
    char Z = 0;
    int LL = 0;
    for (int i = 0; ISLA[i]; i++) {
      LL += ISLA[i] - '0';
      if (!((ISLA[i] - '0') & 1)) {
        if (ISLA[i] == '0') {
          if (Z == 0) {
            Z = 1;
          } else {
            E = 1;
          }
        } else {
          E = 1;
        }
      }
    }
    if (LL % 3 == 0 && E == 1 && Z == 1) {
      printf("red\n");
    } else {
      printf("cyan\n");
    }
  }
  return 0;
}

fn solution() {
    let mut result = Vec::new();

    let reader = io::stdin();
    let grandmaster_count = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i32>()
        .unwrap();

    for _i in 0..grandmaster_count {
        let str_number = reader.lock().lines().next().unwrap().unwrap();

        let digits: Vec<u8> = str_number
            .chars()
            .map(|s| s.to_string().parse::<u8>().unwrap())
            .collect();

        let iterator = digits.iter();
        let is_divisible_by_3 = iterator.clone().map(|x| x % 3).sum::<u8>() % 3 == 0;

        let is_divisible_by_10 = !iterator
            .clone()
            .filter(|s| **s == 0)
            .collect::<Vec<&u8>>()
            .is_empty();

        let amount_of_even = iterator
            .clone()
            .filter(|s| **s % 2 == 0)
            .collect::<Vec<&u8>>()
            .len();

        if is_divisible_by_10 && is_divisible_by_3 && amount_of_even > 1 {
            result.push("red");
        } else {
            result.push("cyan");
        }
    }

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


Score : <var>600</var> points

Problem Statement

Given are a sequence of <var>N</var> positive integers <var>A_1</var>, <var>A_2</var>, <var>\ldots</var>, <var>A_N</var> and another positive integer <var>S</var>.

For a non-empty subset <var>T</var> of the set <var>\{1, 2, \ldots , N \}</var>, let us define <var>f(T)</var> as follows:

<var>f(T)</var> is the number of different non-empty subsets <var>\{x_1, x_2, \ldots , x_k \}</var> of <var>T</var> such that <var>A_{x_1}+A_{x_2}+\cdots +A_{x_k} = S</var>.

Find the sum of <var>f(T)</var> over all <var>2^N-1</var> subsets <var>T</var> of <var>\{1, 2, \ldots , N \}</var>. Since the sum can be enormous, print it modulo <var>998244353</var>.

Constraints

All values in input are integers.

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the sum of <var>f(T)</var> modulo <var>998244353</var>.

Sample Input 1

3 4
2 2 4

Sample Output 1

6

For each <var>T</var>, the value of <var>f(T)</var> is shown below. The sum of these values is <var>6</var>.

<var>f(\{1\}) = 0</var>

<var>f(\{2\}) = 0</var>

<var>f(\{3\}) = 1</var> (One subset <var>\{3\}</var> satisfies the condition.)

<var>f(\{1, 2\}) = 1</var> (<var>\{1, 2\}</var>)

<var>f(\{2, 3\}) = 1</var> (<var>\{3\}</var>)

<var>f(\{1, 3\}) = 1</var> (<var>\{3\}</var>)

<var>f(\{1, 2, 3\}) = 2</var> (<var>\{1, 2\}, \{3\}</var>)

Sample Input 2

5 8
9 9 9 9 9

Sample Output 2

0

Sample Input 3

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

Sample Output 3

3296

int solution(void) {

  long n;
  long s;
  scanf("%ld %ld", &n, &s);
  long a[n];
  for (long i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
  }
  long mod = 998244353;
  long value;
  long dp[n][s + 1];
  for (long i = 0; i < n; i++) {
    for (long j = 0; j <= s; j++) {
      dp[i][j] = 0;
    }
  }
  dp[0][0] = 2;
  if (a[0] <= s) {
    dp[0][a[0]] = 1;
  }
  for (long i = 1; i < n; i++) {
    for (long j = 0; j <= s; j++) {
      dp[i][j] += dp[i - 1][j] * 2;
      dp[i][j] %= mod;
      value = j + a[i];
      if (value <= s) {
        dp[i][value] += dp[i - 1][j];
        dp[i][value] %= mod;
      }
    }
  }
  printf("%ld\n", dp[n - 1][s]);

  return 0;
}

fn solution() {
    const MOD: u64 = 998244353;

    let (n, s): (usize, usize) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();

        let n: usize = iter.next().unwrap().parse().unwrap();
        let s: usize = iter.next().unwrap().parse().unwrap();
        (n, s)
    };

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

    let mut dp: Vec<Vec<u64>> = vec![vec![0; s + 1]; n + 1];
    dp[0][0] = 1;

    for i in 0..n {
        for j in 0..(s + 1) {
            dp[i + 1][j] += dp[i][j] * 2;
            dp[i + 1][j] %= MOD;

            if j + a[i] <= s {
                dp[i + 1][j + a[i]] += dp[i][j];
                dp[i + 1][j + a[i]] %= MOD;
            }
        }
    }

    println!("{}", dp[n][s]);
}


A class of students got bored wearing the same pair of shoes every day, so they decided to shuffle their shoes among themselves. In this problem, a pair of shoes is inseparable and is considered as a single object.There are $$$n$$$ students in the class, and you are given an array $$$s$$$ in non-decreasing order, where $$$s_i$$$ is the shoe size of the $$$i$$$-th student. A shuffling of shoes is valid only if no student gets their own shoes and if every student gets shoes of size greater than or equal to their size. You have to output a permutation $$$p$$$ of $$$\{1,2,\ldots,n\}$$$ denoting a valid shuffling of shoes, where the $$$i$$$-th student gets the shoes of the $$$p_i$$$-th student ($$$p_i \ne i$$$). And output $$$-1$$$ if a valid shuffling does not exist.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

int solution() {
  int tc;
  scanf("%d", &tc);
  for (int i = 0; i < tc; i++) {
    long long int n;
    scanf("%lli\n", &n);
    long long int arr[n + 1];
    for (long long int l = 0; l < n; l++) {
      scanf("%lli ", &arr[l]);
    }
    arr[n + 1] = -1;
    long long int count = 1;
    long long int flag = 0;
    long long int j = 0;
    long long int op[n];
    for (long long int l = 0; l < n; l++) {
      op[l] = 0;
    }
    while (j < n && flag == 0) {
      if (arr[j + 1] != arr[j] && count == 1) {
        flag = 1;
      } else if (arr[j + 1] == arr[j] && count >= 1) {
        count++;
        op[j] = j + 2;
      } else if (arr[j + 1] != arr[j] && count > 1) {
        op[j] = j - count + 2;
        count = 1;
      }
      j++;
    }
    if (flag == 0) {
      for (long long int k = 0; k < n; k++) {
        printf("%lli ", op[k]);
      }
    } else {
      printf("-1");
    }
    printf("\n");
  }
  return 0;
}

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

    let mut buffer = String::new();

    stdin.read_line(&mut buffer).unwrap();
    let count: u32 = buffer.trim().parse().unwrap();

    'a: for _ in 0..count {
        stdin.read_line(&mut buffer).unwrap();

        buffer.clear();

        stdin.read_line(&mut buffer).unwrap();

        let data: Vec<usize> = buffer
            .trim()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();

        let mut record = HashMap::new();

        for (index, value) in data.iter().enumerate() {
            let edit = if let Some(x) = record.get_mut(&value) {
                x
            } else {
                record.insert(value, (0, vec![]));
                record.get_mut(&value).unwrap()
            };
            edit.1.push(index);
        }

        let mut output = Vec::with_capacity(data.len());

        for value in data.iter() {
            let data = record.get_mut(&value).unwrap();

            if data.1.len() == 1 {
                println!("-1");
                continue 'a;
            }

            data.0 += 1;
            output.push(data.1[data.0 % data.1.len()])
        }
        let mut output = output.into_iter();

        print!("{}", 1 + output.next().unwrap());

        for i in output {
            print!(" {}", 1 + i);
        }
        println!()
    }
}


Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer <var>x</var> and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer <var>x</var> in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print <var>x</var> in the following format:

Case i: x

where <var>i</var> is the case number which starts with 1. Put a single space between "Case" and <var>i</var>. Also, put a single space between ':' and <var>x</var>.

Constraints

1 ≤ <var>x</var> ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19

int solution() {
  int n = 0;
  int i = 1;
  while (scanf("%d", &n) && n != 0) {
    printf("Case %d: %d\n", i++, n);
  }
  return 0;
}

fn solution() {
    let out = &mut BufWriter::new(stdout());

    for i in 0..10000 {
        let mut input = String::new();
        stdin().read_line(&mut input).ok();
        match input.trim().parse::<i32>() {
            Ok(x) => {
                writeln!(out, "Case {}: {}", i + 1, x).ok();
            }
            _ => break,
        }
    }
}


Shuffle

  Your task is to shuffle a deck of <var>n</var> cards, each of which is marked by a alphabetical letter.

  A single shuffle action takes out <var>h</var> cards from the bottom of the deck and moves them to the top of the deck.

  The deck of cards is represented by a string as follows.

abcdeefab

  The first character and the last character correspond to the card located at the bottom of the deck and the card on the top of the deck respectively.

  For example, a shuffle with <var>h</var> = 4 to the above deck, moves the first 4 characters "abcd" to the end of the remaining characters "eefab", and generates the following deck:

eefababcd

  You can repeat such shuffle operations.

  Write a program which reads a deck (a string) and a sequence of <var>h</var>, and prints the final state (a string).

Input

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

A string which represents a deck
The number of shuffle <var>m</var>
<var>h</var>1
<var>h</var>2
  .
  .
<var>h</var><var>m</var>

  The input ends with a single character '-' for the string.

Constraints

The length of the string ≤ 200

1 ≤ <var>m</var> ≤ 100

1 ≤ <var>hi</var> < The length of the string

 The number of datasets ≤ 10

Output

  For each dataset, print a string which represents the final state in a line.

Sample Input

aabc
3
1
2
1
vwxyz
2
3
4
-

Sample Output

aabc
xyzvw

int solution() {
  char buf[2][201];
  char *p1 = buf[0];
  char *p2 = buf[1];

  while (scanf("%s\n", p1) && strcmp(p1, "-") != 0) {
    int m;
    scanf("%d\n", &m);

    while (m--) {
      int h;
      scanf("%d\n", &h);

      int rest = strlen(p1) - h;
      memcpy(p2, p1 + h, rest);
      memcpy(p2 + rest, p1, h);
      *(p2 + h + rest) = '\0';

      char *t = p1;
      p1 = p2;
      p2 = t;
    }
    puts(p1);
  }
}

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

    loop {
        let word = lines.by_ref().next().unwrap().unwrap();
        let word = word.trim();

        if word == "-" {
            break;
        }

        let m = lines
            .by_ref()
            .next()
            .unwrap()
            .unwrap()
            .parse::<usize>()
            .unwrap();
        let h = lines
            .by_ref()
            .take(m)
            .map(|x| x.unwrap().parse::<usize>().unwrap())
            .sum::<usize>()
            % word.len();

        println!("{}{}", &word[h..], &word[..h]);
    }
}


Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself, decides he wants to shuffle the guests around because he thinks this will create a vacancy (a room without a guest).For any integer $$$k$$$ and positive integer $$$n$$$, let $$$k\bmod n$$$ denote the remainder when $$$k$$$ is divided by $$$n$$$. More formally, $$$r=k\bmod n$$$ is the smallest non-negative integer such that $$$k-r$$$ is divisible by $$$n$$$. It always holds that $$$0\le k\bmod n\le n-1$$$. For example, $$$100\bmod 12=4$$$ and $$$(-1337)\bmod 3=1$$$.Then the shuffling works as follows. There is an array of $$$n$$$ integers $$$a_0,a_1,\ldots,a_{n-1}$$$. Then for each integer $$$k$$$, the guest in room $$$k$$$ is moved to room number $$$k+a_{k\bmod n}$$$.After this shuffling process, determine if there is still exactly one guest assigned to each room. That is, there are no vacancies or rooms with multiple guests.

fn solution() {
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("Failed to read line");
    let t: i32 = buffer.trim().parse().unwrap();
    for _ in 0..t {
        let mut buffer = String::new();
        io::stdin()
            .read_line(&mut buffer)
            .expect("Failed to read line");
        let n: i32 = buffer.trim().parse().unwrap();
        let mut vec = vec![0; n as usize];
        let mut buffer = String::new();
        io::stdin()
            .read_line(&mut buffer)
            .expect("Failed to read line");
        let a: Vec<i32> = buffer
            .trim()
            .split(" ")
            .map(|s| s.parse().unwrap())
            .collect();
        let mut flag = false;
        for i in 0..a.len() {
            let x = (((i as i32 + a[i]) % n) + n) % n;
            if vec[x as usize] != 0 {
                flag = true;
                break;
            } else {
                vec[x as usize] = 1;
            }
        }
        if flag {
            println!("NO");
        } else {
            println!("YES");
        }
    }
}


A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $$$7$$$ days!In detail, she can choose any integer $$$k$$$ which satisfies $$$1 \leq k \leq r$$$, and set $$$k$$$ days as the number of days in a week.Alice is going to paint some $$$n$$$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has $$$4$$$ days and Alice paints $$$5$$$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes.    Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $$$n$$$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.

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


Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?

int solution() {

  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
    }
    int x = arr[0];
    for (int i = 1; i < n; i++) {
      x &= arr[i];
    }
    printf("%d\n", x);
  }
  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();

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

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

        let ans = a.fold(!0, |a, x| a & x);

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


Score : <var>700</var> points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are <var>N</var> rows with <var>N</var> seats each, forming an <var>N\times N</var> square. We denote with <var>1, 2,\dots, N</var> the viewers in the first row (from left to right); with <var>N+1, \dots, 2N</var> the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by <var>N^2-N+1,\dots, N^2</var>.

At the end of the movie, the viewers go out of the cinema in a certain order: the <var>i</var>-th viewer leaving her seat is the one denoted by the number <var>P_i</var>. The viewer <var>P_{i+1}</var> waits until viewer <var>P_i</var> has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its <var>4</var> adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer <var>x</var> goes through a seat currently occupied by viewer <var>y</var>; in that case viewer <var>y</var> will hate viewer <var>x</var> forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers <var>(x, y)</var> such that <var>y</var> will hate <var>x</var> forever.

Constraints

<var>2 \le N \le 500</var>

The sequence <var>P_1, P_2, \dots, P_{N^2}</var> is a permutation of <var>\{1, 2, \dots, N^2\}</var>.

Input

The input is given from Standard Input in the format

<var>N</var>
<var>P_1</var> <var>P_2</var> <var>\cdots</var> <var>P_{N^2}</var>

Output

If <var>ans</var> is the number of pairs of viewers described in the statement, you should print on Standard Output

<var>ans</var>

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (<var>1</var>, <var>3</var>, <var>7</var>, <var>9</var>) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer <var>5</var> must go through one of the seats where viewers <var>2</var>, <var>4</var>, <var>6</var>, <var>8</var> are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order <var>4</var>, <var>8</var>, <var>6</var>, <var>2</var>) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11

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

    let N = buf_it.next().unwrap().parse::<usize>().unwrap();
    let P = (0..N * N)
        .map(|_| buf_it.next().unwrap().parse::<usize>().unwrap() - 1)
        .collect::<Vec<_>>();

    let mut ans = 0;
    let mut cost = (0..N)
        .map(|_| (0..N).map(|_| 0).collect::<Vec<_>>())
        .collect::<Vec<_>>();
    let mut seated = (0..N)
        .map(|_| (0..N).map(|_| 1).collect::<Vec<_>>())
        .collect::<Vec<_>>();
    for i in 0..N {
        for j in 0..N {
            let mut tmp = min(i, N - 1 - i);
            tmp = min(tmp, j);
            tmp = min(tmp, N - 1 - j);
            cost[i][j] = tmp;
        }
    }

    for p in P {
        let i = p % N;
        let j = p / N;
        ans += cost[i][j];
        seated[i][j] = 0;
        let mut q = vec![(i, j)];
        while !q.is_empty() {
            let mut qq = Vec::new();
            while let Some((i, j)) = q.pop() {
                let c = cost[i][j] + seated[i][j];
                let i = i as isize;
                let j = j as isize;
                for (di, dj) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
                    let i = i + di;
                    let j = j + dj;
                    if i < 0 || i >= (N as isize) || j < 0 || j >= (N as isize) {
                        continue;
                    }
                    let i = i as usize;
                    let j = j as usize;
                    if cost[i][j] <= c {
                        continue;
                    }
                    cost[i][j] = c;
                    qq.push((i, j));
                }
            }
            q = qq;
        }
    }

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


Reverse Sequence

Write a program which reverses a given string <var>str</var>.

Input

<var>str</var> (the size of <var>str</var> ≤ 20) is given in a line.

Output

Print the reversed <var>str</var> in a line.

Sample Input

w32nimda

Output for the Sample Input

admin23w

fn solution() {
    let mut buf = String::new();
    if let Ok(_) = stdin().read_line(&mut buf) {
        println!("{}", buf.trim().chars().rev().collect::<String>());
    }
}


You are given four distinct integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$. Timur and three other people are running a marathon. The value $$$a$$$ is the distance that Timur has run and $$$b$$$, $$$c$$$, $$$d$$$ correspond to the distances the other three participants ran. Output the number of participants in front of Timur.

int solution() {
  int tc = 0;
  int a = 0;
  int b = 0;
  int c = 0;
  int d = 0;
  int ahead = 0;
  scanf("%d", &tc);
  while (tc--) {
    scanf("%d %d %d %d", &a, &b, &c, &d);
    if (b > a) {
      ahead++;
    }
    if (c > a) {
      ahead++;
    }
    if (d > a) {
      ahead++;
    }
    printf("%d\n", ahead);
    ahead = 0;
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("E");
    for _ in 0..(input.trim().to_string().parse::<u16>().unwrap()) {
        input = String::new();
        io::stdin().read_line(&mut input).expect("E");
        let mut data: Vec<u16> = vec![];
        for i in input.trim().to_string().split(" ") {
            data.push(i.parse::<u16>().unwrap());
        }
        let tim: u16 = data[0];
        data.sort();
        println!("{}", 3 - data.iter().position(|&x| x == tim).unwrap());
    }
}


Welcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $$$a$$$ dollars and Ronnie has bet $$$b$$$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $$$gcd(a,b)$$$, where $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. To make the race more exciting, you can perform two types of operations:  Increase both $$$a$$$ and $$$b$$$ by $$$1$$$.  Decrease both $$$a$$$ and $$$b$$$ by $$$1$$$. This operation can only be performed if both $$$a$$$ and $$$b$$$ are greater than $$$0$$$. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that $$$gcd(x,0)=x$$$ for any $$$x \ge 0$$$.

int solution(void) {
  int tc;
  scanf("%d", &tc);
  while (tc-- > 0) {
    long long a;
    long long b;
    scanf("%lld %lld", &a, &b);
    if (a == b) {
      puts("0 0");
      continue;
    }
    if (a > b) {
      long long t = a;
      a = b;
      b = t;
    }
    long long d = b - a;
    long long lo = a / d * d;
    long long hi = lo + d;
    long long moves = hi - a < a - lo ? hi - a : a - lo;
    printf("%lld %lld\n", d, moves);
  }
  return 0;
}

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

    let t: i64 = line.trim().parse().unwrap();

    for _ in 0..t {
        line.clear();
        stdin().read_line(&mut line).unwrap();

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

        let a = words[0];
        let b = words[1];

        let m = min(a, b);
        let d = i64::abs(a - b);

        if d == 0 {
            println!("0 0");
            continue;
        }

        println!("{} {}", d, min(m % d, d - m % d));
    }
}


Score : <var>100</var> points

Problem Statement

Snuke is giving cookies to his three goats.

He has two cookie tins. One contains <var>A</var> cookies, and the other contains <var>B</var> cookies. He can thus give <var>A</var> cookies, <var>B</var> cookies or <var>A+B</var> cookies to his goats (he cannot open the tins).

Your task is to determine whether Snuke can give cookies to his three goats so that each of them can have the same number of cookies.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

If it is possible to give cookies so that each of the three goats can have the same number of cookies, print Possible; otherwise, print Impossible.

Sample Input 1

4 5

Sample Output 1

Possible

If Snuke gives nine cookies, each of the three goats can have three cookies.

Sample Input 2

1 1

Sample Output 2

Impossible

Since there are only two cookies, the three goats cannot have the same number of cookies no matter what Snuke gives to them.

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

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

    if a % 3 == 0 {
        println!("Possible");
        return;
    }
    if b % 3 == 0 {
        println!("Possible");
        return;
    }
    if (a + b) % 3 == 0 {
        println!("Possible");
        return;
    }
    println!("Impossible");
}


You have a string $$$s_1 s_2 \ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \le k \le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

fn solution() {
    let mut buf = String::new();
    let stdin = io::stdin();
    let r = stdin.read_line(&mut buf);
    match r {
        Ok(_) => {}
        _ => panic!("could not read from stdin"),
    }

    let n: u32 = buf.trim().parse().unwrap();

    'testcases: for _i in 0..n {
        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }
        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }

        let rb = buf.trim().as_bytes();
        let mut best = String::new();

        for i in 0..rb.len() - 1 {
            if rb[i] < rb[i + 1] {
                let new = format!(
                    "{}{}",
                    &buf[0..i + 1],
                    buf[0..i + 1].chars().rev().collect::<String>()
                );
                best = if best.is_empty() {
                    new
                } else {
                    std::cmp::min(best, new)
                };

                println!("{}", best);
                continue 'testcases;
            }
            if rb[i] == rb[i + 1] && i == 0 {
                let new = format!(
                    "{}{}",
                    &buf[0..i + 1],
                    buf[0..i + 1].chars().rev().collect::<String>()
                );

                best = if best.is_empty() {
                    new
                } else {
                    std::cmp::min(best, new)
                };
                break;
            }
        }
        let new = format!(
            "{}{}",
            buf.trim(),
            buf.trim().chars().rev().collect::<String>()
        );
        best = if best.is_empty() {
            new
        } else {
            std::cmp::min(best, new)
        };

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


Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any $$$i$$$ ($$$1 \le i \le n-1$$$), this condition must be satisfied: $$$$$$\frac{\max(a[i], a[i+1])}{\min(a[i], a[i+1])} \le 2$$$$$$For example, the arrays $$$[1, 2, 3, 4, 3]$$$, $$$[1, 1, 1]$$$ and $$$[5, 10]$$$ are dense. And the arrays $$$[5, 11]$$$, $$$[1, 4, 2]$$$, $$$[6, 6, 1]$$$ are not dense.You are given an array $$$a$$$ of $$$n$$$ integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added.For example, if $$$a=[4,2,10,1]$$$, then the answer is $$$5$$$, and the array itself after inserting elements into it may look like this: $$$a=[4,2,\underline{\textbf{3}},\underline{\textbf{5}},10,\underline{\textbf{6}},\underline{\textbf{4}},\underline{\textbf{2}},1]$$$ (there are other ways to build such $$$a$$$).

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 arr: Vec<i32> = (0..n).map(|_| sc.next()).collect();
        let mut ans: i32 = 0;
        for i in 1..n {
            let mut a = min(arr[i - 1], arr[i]);
            let b = max(arr[i - 1], arr[i]);
            while 2 * a < b {
                a *= 2;
                ans += 1;
            }
        }
        writeln!(out, "{}", ans).unwrap();
    }
}


Score : <var>300</var> points

Problem Statement

You are given a string <var>S</var> consisting of digits between 1 and 9, inclusive.
You can insert the letter + into some of the positions (possibly none) between two letters in this string.
Here, + must not occur consecutively after insertion.

All strings that can be obtained in this way can be evaluated as formulas.

Evaluate all possible formulas, and print the sum of the results.

Constraints

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

All letters in <var>S</var> are digits between 1 and 9, inclusive.

Input

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

<var>S</var>

Output

Print the sum of the evaluated value over all possible formulas.

Sample Input 1

125

Sample Output 1

176

There are <var>4</var> formulas that can be obtained: 125, 1+25, 12+5 and 1+2+5. When each formula is evaluated,

<var>125</var>

<var>1+25=26</var>

<var>12+5=17</var>

<var>1+2+5=8</var>

Thus, the sum is <var>125+26+17+8=176</var>.

Sample Input 2

9999999999

Sample Output 2

12656242944

int solution() {
  long S[12];
  int fig = 0;
  long ans = 0;
  int x;

  S[0] = getc(stdin) - '0';
  ans += S[0];

  for (fig = 1; fig < 10; fig++) {
    S[fig] = getchar() - '0';
    if (S[fig] > 9 || S[fig] < 1) {
      break;
    }
    ans *= 10;
    for (x = 1; x <= fig; x++) {
      ans += S[x - 1] * pow(2, fig - 1);
    }
    ans += S[fig] * pow(2, fig);
  }

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

  return 0;
}

fn solution() {
    input! {
        S: chars,
    }
    let mut ans: u64 = 0;

    for bit in 0..1 << (S.len() - 1) {
        let mut acc_str = String::new();
        let mut acc = 0_u64;
        acc_str.push(S[0]);
        for i in 0..S.len() - 1 {
            if bit & 1 << i != 0 {
                acc += acc_str.parse::<u64>().unwrap();
                acc_str = String::new();
            }
            acc_str.push(S[i + 1]);
        }
        acc += acc_str.parse::<u64>().unwrap();
        ans += acc;
    }
    println!("{}", ans);
}


Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it becomes empty.Your task is to calculate the tram's minimum capacity such that the number of people inside the tram at any time never exceeds this capacity. Note that at each stop all exiting passengers exit before any entering passenger enters the tram.

int solution() {

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

  for (int i = 0; i < n; i++) {
    int exitt = 0;
    int enter = 0;
    scanf("%d %d\n", &exitt, &enter);
    pass = pass + enter - exitt;
    if (pass > capacity) {
      capacity = pass;
    }
  }
  printf("%d", capacity);

  return 0;
}

fn solution() {
    let mut text = String::new();
    std::io::stdin()
        .read_line(&mut text)
        .expect("cannot read line number");
    let n = text.trim().parse::<u32>().expect("failed to parse");
    let mut total = 0;
    let mut max = 0;
    for _ in 0..n {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("line");
        let mut i = line.split_whitespace();
        let a = i.next().unwrap().parse::<u32>().expect("not a number");
        let b = i.next().unwrap().parse::<u32>().expect("not a number");
        total -= a;
        total += b;
        if total > max {
            max = total;
        }
    }
    println!("{}", max);
}


A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are not adjacent.Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).You are given a sequence of strings. For each string, if it is diverse, print "Yes". Otherwise, print "No".

int solution() {
  int n;
  scanf("%d", &n);
  int letter;
  int sig;
  int occurences[40];
  int correct = 1;
  getc(stdin);
  for (int i = 0; i < n; i++) {
    correct = 1;
    for (int j = 0; j < 40; j++) {
      occurences[j] = 0;
    }
    while ((letter = getc(stdin)) != '\n' && letter != EOF) {
      sig = letter - 'a';

      if (occurences[sig] != 0) {
        correct = 0;
      } else {
        occurences[sig] = 1;
      }
    }
    int beg = 0;
    while (beg < 39 && occurences[beg] == 0) {

      beg++;
    }
    while (beg < 39 && occurences[beg] == 1) {

      beg++;
    }
    while (beg < 39 && occurences[beg] == 0) {

      beg++;
    }
    if (beg != 39) {
      correct = 0;
    }
    if (correct == 1) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }
  }
  return 0;
}

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

    for _ in 0..n {
        io::stdin().read_line(&mut input).unwrap();

        let mut s: Vec<char> = input.trim().chars().collect();

        s.sort();

        let mut iter = s.iter();

        let mut cur = iter.next().unwrap();

        let mut yes = true;

        for i in iter {
            if *i as u8 == *cur as u8 + 1 {
                cur = i
            } else {
                yes = false;
            }
        }

        if yes {
            println!("Yes");
        } else {
            println!("No");
        }

        input.clear();
    }
}


Score : <var>500</var> points

Problem Statement

An adult game master and <var>N</var> children are playing a game on an ice rink.
The game consists of <var>K</var> rounds.
In the <var>i</var>-th round, the game master announces:

Form groups consisting of <var>A_i</var> children each!

Then the children who are still in the game form as many groups of <var>A_i</var> children as possible.
One child may belong to at most one group.
Those who are left without a group leave the game. The others proceed to the next round.
Note that it's possible that nobody leaves the game in some round.

In the end, after the <var>K</var>-th round, there are exactly two children left, and they are declared the winners.

You have heard the values of <var>A_1</var>, <var>A_2</var>, ..., <var>A_K</var>. You don't know <var>N</var>, but you want to estimate it.

Find the smallest and the largest possible number of children in the game before the start, or determine that no valid values of <var>N</var> exist.

Constraints

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

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>K</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_K</var>

Output

Print two integers representing the smallest and the largest possible value of <var>N</var>, respectively,
or a single integer <var>-1</var> if the described situation is impossible.

Sample Input 1

4
3 4 3 2

Sample Output 1

6 8

For example, if the game starts with <var>6</var> children, then it proceeds as follows:

In the first round, <var>6</var> children form <var>2</var> groups of <var>3</var> children, and nobody leaves the game.

In the second round, <var>6</var> children form <var>1</var> group of <var>4</var> children, and <var>2</var> children leave the game.

In the third round, <var>4</var> children form <var>1</var> group of <var>3</var> children, and <var>1</var> child leaves the game.

In the fourth round, <var>3</var> children form <var>1</var> group of <var>2</var> children, and <var>1</var> child leaves the game.

The last <var>2</var> children are declared the winners.

Sample Input 2

5
3 4 100 3 2

Sample Output 2

-1

This situation is impossible.
In particular, if the game starts with less than <var>100</var> children, everyone leaves after the third round.

Sample Input 3

10
2 2 2 2 2 2 2 2 2 2

Sample Output 3

2 3

int solution(void) {
  long long k;
  long long max = 2;
  long long min = 2;
  scanf("%lld", &k);
  long long a[k];
  for (int i = 0; i < k; i++) {
    scanf("%lld", &a[i]);
  }
  for (int i = k - 1; i >= 0; i--) {
    min = ((min + a[i] - 1) / a[i]) * a[i];
    if (min > (max / a[i]) * a[i]) {
      printf("-1\n");
      return 0;
    }
    max = ((max / a[i]) * a[i]) + a[i] - 1;
  }
  printf("%lld %lld\n", min, max);
  return 0;
}

fn solution() {
    let mut buf: String = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let iter = buf.split_whitespace();
    let mut nums: Vec<i64> = Vec::new();
    for i in iter {
        nums.push(i.parse::<i64>().unwrap());
    }
    nums.reverse();
    let mut n_max = 2;
    let mut n_min = 2;
    for n in nums {
        if n_max % n != 0 {
            n_max -= n_max % n;
        }
        if n_min % n != 0 {
            n_min += n - n_min % n;
        }
        if n_max < n_min {
            println!("-1");
            return;
        }
        n_max += n - 1;
    }
    println!("{} {}", n_min, n_max);
}


Score : <var>100</var> points

Problem Statement

There is a grid with <var>H</var> horizontal rows and <var>W</var> vertical columns.
Let <var>(i, j)</var> denote the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left.

For each <var>i</var> and <var>j</var> (<var>1 \leq i \leq H</var>, <var>1 \leq j \leq W</var>), Square <var>(i, j)</var> is described by a character <var>a_{i, j}</var>.
If <var>a_{i, j}</var> is ., Square <var>(i, j)</var> is an empty square; if <var>a_{i, j}</var> is #, Square <var>(i, j)</var> is a wall square.
It is guaranteed that Squares <var>(1, 1)</var> and <var>(H, W)</var> are empty squares.

Taro will start from Square <var>(1, 1)</var> and reach <var>(H, W)</var> by repeatedly moving right or down to an adjacent empty square.

Find the number of Taro's paths from Square <var>(1, 1)</var> to <var>(H, W)</var>.
As the answer can be extremely large, find the count modulo <var>10^9 + 7</var>.

Constraints

<var>H</var> and <var>W</var> are integers.

<var>2 \leq H, W \leq 1000</var>

<var>a_{i, j}</var> is . or #.

Squares <var>(1, 1)</var> and <var>(H, W)</var> are empty squares.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>a_{1, 1}</var><var>\ldots</var><var>a_{1, W}</var>
<var>:</var>
<var>a_{H, 1}</var><var>\ldots</var><var>a_{H, W}</var>

Output

Print the number of Taro's paths from Square <var>(1, 1)</var> to <var>(H, W)</var>, modulo <var>10^9 + 7</var>.

Sample Input 1

3 4
...#
.#..
....

Sample Output 1

3

There are three paths as follows:

Sample Input 2

5 2
..
#.
..
.#
..

Sample Output 2

0

There may be no paths.

Sample Input 3

5 5
..#..
.....
#...#
.....
..#..

Sample Output 3

24

Sample Input 4

20 20
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................
....................

Sample Output 4

345263555

Be sure to print the count modulo <var>10^9 + 7</var>.

fn solution() {
    input! {
      h: usize,
      w: usize,
      boards: [chars; h],
    }

    let d = 1000000000 + 7;
    let mut dp = vec![vec![0; w + 1]; h + 1];

    let mut left;
    let mut top;

    for i in 0..h {
        for j in 0..w {
            if j > 0 {
                left = if boards[i][j - 1] == '.' {
                    dp[i][j - 1]
                } else {
                    0
                };
            } else {
                left = 0;
            }
            if i > 0 {
                top = if boards[i - 1][j] == '.' {
                    dp[i - 1][j]
                } else {
                    0
                };
            } else {
                top = 0;
            }
            if i == 0 && j == 0 {
                dp[i][j] = 1;
            } else {
                dp[i][j] = (top + left) % d;
            }
        }
    }

    println!("{}", dp[h - 1][w - 1]);
}


Chouti and his classmates are going to the university soon. To say goodbye to each other, the class has planned a big farewell party in which classmates, teachers and parents sang and danced.Chouti remembered that $$$n$$$ persons took part in that party. To make the party funnier, each person wore one hat among $$$n$$$ kinds of weird hats numbered $$$1, 2, \ldots n$$$. It is possible that several persons wore hats of the same kind. Some kinds of hats can remain unclaimed by anyone.After the party, the $$$i$$$-th person said that there were $$$a_i$$$ persons wearing a hat differing from his own.It has been some days, so Chouti forgot all about others' hats, but he is curious about that. Let $$$b_i$$$ be the number of hat type the $$$i$$$-th person was wearing, Chouti wants you to find any possible $$$b_1, b_2, \ldots, b_n$$$ that doesn't contradict with any person's statement. Because some persons might have a poor memory, there could be no solution at all.

int solution() {

  int n;
  scanf("%d", &n);
  int i;
  int en[n];
  int con = 1;
  int fre[n + 1];
  int va[n + 1];
  memset(fre, 0, sizeof fre);
  for (i = 0; i < n; i++) {
    scanf("%d", &en[i]);
    en[i] = n - en[i];
    fre[en[i]]++;
  }
  for (i = 0; i < n; i++) {
    if (fre[en[i]] % en[i]) {
      break;
    }
  }
  if (i < n) {
    printf("Impossible\n");
  } else {
    printf("Possible\n");
    for (i = 0; i < n; i++) {
      if (fre[en[i]] % en[i] == 0) {
        va[en[i]] = con++;
      }
      printf("%d", va[en[i]]);
      fre[en[i]]--;
      if (i < n - 1) {
        printf(" ");
      } else {
        printf("\n");
      }
    }
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let total: i32 = line.trim().parse().unwrap();
    line.clear();
    let mut recalls: BTreeMap<i32, (i32, i32)> = BTreeMap::new();
    let mut hats = Vec::with_capacity(total as usize);
    let mut hat_type = 0;
    input.read_line(&mut line).unwrap();
    for recall in line.split_whitespace() {
        let recall: i32 = recall.parse().unwrap();
        if let std::collections::btree_map::Entry::Vacant(e) = recalls.entry(recall) {
            hat_type += 1;
            hats.push(hat_type);
            let left_hats = total - recall - 1;
            if left_hats != 0 {
                e.insert((hat_type, left_hats));
            }
        } else {
            let same_hats = recalls.get_mut(&recall).unwrap();
            hats.push(same_hats.0);
            if same_hats.1 == 1 {
                recalls.remove(&recall);
            } else {
                same_hats.1 -= 1;
            }
        }
    }
    if recalls.is_empty() {
        println!("Possible");
        for hat in hats {
            print!("{} ", hat);
        }
    } else {
        println!("Impossible");
    }
}


Let $$$\mathsf{AND}$$$ denote the bitwise AND operation, and $$$\mathsf{OR}$$$ denote the bitwise OR operation.You are given an array $$$a$$$ of length $$$n$$$ and a non-negative integer $$$k$$$. You can perform at most $$$k$$$ operations on the array of the following type:  Select an index $$$i$$$ ($$$1 \leq i \leq n$$$) and replace $$$a_i$$$ with $$$a_i$$$ $$$\mathsf{OR}$$$ $$$2^j$$$ where $$$j$$$ is any integer between $$$0$$$ and $$$30$$$ inclusive. In other words, in an operation you can choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) and set the $$$j$$$-th bit of $$$a_i$$$ to $$$1$$$ ($$$0 \leq j \leq 30$$$). Output the maximum possible value of $$$a_1$$$ $$$\mathsf{AND}$$$ $$$a_2$$$ $$$\mathsf{AND}$$$ $$$\dots$$$ $$$\mathsf{AND}$$$ $$$a_n$$$ after performing at most $$$k$$$ operations.

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

  int ans[test_cases];

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

    int remaining = k;
    for (int pos = 30; pos >= 0; pos--) {

      int guess = n;
      for (int i = 0; i < n; i++) {
        guess -= (a[i] >> pos) & 1;
      }

      if (remaining >= guess) {
        remaining -= guess;
        for (int i = 0; i < n; i++) {
          a[i] |= 1 << pos;
        }
      }
    }

    unsigned int and = (1 << 31);
    and--;
    for (int i = 0; i < n; i++) {
      and &= a[i];
    }
    ans[t] = and;
  }

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

  return 0;
}

fn solution() {
    let t = read!(u64);
    for _i in 0..t {
        let (_n, k) = read_pair!(usize);
        let a: Vec<u32> = read_vec!(u32);

        let mut bits: [u32; 31] = [0; 31];
        for num in a {
            for j in 0..31 {
                let jth_bit = (num >> j) & 1;

                if jth_bit == 0 {
                    bits[j] += 1
                }
            }
        }

        let mut budget = k as u32;
        for j in (0..31).rev() {
            if bits[j] <= budget {
                budget -= bits[j];
                bits[j] = 0;
            }
        }

        let mut ans: u32 = 0;
        for j in 0..31 {
            if bits[j] == 0 {
                ans |= 1 << j;
            }
        }

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


Score: <var>600</var> points

Problem Statement

Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east.

They start simultaneously at the same point and moves as follows towards the east:

Takahashi runs <var>A_1</var> meters per minute for the first <var>T_1</var> minutes,  then runs at <var>A_2</var> meters per minute for the subsequent <var>T_2</var> minutes, and alternates between these two modes forever.

Aoki runs <var>B_1</var> meters per minute for the first <var>T_1</var> minutes,  then runs at <var>B_2</var> meters per minute for the subsequent <var>T_2</var> minutes, and alternates between these two modes forever.

How many times will Takahashi and Aoki meet each other, that is, come to the same point? We do not count the start of the run. If they meet infinitely many times, report that fact.

Constraints

<var>1 \leq T_i \leq 100000</var>

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

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

<var>A_1 \neq B_1</var>

<var>A_2 \neq B_2</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>T_1</var> <var>T_2</var>
<var>A_1</var> <var>A_2</var>
<var>B_1</var> <var>B_2</var>

Output

Print the number of times Takahashi and Aoki will meet each other.

If they meet infinitely many times, print infinity instead.

Sample Input 1

1 2
10 10
12 4

Sample Output 1

1

They will meet just once, <var>\frac{4}{3}</var> minutes after they start, at <var>\frac{40}{3}</var> meters from where they start.

Sample Input 2

100 1
101 101
102 1

Sample Output 2

infinity

They will meet <var>101, 202, 303, 404, 505, 606, ...</var> minutes after they start, that is, they will meet infinitely many times.

Sample Input 3

12000 15700
3390000000 3810000000
5550000000 2130000000

Sample Output 3

113

The values in input may not fit into a <var>32</var>-bit integer type.

int solution() {
  long long int T1;
  long long int T2;
  long long int A1;
  long long int A2;
  long long int B1;
  long long int B2;
  scanf("%lld %lld", &T1, &T2);
  scanf("%lld %lld", &A1, &A2);
  scanf("%lld %lld", &B1, &B2);
  long long int diff = (T1 * (A1 - B1)) + (T2 * (A2 - B2));
  if (diff == 0) {
    printf("infinity\n");
  } else {
    long long diff2 = T1 * (A1 - B1);
    if ((diff > 0 && diff2 > 0) || (diff < 0 && diff2 < 0)) {
      printf("0\n");
    } else {
      long long int ct = -diff2 / diff;
      ct *= 2;
      ct++;
      if (diff2 % diff == 0) {
        ct--;
      }
      printf("%lld\n", ct);
    }
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let t = (
        s.next().unwrap().parse::<i64>().unwrap(),
        s.next().unwrap().parse::<i64>().unwrap(),
    );
    let a = (
        s.next().unwrap().parse::<i64>().unwrap(),
        s.next().unwrap().parse::<i64>().unwrap(),
    );
    let b = (
        s.next().unwrap().parse::<i64>().unwrap(),
        s.next().unwrap().parse::<i64>().unwrap(),
    );
    let alen = a.0 * t.0 + a.1 * t.1;
    let blen = b.0 * t.0 + b.1 * t.1;
    if alen == blen {
        println!("infinity");
    } else {
        let (a, b) = if alen < blen { (b, a) } else { (a, b) };
        let ans = if a.0 > b.0 {
            0
        } else {
            let dif = (alen - blen).abs();
            let r = b.0 - a.0;
            2 * ((t.0 * r + dif - 1) / dif) + if t.0 * r % dif == 0 { 1 } else { 0 } - 1
        };
        println!("{}", ans);
    }
}


Score : <var>100</var> points

Problem Statement

Two deer, AtCoDeer and TopCoDeer, are playing a game called Honest or Dishonest.
In this game, an honest player always tells the truth, and an dishonest player always tell lies.
You are given two characters <var>a</var> and <var>b</var> as the input. Each of them is either H or D, and carries the following information:

If <var>a</var>=H, AtCoDeer is honest; if <var>a</var>=D, AtCoDeer is dishonest.
If <var>b</var>=H, AtCoDeer is saying that TopCoDeer is honest; if <var>b</var>=D, AtCoDeer is saying that TopCoDeer is dishonest.

Given this information, determine whether TopCoDeer is honest.

Constraints

<var>a</var>=H or <var>a</var>=D.

<var>b</var>=H or <var>b</var>=D.

Input

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

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

Output

If TopCoDeer is honest, print H. If he is dishonest, print D.

Sample Input 1

H H

Sample Output 1

H

In this input, AtCoDeer is honest. Hence, as he says, TopCoDeer is honest.

Sample Input 2

D H

Sample Output 2

D

In this input, AtCoDeer is dishonest. Hence, contrary to what he says, TopCoDeer is dishonest.

Sample Input 3

D D

Sample Output 3

H

int solution() {

  char A = ' ';
  char B = ' ';

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

  if (A == B) {
    printf("H");
  } else {
    printf("D");
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let iter = buf.split_whitespace();
    let mut v: Vec<char> = Vec::new();
    for i in iter {
        v.push(i.chars().collect::<Vec<char>>()[0]);
    }
    if v[0] == 'H' {
        println!("{}", v[1]);
    } else {
        if v[1] == 'H' {
            println!("D");
        } else {
            println!("H");
        }
    }
}


Score : <var>100</var> points

Problem Statement

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

Determine if there exists an equilateral triangle whose sides have lengths <var>A, B</var> and <var>C</var>.

Constraints

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

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

Output

If there exists an equilateral triangle whose sides have lengths <var>A, B</var> and <var>C</var>, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

There exists an equilateral triangle whose sides have lengths <var>2, 2</var> and <var>2</var>.

Sample Input 2

3 4 5

Sample Output 2

No

There is no equilateral triangle whose sides have lengths <var>3, 4</var> and <var>5</var>.

int solution() {
  int a = 0;
  int b = 0;
  int c = 0;
  scanf("%d %d %d", &a, &b, &c);
  if (a == b && b == c) {
    printf("Yes\n");
  } else {
    printf("No\n");
  }
  return 0;
}

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

    let mut three_iter = buf.split_whitespace().map(|s| s.parse::<u32>().unwrap());
    let first = three_iter.next().unwrap();
    match three_iter.all(|elem| elem == first) {
        true => println!("Yes"),
        false => println!("No"),
    }
}


Polycarp wrote on a whiteboard an array $$$p$$$ of length $$$n$$$, which is a permutation of numbers from $$$1$$$ to $$$n$$$. In other words, in $$$p$$$ each number from $$$1$$$ to $$$n$$$ occurs exactly once.He also prepared a resulting array $$$a$$$, which is initially empty (that is, it has a length of $$$0$$$).After that, he did exactly $$$n$$$ steps. Each step looked like this:  Look at the leftmost and rightmost elements of $$$p$$$, and pick the smaller of the two. If you picked the leftmost element of $$$p$$$, append it to the left of $$$a$$$; otherwise, if you picked the rightmost element of $$$p$$$, append it to the right of $$$a$$$. The picked element is erased from $$$p$$$. Note that on the last step, $$$p$$$ has a length of $$$1$$$ and its minimum element is both leftmost and rightmost. In this case, Polycarp can choose what role the minimum element plays. In other words, this element can be added to $$$a$$$ both on the left and on the right (at the discretion of Polycarp).Let's look at an example. Let $$$n=4$$$, $$$p=[3, 1, 4, 2]$$$. Initially $$$a=[]$$$. Then: During the first step, the minimum is on the right (with a value of $$$2$$$), so after this step, $$$p=[3,1,4]$$$ and $$$a=[2]$$$ (he added the value $$$2$$$ to the right).  During the second step, the minimum is on the left (with a value of $$$3$$$), so after this step, $$$p=[1,4]$$$ and $$$a=[3,2]$$$ (he added the value $$$3$$$ to the left).  During the third step, the minimum is on the left (with a value of $$$1$$$), so after this step, $$$p=[4]$$$ and $$$a=[1,3,2]$$$ (he added the value $$$1$$$ to the left).  During the fourth step, the minimum is both left and right (this value is $$$4$$$). Let's say Polycarp chose the right option. After this step, $$$p=[]$$$ and $$$a=[1,3,2,4]$$$ (he added the value $$$4$$$ to the right).Thus, a possible value of $$$a$$$ after $$$n$$$ steps could be $$$a=[1,3,2,4]$$$.You are given the final value of the resulting array $$$a$$$. Find any possible initial value for $$$p$$$ that can result the given $$$a$$$, or determine that there is no solution.

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

  return 0;
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let v = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<u32>().unwrap())
            .collect::<Vec<_>>();
        let x = *v.iter().max().unwrap();
        if v[0] == x || v[v.len() - 1] == x {
            for n in v.iter().rev() {
                write!(o, "{} ", n).ok();
            }
            writeln!(o).ok();
        } else {
            writeln!(o, "-1").ok();
        }
    }
}


This is the easy version of the problem. The only difference is the constraints on $$$n$$$ and $$$k$$$. You can make hacks only if all versions of the problem are solved.You have a string $$$s$$$, and you can do two types of operations on it:   Delete the last character of the string.  Duplicate the string: $$$s:=s+s$$$, where $$$+$$$ denotes concatenation. You can use each operation any number of times (possibly none).Your task is to find the lexicographically smallest string of length exactly $$$k$$$ that can be obtained by doing these operations on string $$$s$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a prefix of $$$b$$$, but $$$a\ne b$$$;  In the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

int solution() {
  int n;
  int k;
  int a = 1;
  scanf("%d %d", &n, &k);
  char s[n + 1];
  scanf("%s", s);
  for (int i = 0; i < n; i++) {
    if (s[i] > s[i % a]) {
      break;
    }
    if (s[i] < s[i % a]) {
      a = i + 1;
    }
  }
  for (int i = 0; i < k; i++) {
    putchar(s[i % a]);
  }
  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 s = lines.next().unwrap();
    let mut it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());

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

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

    let i = (1..=n)
        .min_by(|&i, &j| {
            a[..i]
                .iter()
                .cycle()
                .take(k)
                .cmp(a[..j].iter().cycle().take(k))
        })
        .unwrap();

    let mut k = k;
    while k > 0 {
        let x = std::cmp::min(i, k);
        output.write_all(&a[..x]).unwrap();
        k -= x;
    }

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


You had $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ arranged in a circle. For each pair of neighboring numbers ($$$a_1$$$ and $$$a_2$$$, $$$a_2$$$ and $$$a_3$$$, ..., $$$a_{n - 1}$$$ and $$$a_n$$$, and $$$a_n$$$ and $$$a_1$$$), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array $$$a$$$. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array $$$a$$$ which is consistent with information you have about equality or non-equality of corresponding pairs?

int solution() {
  int n_case = 0;
  scanf("%d", &n_case);
  char s[52];
  int n_sum = 0;
  for (int ii = 0; ii < n_case; ++ii) {
    scanf("%s", s);
    n_sum = 0;
    for (int i = 0; s[i] != '\0'; ++i) {
      if (s[i] == 'N') {
        ++n_sum;
        if (n_sum > 1) {
          printf("YES\n");
          break;
        }
      }
    }
    if (n_sum == 0) {
      printf("YES\n");
    }
    if (n_sum == 1) {
      printf("NO\n");
    }
  }
}

fn solution() {
    let mut t = String::new();
    io::stdin().read_line(&mut t).expect("input error");
    let mut t: i32 = t.trim().parse().expect("input error");
    while t > 0 {
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("input error");
        if input.matches('N').count() == 1 {
            println!("NO");
        } else {
            println!("YES");
        }
        t -= 1;
    }
}


Berland annual chess tournament is coming!Organizers have gathered 2·n chess players who should be divided into two teams with n people each. The first team is sponsored by BerOil and the second team is sponsored by BerMobile. Obviously, organizers should guarantee the win for the team of BerOil.Thus, organizers should divide all 2·n players into two teams with n people each in such a way that the first team always wins.Every chess player has its rating ri. It is known that chess player with the greater rating always wins the player with the lower rating. If their ratings are equal then any of the players can win.After teams assignment there will come a drawing to form n pairs of opponents: in each pair there is a player from the first team and a player from the second team. Every chess player should be in exactly one pair. Every pair plays once. The drawing is totally random.Is it possible to divide all 2·n players into two teams with n people each so that the player from the first team in every pair wins regardless of the results of the drawing?

int solution() {
  int n;
  scanf("%d", &n);
  int arr[2 * n];
  int i = 0;
  int j = 0;
  for (i = 0; i < 2 * n; i++) {
    scanf("%d ", &arr[i]);
  }
  for (i = 0; i < 2 * n; i++) {
    for (j = i + 1; j < 2 * n; j++) {
      if (arr[i] > arr[j]) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }
  }
  for (i = 0; i < n; i++) {
    for (j = n; j < 2 * n; j++) {
      if (arr[i] == arr[j]) {
        printf("NO");
        return 0;
      }
    }
  }
  printf("YES");
}

fn solution() {
    let mut reader = BufReader::new(io::stdin());
    let mut res = String::new();
    reader
        .read_to_string(&mut res)
        .expect("Could not read stdin");
    let values: Vec<&str> = res.split_whitespace().collect();

    let n: usize = values[0].parse().unwrap();
    let mut players: Vec<u16> = values[1..].iter().map(|s| s.parse().unwrap()).collect();

    players.sort();
    if players[n - 1] == players[n] {
        println!("NO");
    } else {
        println!("YES");
    }
}


void solution(int arr[]) {
  const int NARRAY = 8;
  const int NBUCKET = 5;
  const int INTERVAL = 10;

  int i, j;
  struct Node **buckets;

  buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);

  for (i = 0; i < NBUCKET; ++i) {
    buckets[i] = NULL;
  }

  for (i = 0; i < NARRAY; ++i) {
    struct Node *current;
    int pos = arr[i] / INTERVAL;

    current = (struct Node *)malloc(sizeof(struct Node));
    current->data = arr[i];

    current->next = buckets[pos];
    buckets[pos] = current;
  }

  for (i = 0; i < NBUCKET; i++) {
    struct Node *p;

    printf("Bucket[\"%d\"] : ", i);

    p = buckets[i];
    while (p) {
      printf("%d ", p->data);
      p = p->next;
    }

    printf("\n");
  }

  for (i = 0; i < NBUCKET; ++i) {
    struct Node *list;
    struct Node *k;

    list = buckets[i];

    if (list == NULL || list->next == NULL) {
      buckets[i] = list;
      continue;
    }

    k = list->next;
    list->next = NULL;

    while (k != NULL) {
      struct Node *ptr;

      if (list->data > k->data) {
        struct Node *tmp;

        tmp = k;
        k = k->next;

        tmp->next = list;
        list = tmp;

        continue;
      }

      for (ptr = list; ptr->next != NULL; ptr = ptr->next) {
        if (ptr->next->data > k->data)
          break;
      }

      if (ptr->next != NULL) {
        struct Node *tmp;

        tmp = k;
        k = k->next;

        tmp->next = ptr->next;
        ptr->next = tmp;

        continue;
      } else {

        ptr->next = k;
        k = k->next;

        ptr->next->next = NULL;

        continue;
      }
    }

    buckets[i] = list;
  }

  printf("--------------\n");
  printf("Buckets after sorted\n");

  for (i = 0; i < NBUCKET; i++) {
    struct Node *p;

    printf("Bucket[\"%d\"] : ", i);

    p = buckets[i];
    while (p) {
      printf("%d ", p->data);
      p = p->next;
    }

    printf("\n");
  }

  for (j = 0, i = 0; i < NBUCKET; ++i) {
    struct Node *node;

    node = buckets[i];

    while (node) {
      assert(j < NARRAY);

      arr[j++] = node->data;
      node = node->next;
    }
  }

  for (i = 0; i < NBUCKET; ++i) {
    struct Node *node;

    node = buckets[i];

    while (node) {
      struct Node *tmp;

      tmp = node;
      node = node->next;

      free(tmp);
    }
  }

  free(buckets);
}

fn solution(arr: &[usize]) -> Vec<usize> {
    if arr.is_empty() {
        return vec![];
    }

    let max = *arr.iter().max().unwrap();
    let len = arr.len();
    let mut buckets = vec![vec![]; len + 1];

    for x in arr {
        buckets[len * *x / max].push(*x);
    }

    for bucket in buckets.iter_mut() {
        super::insertion_sort(bucket);
    }

    let mut result = vec![];
    for bucket in buckets {
        for x in bucket {
            result.push(x);
        }
    }

    result
}


Transformation

  Write a program which performs a sequence of commands to a given string $str$. The command is one of:

print a b: print from the <apan>a-th character to the b-th character of $str$

reverse a b: reverse from the a-th character to the b-th character of $str$

replace a b p: replace from the a-th character to the b-th character of $str$ with p

  Note that the indices of $str$ start with 0.

Input

  In the first line, a string $str$ is given. $str$ consists of lowercase letters. In the second line, the number of commands <var>q</var> is given. In the next <var>q</var> lines, each command is given in the above mentioned format.

Output

For each print command, print a string in a line.

Constraints

$1 \leq $ length of $str \leq 1000$

$1 \leq q \leq 100$

$0 \leq a \leq b < $ length of $str$

for replace command, $b - a + 1 = $ length of $p$

Sample Input 1

abcde
3
replace 1 3 xyz
reverse 0 2
print 1 4

Sample Output 1

xaze

Sample Input 2

xyz
3
print 0 2
replace 0 2 abc
print 0 2

Sample Output 2

xyz
abc

int solution() {
  char str[1000];
  char operation[10];
  int operation_number = 0;
  int a = 0;
  int b = 0;
  int i = 0;
  char p[1000];
  char tmp;
  scanf("%s", str);
  scanf("%d", &operation_number);

  while (operation_number > 0) {
    scanf("%s %d %d", operation, &a, &b);
    if (strcmp(operation, "replace") == 0) {
      scanf("%s", p);
    }
    if (strcmp(operation, "print") == 0) {
      while (a <= b) {
        printf("%c", str[a]);
        if (a == b) {
          printf("\n");
        }
        a++;
      }
    } else if (strcmp(operation, "reverse") == 0) {
      while (a <= b) {
        tmp = str[b];
        str[b] = str[a];
        str[a] = tmp;
        b--;
        a++;
      }
    } else if (strcmp(operation, "replace") == 0) {
      i = 0;
      while (a <= b) {
        str[a] = p[i];
        a++;
        i++;
      }
    }
    operation_number--;
  }

  return 0;
}

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

    let mut n = String::new();
    io::stdin().read_line(&mut n).unwrap();
    let n: i32 = n.trim().parse().unwrap();

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

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

        match command {
            "replace" => {
                let p = iter.next().unwrap();

                let f = s[0..a].to_string();
                let t = s[b + 1..].to_string();

                s = f + p;
                s = s + &t;
            }
            "reverse" => {
                let f = s[0..a].to_string();
                let m = s[a..b + 1].to_string().chars().rev().collect::<String>();
                let t = s[b + 1..].to_string();

                s = f + &m;
                s = s + &t;
            }
            _ => {
                println!("{}", &s[a..b + 1]);
            }
        }
    }
}


You have a string $$$s$$$ consisting of digits from $$$0$$$ to $$$9$$$ inclusive. You can perform the following operation any (possibly zero) number of times:   You can choose a position $$$i$$$ and delete a digit $$$d$$$ on the $$$i$$$-th position. Then insert the digit $$$\min{(d + 1, 9)}$$$ on any position (at the beginning, at the end or in between any two adjacent digits). What is the lexicographically smallest string you can get by performing these operations?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a smaller digit than the corresponding digit in $$$b$$$.

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

    for _ in 0..tests_str.trim().parse::<usize>().unwrap() {
        let mut s_str = String::new();
        std::io::stdin().read_line(&mut s_str).unwrap();

        let mut new_chars = Vec::new();
        let mut min_seen = b'9';

        for c in s_str.trim().bytes().rev() {
            if c <= min_seen {
                min_seen = c;
                new_chars.push(c);
            } else {
                new_chars.push((c + 1).min(b'9'));
            }
        }

        new_chars.sort_unstable();
        println!("{}", String::from_utf8_lossy(&new_chars));
    }
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> empty boxes arranged in a row from left to right.
The integer <var>i</var> is written on the <var>i</var>-th box from the left <var>(1 \leq i \leq N)</var>.

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer <var>i</var> between <var>1</var> and <var>N</var> (inclusive), the total number of balls contained in the boxes with multiples of <var>i</var> written on them is congruent to <var>a_i</var> modulo <var>2</var>.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

<var>a_i</var> is <var>0</var> or <var>1</var>.

Input

Input is given from Standard Input in the following format:

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

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

<var>M</var>
<var>b_1</var> <var>b_2</var> <var>...</var> <var>b_M</var>

where <var>M</var> denotes the number of boxes that will contain a ball, and <var>b_1,\ b_2,\ ...,\ b_M</var> are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with <var>1</var> written on it.

There are three boxes with multiples of <var>1</var> written on them: the boxes with <var>1</var>, <var>2</var>, and <var>3</var>. The total number of balls contained in these boxes is <var>1</var>.

There is only one box with a multiple of <var>2</var> written on it: the box with <var>2</var>. The total number of balls contained in these boxes is <var>0</var>.

There is only one box with a multiple of <var>3</var> written on it: the box with <var>3</var>. The total number of balls contained in these boxes is <var>0</var>.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.

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

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

  int ans[N];
  for (int i = 0; i < N; i++) {
    ans[i] = 0;
  }

  int ball = 0;
  for (int i = N; i >= 1; i--) {
    if (i == 1) {
      if (ball % 2 != a[i - 1]) {
        ans[i - 1] = 1;
        ball++;
      }
      break;
    }
    int count = 0;
    for (int j = 1;; j++) {
      if (i * j - 1 >= N) {
        break;
      }
      count += ans[(i * j) - 1];
    }
    if (count % 2 != a[i - 1]) {
      ans[i - 1] = 1;
      ball++;
    }
  }

  printf("%d\n", ball);
  for (int i = 0; i < N; i++) {
    if (ans[i] == 1) {
      ball--;
      printf("%d", i + 1);
      if (ball == 0) {
        printf("\n");
      } else {
        printf(" ");
      }
    }
  }

  return 0;
}

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

    let mut array = String::new();
    stdin().read_line(&mut array).unwrap();
    let array: Vec<u8> = array.split_whitespace().flat_map(str::parse).collect();
    let mut boxes = [0; 200002];

    let mut result = vec![];
    for (i, &a) in array.iter().enumerate().rev() {
        let mut total = 0;
        let mut j = i + 1;
        while j <= n {
            total += boxes[j];
            j += i + 1;
        }
        if total % 2 != a {
            boxes[i + 1] += 1;
            result.push(format!("{}", i + 1));
        }
    }

    println!("{}", result.len());
    println!("{}", result.join(" "));
}


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

int solution() {
  int n;
  int k;
  scanf("%d %d\n", &n, &k);
  char str[n + 1];
  scanf("%s", str);
  int count = 0;
  for (int i = 0; i < 26 && count < k; i++) {
    for (int j = 0; j < n; j++) {
      if (str[j] == i + 97 && count < k) {
        str[j] = '.';
        count++;
      } else if (count == k) {
        break;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    if (str[i] != '.') {
      printf("%c", str[i]);
    }
  }
}

fn solution() {
    let stdin: io::Stdin = io::stdin();
    let mut lines: io::Lines<io::StdinLock> = stdin.lock().lines();

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

    let flv: Vec<_> = next_line
        .trim()
        .split(' ')
        .map(|n| n.parse::<u32>().unwrap())
        .collect();

    let k = flv[1];

    let mut s: String = lines.next().unwrap().unwrap().trim().to_string();

    let abc = "abcdefghijklmnopqrstuvwxyz";
    let mut rc = 0;
    let mut v: Vec<usize> = vec![];

    'outer: for c in abc.chars() {
        for (i, cc) in s.chars().enumerate() {
            if rc == k {
                break 'outer;
            }
            if c == cc {
                v.push(i);
                rc += 1;
            }
        }
    }

    v.sort();
    for i in v.iter().rev() {
        s.remove(*i);
    }

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


Timur has a stairway with $$$n$$$ steps. The $$$i$$$-th step is $$$a_i$$$ meters higher than its predecessor. The first step is $$$a_1$$$ meters higher than the ground, and the ground starts at $$$0$$$ meters.   The stairs for the first test case. Timur has $$$q$$$ questions, each denoted by an integer $$$k_1, \dots, k_q$$$. For each question $$$k_i$$$, you have to print the maximum possible height Timur can achieve by climbing the steps if his legs are of length $$$k_i$$$. Timur can only climb the $$$j$$$-th step if his legs are of length at least $$$a_j$$$. In other words, $$$k_i \geq a_j$$$ for each step $$$j$$$ climbed.Note that you should answer each question independently.

int solution() {
  int zushu;
  scanf("%d", &zushu);
  for (int zu = 1; zu <= zushu; zu++) {
    int n;
    int q;
    scanf("%d%d", &n, &q);

    if (zu != 1) {
      printf("\n");
    }
    long long int step[n + 1][2];
    long long int temp;
    step[0][0] = 0;
    step[0][1] = 0;
    for (int i = 1; i <= n; i++) {
      scanf("%lld", &temp);
      step[i][0] = (temp > step[i - 1][0]) ? temp : step[i - 1][0];
      step[i][1] = step[i - 1][1] + temp;
    }
    for (int i = 1; i <= q; i++) {
      if (i != 1) {
        printf(" ");
      }
      long long int h;
      long long int left = 1;
      long long int right = n;
      scanf("%lld", &h);
      if (step[n][0] <= h) {
        printf("%lld", step[n][1]);
        right = 0;
      } else if (step[1][0] > h) {
        printf("0");
        right = 0;
      }
      while (left < right) {
        long long int mid = (left + right) / 2;

        if (step[mid][0] == h) {
          left = mid;
          break;
        }
        if (step[mid][0] < h)
          left = mid + 1;
        else
          right = mid;
      }
      if (right != 0) {
        while (step[left][0] == h) {
          left++;
        }
        printf("%lld", step[left - 1][1]);
      }
    }
  }

  return 0;
}

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

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

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

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

        let mut max_height = vec![0; n + 1];
        let mut sum_height = vec![0; n + 1];

        for i in 0..n {
            let h = a[i];

            max_height[i + 1] = std::cmp::max(max_height[i], h);
            sum_height[i + 1] = sum_height[i] + h;
        }

        let mut ans = vec![0; q];

        for i in 0..q {
            let qu = b[i];

            let mut OK = 0;
            let mut NG = n + 1;

            while NG > OK + 1 {
                let mid = (OK + NG) / 2;

                if max_height[mid] <= qu {
                    OK = mid;
                } else {
                    NG = mid;
                }
            }

            ans[i] = sum_height[OK];
        }

        println!(
            "{}",
            ans.iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        );
    }
}


Score : <var>100</var> points

Problem Statement

It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board.

The bulletin board is in the form of a grid with <var>N</var> rows and <var>N</var> columns, and the notice will occupy a rectangular region with <var>H</var> rows and <var>W</var> columns.

How many ways are there to choose where to put the notice so that it completely covers exactly <var>HW</var> squares?

Constraints

<var>1 \leq H, W \leq N \leq 100</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>H</var>
<var>W</var>

Output

Print the answer.

Sample Input 1

3
2
3

Sample Output 1

2

There are two ways to put the notice, as follows:

###   ...
###   ###
...   ###

Here, # represents a square covered by the notice, and . represents a square not covered.

Sample Input 2

100
1
1

Sample Output 2

10000

Sample Input 3

5
4
2

Sample Output 3

8

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

    let n: isize = {
        handle.read_line(&mut buf).unwrap();
        let tmp = buf.trim().parse().unwrap();
        buf.clear();
        tmp
    };
    let h: isize = {
        handle.read_line(&mut buf).unwrap();
        let tmp = buf.trim().parse().unwrap();
        buf.clear();
        tmp
    };
    let w: isize = {
        handle.read_line(&mut buf).unwrap();
        let tmp = buf.trim().parse().unwrap();
        buf.clear();
        tmp
    };
    println!("{}", (n - h + 1) * (n - w + 1));
}


"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme.""Little Alena got an array as a birthday present..."The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:b1 = b2 = b3 = b4 = 0.For all 5 ≤ i ≤ n:   bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1  bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0  bi = bi - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and r (l ≤ r), such that applying the algorithm described above will yield an array b equal to b'.It's guaranteed that the answer exists.

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

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

  char b[n + 1];
  scanf("%s", b);

  int lmin = -1000000000;
  int rmax = 1000000000;
  for (int i = 4; i < n; i++) {
    bool same = true;
    for (int j = 1; j < 4; j++) {
      if (b[i - j] != b[i - j - 1]) {
        same = false;
        break;
      }
    }

    if (!same || b[i] == b[i - 1]) {
      continue;
    }

    if (b[i] == '0') {
      int min = a[i];
      for (int j = 1; j < 5; j++) {
        if (a[i - j] < min) {
          min = a[i - j];
        }
      }

      if (rmax > min) {
        rmax = min - 1;
      }
    } else {
      int max = a[i];
      for (int j = 1; j < 5; j++) {
        if (a[i - j] > max) {
          max = a[i - j];
        }
      }

      if (lmin < max) {
        lmin = max + 1;
      }
    }
  }

  printf("%d %d\n", lmin, rmax);
}

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

    let mut it = input.split_whitespace();

    let n: usize = it.next().unwrap().parse().unwrap();

    let mut a = Vec::with_capacity(n);
    for _ in 0..n {
        let x: i32 = it.next().unwrap().parse().unwrap();
        a.push(x);
    }

    let mut bp = Vec::with_capacity(n);
    for b in it.next().unwrap().bytes() {
        let x = match b {
            b'0' => false,
            b'1' => true,
            _ => unreachable!(),
        };
        bp.push(x);
    }

    let mut cl = Vec::new();

    let mut it = bp.iter();
    let mut cur = *it.next().unwrap();
    let mut cnt = 1;

    for (i, &b) in it.enumerate() {
        if cnt >= 4 {
            cl.push(i + 1);
        }

        if cur != b {
            cur = b;
            cnt = 0;
        } else {
            cnt += 1;
        }
    }

    let mut l = -1_000_000_000;
    let mut r = 1_000_000_000;

    for i in cl {
        let x = bp[i];
        if x {
            if bp[i - 1] != x {
                let y = *a[i - 4..i + 1].iter().max().unwrap() + 1;
                if l < y {
                    l = y;
                }
            } else {
                let y = *a[i - 4..i + 1].iter().min().unwrap();
                if r < y {
                    r = y;
                }
            }
        } else {
            if bp[i - 1] != x {
                let y = *a[i - 4..i + 1].iter().min().unwrap() - 1;
                if y < r {
                    r = y;
                }
            } else {
                let y = *a[i - 4..i + 1].iter().max().unwrap();
                if y < l {
                    l = y;
                }
            }
        }
    }

    println!("{} {}", l, r);
}


A + B Problem

Compute A + B.

Input

The input will consist of a series of pairs of integers A and B separated by a space, one pair of integers per line. The input will be terminated by EOF.

Output

For each pair of input integers A and B, you must output the sum of A and B in one line.

Constraints

 -1000 ≤ A, B ≤ 1000

Sample Input

1 2
10 5
100 20

Output for the Sample Input

3
15
120

Sample Program

#include<stdio.h>

int main(){
    int a, b;
    while( scanf("%d %d", &a, &b) != EOF ){
        printf("%d\n", a + b);
    }
    return 0;
}

int solution() {

  int a = 0;
  int b = 0;

  while (scanf("%d %d", &a, &b) != EOF) {
    printf("%d\n", a + b);
  }

  return 0;
}

fn solution() {
    let mut input: String;
    loop {
        input = String::new();
        match std::io::stdin().read_line(&mut input) {
            Ok(0) => {
                break;
            }
            Ok(_) => {
                println!(
                    "{}",
                    input
                        .split_whitespace()
                        .fold(0, |x, y| x + y.parse::<i32>().unwrap())
                );
            }
            Err(_) => {}
        };
    }
}