Score : <var>700</var> points

Problem Statement

There is a sequence <var>X</var> of length <var>N</var>, where every element is initially <var>0</var>. Let <var>X_i</var> denote the <var>i</var>-th element of <var>X</var>.

You are given a sequence <var>A</var> of length <var>N</var>. The <var>i</var>-th element of <var>A</var> is <var>A_i</var>. Determine if we can make <var>X</var> equal to <var>A</var> by repeating the operation below. If we can, find the minimum number of operations required.

Choose an integer <var>i</var> such that <var>1\leq i\leq N-1</var>. Replace the value of <var>X_{i+1}</var> with the value of <var>X_i</var> plus <var>1</var>.

Constraints

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

<var>0 \leq A_i \leq 10^9(1\leq i\leq N)</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If we can make <var>X</var> equal to <var>A</var> by repeating the operation, print the minimum number of operations required. If we cannot, print <var>-1</var>.

Sample Input 1

4
0
1
1
2

Sample Output 1

3

We can make <var>X</var> equal to <var>A</var> as follows:

Choose <var>i=2</var>. <var>X</var> becomes <var>(0,0,1,0)</var>.

Choose <var>i=1</var>. <var>X</var> becomes <var>(0,1,1,0)</var>.

Choose <var>i=3</var>. <var>X</var> becomes <var>(0,1,1,2)</var>.

Sample Input 2

3
1
2
1

Sample Output 2

-1

Sample Input 3

9
0
1
1
0
1
2
2
1
2

Sample Output 3

8

int solution(void) {
  long long n;
  long long ans = 0;
  scanf("%lld", &n);
  long long a[n + 1];
  a[n] = 0;
  for (long long i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
  }
  if (n == 1) {
    if (a[0] == 0) {
      printf("0\n");
    } else {
      printf("-1\n");
    }
    return 0;
  }
  for (long long i = 1; i < n; i++) {
    if (a[i] > a[i - 1] + 1 || a[i] > i || a[0] != 0) {
      printf("-1\n");
      return 0;
    }
    if (a[i] >= a[i + 1]) {
      ans += a[i];
    }
  }
  printf("%lld\n", ans);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<usize>().unwrap();
    let mut a: Vec<usize> = BufReader::new(stdin())
        .lines()
        .map(|l| l.unwrap().trim().parse::<usize>().unwrap())
        .collect();
    for (i, &n) in a.iter().enumerate() {
        if n > i {
            println!("-1");
            return;
        }
    }
    a.reverse();
    let mut tmp = n + 1;
    let mut total = 0;
    for i in a {
        if tmp < n + 1 && i + 1 < tmp {
            println!("-1");
            return;
        }
        if i + 1 != tmp {
            total += i;
        }
        tmp = i;
    }
    println!("{}", total);
}


This is an interactive problem.We hid from you a permutation $$$p$$$ of length $$$n$$$, consisting of the elements from $$$1$$$ to $$$n$$$. You want to guess it. To do that, you can give us 2 different indices $$$i$$$ and $$$j$$$, and we will reply with $$$p_{i} \bmod p_{j}$$$ (remainder of division $$$p_{i}$$$ by $$$p_{j}$$$).We have enough patience to answer at most $$$2 \cdot n$$$ queries, so you should fit in this constraint. Can you do it?As a reminder, a permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

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

    let mut ans = vec![0; n + 1];
    let mut unk_idx = 1;
    for i in 2..=n {
        println!("? {} {}", unk_idx, i);
        let k1: usize = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            buf.trim_end().parse().unwrap()
        };
        println!("? {} {}", i, unk_idx);
        let k2: usize = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            buf.trim_end().parse().unwrap()
        };

        if k1 < k2 {
            ans[i] = k2;
        } else {
            ans[unk_idx] = k1;
            unk_idx = i;
        }
    }
    ans[unk_idx] = n;
    println!(
        "! {}",
        ans.iter()
            .skip(1)
            .map(|val| val.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    );
}


Score : <var>100</var> points

Problem Statement

You are given positive integers <var>X</var> and <var>Y</var>.
If there exists a positive integer not greater than <var>10^{18}</var> that is a multiple of <var>X</var> but not a multiple of <var>Y</var>, choose one such integer and print it.
If it does not exist, print <var>-1</var>.

Constraints

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

<var>X</var> and <var>Y</var> are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print a positive integer not greater than <var>10^{18}</var> that is a multiple of <var>X</var> but not a multiple of <var>Y</var>, or print <var>-1</var> if it does not exist.

Sample Input 1

8 6

Sample Output 1

16

For example, <var>16</var> is a multiple of <var>8</var> but not a multiple of <var>6</var>.

Sample Input 2

3 3

Sample Output 2

-1

A multiple of <var>3</var> is a multiple of <var>3</var>.

int solution() {
  int a;
  int b;
  int x;
  scanf("%d %d", &a, &b);
  x = -1;
  if (b != 0 && a % b != 0) {
    x = a;
  }
  printf("%d\n", x);
  return 0;
}

fn solution() {
    let base: u64 = 10;
    let scan = stdin();
    let mut line = String::new();

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

    let mut iter = line.split_whitespace();
    let x: u64 = iter
        .next()
        .expect("Iteration Error?")
        .trim()
        .parse()
        .expect("Number pls...");
    let y: u64 = iter
        .next()
        .expect("Iteration Error?")
        .trim()
        .parse()
        .expect("Number pls...");

    if x == y {
        println!("{}", -1);
        return;
    }

    let mut i: u64 = 1;
    loop {
        let mul: u64 = x * i;
        i += 1;

        if mul >= base.pow(18) {
            println!("{}", -1);
            return;
        }

        if i > 3 {
            println!("{}", -1);
            return;
        }

        if !mul.is_multiple_of(y) {
            println!("{}", mul);
            return;
        }
    }
}


Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.

int solution() {
  int n = 0;
  scanf("%d", &n);
  int nr = n;
  int size = 1;
  int tow[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &tow[i]);
  }

  int dub[1001] = {0};
  for (int i = 0; i < n; i++) {
    if (dub[i] == 1) {
      continue;
    }
    int sz = 1;
    for (int j = i + 1; j < n; j++) {

      if (tow[i] == tow[j]) {
        sz++;
        nr--;
        dub[j] = 1;
      }
    }
    if (sz > size) {
      size = sz;
    }
  }
  printf("%d %d", size, nr);
}

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

    let mut s1 = String::new();
    std::io::stdin().read_line(&mut s1).unwrap();
    let mut v: Vec<usize> = s1
        .trim_end()
        .to_string()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    v.sort();

    let mut max_len: usize = 0;
    let mut h = 1;

    let mut p: usize = 0;
    while p < n {
        let mut q: usize = p + 1;
        while q < n {
            if v[p] != v[q] {
                h += 1;
                break;
            }

            q += 1;
        }

        if max_len < q - p {
            max_len = q - p;
        }

        p = q;
    }

    println!("{} {}", max_len, h);
}


As their story unravels, a timeless tale is told once again...Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow.There are $$$n$$$ squares arranged in a row, and each of them can be painted either red or blue.Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square.Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color.For example, the imperfectness of "BRRRBBR" is $$$3$$$, with "BB" occurred once and "RR" occurred twice.Your goal is to minimize the imperfectness and print out the colors of the squares after painting.

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

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

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

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

        let mut a = lines.next().unwrap().into_bytes();

        let (first_span, s) = match a.iter().position(|&b| b != b'?') {
            Some(i) => a.split_at_mut(i),
            None => {
                let mut i = 0;
                while i < n {
                    output.write(b"B").unwrap();
                    i += 1;
                    if i == n {
                        break;
                    }
                    output.write(b"R").unwrap();
                    i += 1;
                }
                writeln!(&mut output).unwrap();
                continue 'cases;
            }
        };

        let j = s
            .iter()
            .enumerate()
            .rev()
            .find_map(|(j, &b)| if b != b'?' { Some(j) } else { None })
            .unwrap();
        let (s, last_span) = s.split_at_mut(j + 1);

        let mut x = *s.first().unwrap() == b'B';
        for b in first_span.iter_mut().rev() {
            x = !x;
            *b = if x { b'B' } else { b'R' }
        }

        let mut x = *s.last().unwrap() == b'B';
        for b in last_span.iter_mut() {
            x = !x;
            *b = if x { b'B' } else { b'R' }
        }

        let mut x = *s.first().unwrap() == b'B';
        for b in s.iter_mut().skip(1) {
            match *b {
                b'R' => x = false,
                b'B' => x = true,
                _ => {
                    x = !x;
                    *b = if x { b'B' } else { b'R' }
                }
            }
        }

        output.write_all(a.as_slice()).unwrap();
        writeln!(&mut output).unwrap();
    }
}


Your friend Mishka and you attend a calculus lecture. Lecture lasts n minutes. Lecturer tells ai theorems during the i-th minute.Mishka is really interested in calculus, though it is so hard to stay awake for all the time of lecture. You are given an array t of Mishka's behavior. If Mishka is asleep during the i-th minute of the lecture then ti will be equal to 0, otherwise it will be equal to 1. When Mishka is awake he writes down all the theorems he is being told — ai during the i-th minute. Otherwise he writes nothing.You know some secret technique to keep Mishka awake for k minutes straight. However you can use it only once. You can start using it at the beginning of any minute between 1 and n - k + 1. If you use it on some minute i then Mishka will be awake during minutes j such that  and will write down all the theorems lecturer tells.You task is to calculate the maximum number of theorems Mishka will be able to write down if you use your technique only once to wake him up.

int solution() {
  int n;
  int k;
  scanf("%d%d", &n, &k);
  int matrix[2][n];
  int beiyong[n];
  memset(matrix, 0, sizeof(int) * 2 * n);
  memset(beiyong, 0, sizeof(int) * n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &matrix[0][i]);
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &matrix[1][i]);
  }

  int score = 0;
  for (int j = 0; j < n; j++) {
    if (matrix[1][j] == 1) {
      score += matrix[0][j];
    } else {
      beiyong[j] = matrix[0][j];
    }
  }
  int maxScore = 0;
  int cont = 0;
  for (int l = 0; l < k; l++) {
    cont += beiyong[l];
  }
  maxScore = maxScore > cont ? maxScore : cont;
  for (int j = 0; j < n - k; j++) {
    cont = cont - beiyong[j];
    cont += beiyong[j + k];
    maxScore = maxScore > cont ? maxScore : cont;
  }
  printf("%d", maxScore + score);
  return 0;
}

fn solution() {
    let mut input1 = String::new();
    io::stdin().read_line(&mut input1);
    let mut iter1 = input1
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());
    let n = iter1.next().unwrap();
    let k = iter1.next().unwrap();

    let mut input2 = String::new();
    io::stdin().read_line(&mut input2);
    let mut theorem_arr = input2
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());

    let mut input3 = String::new();
    io::stdin().read_line(&mut input3);
    let mut awake_arr = input3
        .split_whitespace()
        .map(|x| x.parse::<u8>().unwrap() == 1);

    let _y = n - k + 1;

    let mut highest_sum = 0;
    let mut highest_bonus = 0;
    let mut bonus = 0;
    let mut previous_sleep = vec![0; k];
    for i in 0..n {
        let t = theorem_arr.next().unwrap();
        let a = awake_arr.next().unwrap();
        if a {
            highest_sum += t;
            bonus -= previous_sleep[i];
            previous_sleep.push(0);
        } else {
            bonus += t;
            bonus -= previous_sleep[i];
            highest_bonus = max(highest_bonus, bonus);
            previous_sleep.push(t);
        }
    }

    println!("{}", highest_sum + highest_bonus);
}


Score : <var>200</var> points

Problem Statement

We have <var>N</var> points in the two-dimensional plane. The coordinates of the <var>i</var>-th point are <var>(X_i,Y_i)</var>.

Among them, we are looking for the points such that the distance from the origin is at most <var>D</var>. How many such points are there?

We remind you that the distance between the origin and the point <var>(p, q)</var> can be represented as <var>\sqrt{p^2+q^2}</var>.

Constraints

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

<var>0 \leq D \leq 2\times 10^5</var>

<var>|X_i|,|Y_i| \leq 2\times 10^5</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>D</var>
<var>X_1</var> <var>Y_1</var>
<var>\vdots</var>
<var>X_N</var> <var>Y_N</var>

Output

Print an integer representing the number of points such that the distance from the origin is at most <var>D</var>.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

<var>\sqrt{0^2+5^2}=5</var>

<var>\sqrt{(-2)^2+4^2}=4.472\ldots</var>

<var>\sqrt{3^2+4^2}=5</var>

<var>\sqrt{4^2+(-4)^2}=5.656\ldots</var>

Thus, we have three points such that the distance from the origin is at most <var>5</var>.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6

int solution(void) {
  int n = 0;
  long int d = 0;
  long int a = 0;
  long int b = 0;
  int count = 0;

  scanf("%d %ld", &n, &d);
  d *= d;

  while (n--) {
    scanf("%ld %ld", &a, &b);
    if (d >= (a * a + b * b)) {
      count++;
    }
  }

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

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

    let mut ans = 0;
    for _ in 0..n {
        let (x, y): (i64, i64) = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        if x * x + y * y <= d * d {
            ans += 1;
        }
    }
    println!("{}", ans);
}


Score : <var>200</var> points

Problem Statement

There are <var>2000001</var> stones placed on a number line. The coordinates of these stones are <var>-1000000, -999999, -999998, \ldots, 999999, 1000000</var>.

Among them, some <var>K</var> consecutive stones are painted black, and the others are painted white.

Additionally, we know that the stone at coordinate <var>X</var> is painted black.

Print all coordinates that potentially contain a stone painted black, in ascending order.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print all coordinates that potentially contain a stone painted black, in ascending order, with spaces in between.

Sample Input 1

3 7

Sample Output 1

5 6 7 8 9

We know that there are three stones painted black, and the stone at coordinate <var>7</var> is painted black. There are three possible cases:

The three stones painted black are placed at coordinates <var>5</var>, <var>6</var>, and <var>7</var>.

The three stones painted black are placed at coordinates <var>6</var>, <var>7</var>, and <var>8</var>.

The three stones painted black are placed at coordinates <var>7</var>, <var>8</var>, and <var>9</var>.

Thus, five coordinates potentially contain a stone painted black: <var>5</var>, <var>6</var>, <var>7</var>, <var>8</var>, and <var>9</var>.

Sample Input 2

4 0

Sample Output 2

-3 -2 -1 0 1 2 3

Negative coordinates can also contain a stone painted black.

Sample Input 3

1 100

Sample Output 3

100

int solution(void) {
  int K = 0;
  int X = 0;
  int min = 0;
  int max = 0;
  scanf("%d %d", &K, &X);
  min = X - K + 1;
  max = X + K - 1;
  for (int i = min; i <= max; i++) {
    printf("%d ", i);
  }
  printf("\n");
  return 0;
}

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

    let from = x - k + 1;
    let to = x + k - 1;
    println!(
        "{}",
        (from..to + 1)
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    );
}


Balls and Boxes 8

Balls	Boxes	Any way	At most one ball	At least one ball

Distinguishable	Distinguishable	1	2	3

Indistinguishable	Distinguishable	4	5	6

Distinguishable	Indistinguishable	7	8	9

Indistinguishable	Indistinguishable	10	11	12

Problem

You have $n$ balls and $k$ boxes. You want to put these balls into the boxes.

Find the number of ways to put the balls under the following conditions:

Each ball is distinguished from the other.

Each box is not distinguished from the other.

Each ball can go into only one box and no one remains outside of the boxes.

Each box can contain at most one ball.

Note that you must print this count modulo $10^9+7$.

Input

$n$ $k$

The first line will contain two integers $n$ and $k$.

Output

Print the number of ways modulo $10^9+7$ in a line.

Constraints

$1 \le n \le 1000$

$1 \le k \le 1000$

Sample Input 1

5 10

Sample Output 1

1

Sample Input 2

200 100

Sample Output 2

0

int solution() {
  int n;
  int k;

  scanf("%d%d", &n, &k);
  puts(n <= k ? "1" : "0");
  return 0;
}

fn solution() {
    input!(n:i64,k:i64);
    if n > k {
        println!("0");
    } else {
        println!("1");
    }
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \ldots, a_n$$$ is possible to divide into.

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

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

    if (store[0] != 0) {
      count = count + 1;
    }
    for (int j = 1; j <= m / 2; j++) {

      if (store[j] > store[m - j]) {
        count++;
        store[j] = store[j] - store[m - j] - 1;
        count = count + store[j];

      } else if (store[j] < store[m - j]) {
        count++;
        store[m - j] = store[m - j] - store[j] - 1;
        count = count + store[m - j];
      } else if (store[j] == store[m - j]) {
        if (store[j] != 0) {
          count++;
        }
      }
    }

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

fn solution() {
    let mut n = String::new();
    io::stdin().read_line(&mut n).unwrap();
    let n = n.trim().parse().unwrap();
    for _i in 0..n {
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        let v = s
            .split_whitespace()
            .map(|x| x.parse::<i32>())
            .collect::<Result<Vec<i32>, _>>()
            .unwrap();
        let mut _n = v[0];
        let m = v[1];
        let mut g = String::new();
        io::stdin().read_line(&mut g).unwrap();
        let a = g
            .split_whitespace()
            .map(|x| x.parse::<i32>())
            .collect::<Result<Vec<i32>, _>>()
            .unwrap();
        let mut v = vec![0; m as usize];
        for el in a {
            v[(el % m) as usize] += 1;
        }
        let mut ans = 0;
        for i in 0..m {
            let j = (m - i) % m;
            if i > j {
                continue;
            }
            let mut mx = cmp::max(v[i as usize], v[j as usize]);
            let mn = cmp::min(v[i as usize], v[j as usize]);
            if mx == 0 {
                continue;
            }
            mx -= mn + 1;
            ans += 1;
            if mx > 0 {
                ans += mx;
            }
        }
        println!("{}", ans);
    }
}


There are $$$n$$$ friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.For each friend the value $$$f_i$$$ is known: it is either $$$f_i = 0$$$ if the $$$i$$$-th friend doesn't know whom he wants to give the gift to or $$$1 \le f_i \le n$$$ if the $$$i$$$-th friend wants to give the gift to the friend $$$f_i$$$.You want to fill in the unknown values ($$$f_i = 0$$$) in such a way that each friend gives exactly one gift and receives exactly one gift and there is no friend who gives the gift to himself. It is guaranteed that the initial information isn't contradictory.If there are several answers, you can print any.

int solution() {
  int i;
  int n;
  scanf("%d", &n);
  int giftGiving[n];
  int giftGetting[n];
  int giftNot[n];
  int top = 0;
  int bottom = 0;
  for (i = 0; i < n; i++) {
    giftGetting[i] = 0;
  }
  for (i = 0; i < n; i++) {
    scanf("%d", &giftGiving[i]);
    giftGetting[giftGiving[i] - 1] = 1;
  }
  for (i = 0; i < n; i++) {
    if (giftGetting[i] != 1) {
      giftNot[bottom++] = i + 1;
    }
  }
  for (i = 0; i < n; i++) {
    if (giftGiving[i] == 0 && giftGetting[i] == 0) {
      if (giftNot[top] == i + 1) {
        giftGiving[i] = giftNot[--bottom];
      } else {
        giftGiving[i] = giftNot[top++];
      }
    }
  }
  for (i = 0; i < n; i++) {
    if (giftGiving[i] == 0) {
      giftGiving[i] = giftNot[top++];
    }
  }
  for (i = 0; i < n; i++) {
    printf("%d ", giftGiving[i]);
  }

  return 0;
}

fn solution() {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).unwrap();
    let n: usize = n.trim().parse().unwrap();
    let mut l2 = String::new();
    std::io::stdin().read_line(&mut l2).unwrap();
    let mut f = Vec::with_capacity(n + 1);
    f.push(0usize);
    for it in l2.split_whitespace() {
        f.push(it.parse().unwrap());
    }
    let mut finv = vec![0; n + 1];
    for u in 1..n + 1 {
        if f[u] != 0 {
            finv[f[u]] = u;
        }
    }
    let mut path = vec![];
    let mut vis = vec![false; n + 1];
    for u in 1..n + 1 {
        if vis[u] {
            continue;
        }
        let mut v = u;
        while f[v] != 0 && f[v] != u {
            v = f[v];
            vis[v] = true;
        }
        if f[v] == u {
            continue;
        }
        let mut w = u;
        while finv[w] != 0 {
            w = finv[w];
            vis[w] = true;
        }
        path.push((w, v));
    }
    for i in 0..path.len() - 1 {
        f[path[i].1] = path[i + 1].0;
    }
    f[path[path.len() - 1].1] = path[0].0;
    for i in 1..n + 1 {
        print!("{}{}", f[i], if i == n { '\n' } else { ' ' });
    }
}


You are given an array $$$a_1, a_2, \dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.

int solution() {
  int t;
  scanf("%d", &t);
  for (int tt = 0; tt < t; tt++) {
    int n;
    scanf("%d", &n);
    int a[n];
    int b[n];
    int min = 1000000000;
    int c = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      b[i] = a[i];
      if (a[i] < min) {
        min = a[i];
      }
    }
    for (int i = 1; i < n; i++) {
      int j = i - 1;
      int temp = a[i];
      while (j >= 0 && a[j] > temp) {
        a[j + 1] = a[j];
        j--;
      }
      a[j + 1] = temp;
    }
    int i;
    for (i = 0; i < n; i++) {
      if (b[i] % min != 0) {
        if (b[i] != a[i]) {
          break;
        }
      }
    }
    if (i == n) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

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

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

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

        let m = *a.iter().min().unwrap();
        let mut indexes = Vec::new();
        let mut values = Vec::new();

        for i in 0..n {
            if a[i] % m == 0 {
                indexes.push(i);
                values.push(a[i]);
            }
        }
        values.sort();

        for (&i, &val) in indexes.iter().zip(values.iter()) {
            a[i] = val;
        }

        if (0..(n - 1)).all(|i| a[i] <= a[i + 1]) {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.

int solution() {
  int count = 0;
  scanf("%d\n", &count);
  int last = 0;
  int i = 0;
  int ninccount = 0;
  int maxinccount = 0;
  for (; i < count; i++) {
    int now = 0;
    scanf("%d", &now);
    if (last < now) {
      ninccount++;
    } else {
      if (maxinccount < ninccount) {
        maxinccount = ninccount;
      }
      ninccount = 1;
    }
    last = now;
  }
  if (maxinccount < ninccount) {
    maxinccount = ninccount;
  }
  printf("%d\n", maxinccount);
}

fn solution() {
    let handle = io::stdin();
    let line = &mut String::new();
    handle.read_line(line).unwrap();
    let n = line.trim().parse::<usize>().unwrap();
    line.clear();
    handle.read_line(line).unwrap();
    let a: &mut Vec<u32> = &mut line
        .split_whitespace()
        .map(|x| x.parse::<u32>().unwrap())
        .collect();

    let mut lm = 0;
    let mut rm = 0;
    let mut l = 0;
    for i in 1..n {
        if a[i] > a[i - 1] {
            if i - l > rm - lm {
                lm = l;
                rm = i;
            }
        } else {
            l = i;
        }
    }

    println!("{}", rm - lm + 1);
}


Score : <var>300</var> points

Problem Statement

The problem set at CODE FESTIVAL 20XX Finals consists of <var>N</var> problems.

The score allocated to the <var>i</var>-th <var>(1≦i≦N)</var> problem is <var>i</var> points.

Takahashi, a contestant, is trying to score exactly <var>N</var> points. For that, he is deciding which problems to solve.

As problems with higher scores are harder, he wants to minimize the highest score of a problem among the ones solved by him.

Determine the set of problems that should be solved.

Constraints

<var>1≦N≦10^7</var>

Partial Score

<var>200</var> points will be awarded for passing the test set satisfying <var>1≦N≦1000</var>.

Additional <var>100</var> points will be awarded for passing the test set without additional constraints.

Input

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

<var>N</var>

Output

Among the sets of problems with the total score of <var>N</var>, find a set in which the highest score of a problem is minimum, then print the indices of the problems in the set in any order, one per line.

If there exists more than one such set, any of them will be accepted.

Sample Input 1

4

Sample Output 1

1
3

Solving only the <var>4</var>-th problem will also result in the total score of <var>4</var> points, but solving the <var>1</var>-st and <var>3</var>-rd problems will lower the highest score of a solved problem.

Sample Input 2

7

Sample Output 2

1
2
4

The set <var>\{3,4\}</var> will also be accepted.

Sample Input 3

1

Sample Output 3

1

int solution() {
  long n = 0;
  long maxi = 0;
  long i = 0;
  long remove = 0;
  scanf("%ld", &n);
  for (i = 1; i < n; i++) {
    if (((i + 1) * i) / 2 >= n) {
      break;
    }
  }
  maxi = i;

  remove = (maxi * (maxi + 1)) / 2 - n;

  for (i = 1; i <= maxi; i++) {
    if (i != remove) {
      printf("%ld\n", i);
    }
  }
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut out = Vec::new();

    let mut ng = 0;
    let mut ok = n;
    while ok - ng > 1 {
        let mid = (ok + ng) >> 1;
        if (1..mid + 1).sum::<usize>() >= n {
            ok = mid;
        } else {
            ng = mid;
        }
    }
    let sum = (1..ok + 1).sum::<usize>();

    for i in 1..ok + 1 {
        if sum - n == i {
            continue;
        }
        writeln!(out, "{}", i).ok();
    }
    stdout().write_all(&out).unwrap();
}


You are given a number $$$k$$$ and a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:   The first character '*' in the original string should be replaced with 'x';  The last character '*' in the original string should be replaced with 'x';  The distance between two neighboring replaced characters 'x' must not exceed $$$k$$$ (more formally, if you replaced characters at positions $$$i$$$ and $$$j$$$ ($$$i < j$$$) and at positions $$$[i+1, j-1]$$$ there is no "x" symbol, then $$$j-i$$$ must be no more than $$$k$$$). For example, if $$$n=7$$$, $$$s=$$$.**.*** and $$$k=3$$$, then the following strings will satisfy the conditions above:   .xx.*xx;  .x*.x*x;  .xx.xxx.  But, for example, the following strings will not meet the conditions:   .**.*xx (the first character '*' should be replaced with 'x');  .x*.xx* (the last character '*' should be replaced with 'x');  .x*.*xx (the distance between characters at positions $$$2$$$ and $$$6$$$ is greater than $$$k=3$$$). Given $$$n$$$, $$$k$$$, and $$$s$$$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int k;
    scanf("%d %d", &n, &k);
    char str[n + 1];
    scanf("%s", str);
    int dis = -1;
    int preindex = 0;
    int bufferdex = 0;
    int tot = 0;
    int nextdex = 0;
    int counttot = 0;
    for (int i = 0; i < n; i++) {
      if (str[i] == '*') {
        counttot++;
      }
    }
    if (counttot == 1) {
      printf("1\n");
    } else {
      for (int i = 0; i < n; i++) {
        if (dis == -1) {
          if (str[i] == '.') {
            continue;
          }
          if (str[i] == '*') {
            dis = 0;
            preindex = i;
          }
        }
        if (dis != -1) {
          if (str[i] == '.' && i - preindex <= k) {
            dis++;
          } else if (str[i] == '.' && i - preindex > k) {
            if (str[preindex] != 'x') {
              tot++;
              str[preindex] = 'x';
              if (nextdex != 0) {
                preindex = nextdex;
                nextdex = 0;
              } else {
                preindex = preindex;
              }
            }
          } else if (str[i] == '*' && i - preindex <= k) {
            nextdex = i;
          } else if (str[i] == '*' && i - preindex > k) {
            if (i - preindex == k + 1) {
              tot++;
              str[preindex] = 'x';
              preindex = nextdex;
              nextdex = i;
            }
          }
        }
      }
      if (nextdex != 0) {
        str[nextdex] = 'x';
        str[preindex] = 'x';
        tot++;
        tot++;
      } else if (nextdex == 0) {
        if (str[preindex] != 'x') {
          str[preindex] = 'x';
          tot++;
        }
      }
      printf("%d\n", tot, str);
    }
  }
  return 0;
}

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, k): (usize, usize) = (sc.next(), sc.next());
        let s: Vec<char> = sc.next::<String>().chars().collect();
        let mut idx: Vec<usize> = vec![];
        for i in 0..n {
            if s[i] == '*' {
                idx.push(i);
            }
        }
        let mut ans: Vec<usize> = vec![0; n];
        let mut last = 0;
        for i in 1..idx.len() {
            if idx[i] - idx[last] > k {
                last = i - 1;
                ans[idx[last]] = 1;
            }
        }
        ans[idx[0]] = 1;
        ans[idx[idx.len() - 1]] = 1;
        writeln!(out, "{}", ans.iter().sum::<usize>()).unwrap();
    }
}


Score : <var>300</var> points

Problem Statement

There are an integer sequence <var>A_1,...,A_N</var> consisting of <var>N</var> terms, and <var>N</var> buttons.
When the <var>i</var>-th <var>(1 ≦ i ≦ N)</var> button is pressed, the values of the <var>i</var> terms from the first through the <var>i</var>-th are all incremented by <var>1</var>.

There is also another integer sequence <var>B_1,...,B_N</var>. Takahashi will push the buttons some number of times so that for every <var>i</var>, <var>A_i</var> will be a multiple of <var>B_i</var>.

Find the minimum number of times Takahashi will press the buttons.

Constraints

All input values are integers.

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

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

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

Input

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

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

Output

Print an integer representing the minimum number of times Takahashi will press the buttons.

Sample Input 1

3
3 5
2 7
9 4

Sample Output 1

7

Press the first button twice, the second button twice and the third button three times.

Sample Input 2

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

Sample Output 2

22

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

fn solution() {
    let N: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let (A, B): (Vec<i64>, Vec<i64>) = {
        let (mut A, mut B) = (vec![], vec![]);
        for _ in 0..N {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            A.push(iter.next().unwrap().parse().unwrap());
            B.push(iter.next().unwrap().parse().unwrap());
        }
        (A, B)
    };

    let ans = (0..N)
        .rev()
        .fold(0, |s, i| s + ((B[i] - (A[i] + s)) % B[i] + B[i]) % B[i]);

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


Matrix-chain Multiplication

  The goal of the matrix-chain multiplication problem is to find the most efficient way to multiply given $n$ matrices $M_1, M_2, M_3,...,M_n$.

  Write a program which reads dimensions of $M_i$, and finds the minimum number of scalar multiplications to compute the maxrix-chain multiplication $M_1M_2...M_n$.

Input

  In the first line, an integer $n$ is given. In the following $n$ lines, the dimension of matrix $M_i$ ($i = 1...n$) is given by two integers $r$ and $c$ which respectively represents the number of rows and columns of $M_i$.

Output

  Print the minimum number of scalar multiplication in a line.

Constraints

$1 \leq n \leq 100$

$1 \leq r, c \leq 100$

Sample Input 1

6
30 35
35 15
15 5
5 10
10 20
20 25

Sample Output 1

15125

fn solution() {
    let mut buf = String::new();
    let _ = std::io::stdin().read_line(&mut buf).ok();
    let n: usize = buf.trim().parse().unwrap();
    let mut mats = vec![vec![(0, 0, 0); n]; n];
    for i in 0..n {
        let mut buf = String::new();
        let _ = std::io::stdin().read_line(&mut buf).ok();
        let mut buf = buf.split_whitespace();
        mats[i][i].1 = buf.next().unwrap().parse().unwrap();
        mats[i][i].2 = buf.next().unwrap().parse().unwrap();
    }
    for j in 1..n {
        for i in 0..n - j {
            let mut res = Vec::new();
            for k in 0..j {
                res.push(
                    mats[i][i + k].0
                        + mats[i + k + 1][i + j].0
                        + mats[i][i + k].1 * mats[i][i + k].2 * mats[i + k + 1][i + j].2,
                );
            }
            mats[i][i + j].0 = *res.iter().min().unwrap();
            mats[i][i + j].1 = mats[i][i].1;
            mats[i][i + j].2 = mats[i + j][i + j].2;
        }
    }
    println!("{}", mats[0][n - 1].0);
}


Score : <var>400</var> points

Problem Statement

Consider a grid with <var>H</var> rows and <var>W</var> columns of squares. Let <var>(r, c)</var> denote the square at the <var>r</var>-th row from the top and the <var>c</var>-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From <var>(1, 1)</var>, we can reach <var>(H, W)</var> by moving one square right or down repeatedly, while always being on a white square.

Note that <var>(1, 1)</var> and <var>(H, W)</var> must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers <var>r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W)</var>. For each pair <var>r, c</var> (<var>r_0 \leq r \leq r_1, c_0 \leq c \leq c_1</var>), invert the color of <var>(r, c)</var> - that is, from white to black and vice versa.

Constraints

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

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>s_{11} s_{12} \cdots s_{1W}</var>
<var>s_{21} s_{22} \cdots s_{2W}</var>
 <var>\vdots</var>
<var>s_{H1} s_{H2} \cdots s_{HW}</var>

Here <var>s_{rc}</var> represents the color of <var>(r, c)</var> - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with <var>(r_0, c_0, r_1, c_1) = (2, 2, 2, 2)</var> to change just the color of <var>(2, 2)</var>, and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

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

Sample Output 4

4

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let h = it.next().unwrap().parse::<usize>().unwrap();
    let w = it.next().unwrap().parse::<usize>().unwrap();
    let s = (0..h)
        .map(|_| it.next().unwrap().as_bytes())
        .collect::<Vec<_>>();
    let mut dp = vec![vec!(100000; w); h];
    dp[0][0] = if s[0][0] == b'#' { 1 } else { 0 };
    for i in 0..h {
        for j in 0..w {
            if i + 1 < h {
                dp[i + 1][j] = cmp::min(
                    dp[i + 1][j],
                    dp[i][j]
                        + if s[i][j] == b'.' && s[i + 1][j] == b'#' {
                            1
                        } else {
                            0
                        },
                );
            }
            if j + 1 < w {
                dp[i][j + 1] = cmp::min(
                    dp[i][j + 1],
                    dp[i][j]
                        + if s[i][j] == b'.' && s[i][j + 1] == b'#' {
                            1
                        } else {
                            0
                        },
                );
            }
        }
    }
    println!("{}", dp[h - 1][w - 1]);
}


The string $$$s$$$ is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.As long as the string length is greater than $$$1$$$, the following operation can be performed on it: select any two adjacent letters in the string $$$s$$$ and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by $$$2$$$.Formally, let the string $$$s$$$ have the form $$$s=s_1s_2 \dots s_n$$$ ($$$n>1$$$). During one operation, you choose an arbitrary index $$$i$$$ ($$$1 \le i < n$$$) and replace $$$s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n$$$.For the given string $$$s$$$ and the letter $$$c$$$, determine whether it is possible to make such a sequence of operations that in the end the equality $$$s=c$$$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $$$1$$$, which consists of the letter $$$c$$$?

int solution() {
  int t;
  scanf("%d", &t);
  while (t-- > 0) {
    char s[49];
    char c;
    scanf("%s %c", s, &c);
    int count = 0;
    int i = 0;
    while (s[i] != '\0') {
      if (s[i] == c && i % 2 == 0) {
        count = 1;
        break;
      }
      i++;
    }
    if (count == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

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

    let mut input = String::new();
    let _firstline = stdin().read_line(&mut input).ok();

    let t = input.trim_end().parse::<u32>().expect("Failed parsed");

    for _ in 0..t {
        let mut src = String::new();
        let mut target = String::new();
        stdin().read_line(&mut src).ok();
        stdin().read_line(&mut target).ok();
        src = String::from(src.trim_end());
        target = String::from(target.trim_end());

        let mut is_ok = false;
        for s_index in 0..src.len() {
            if s_index % 2 == 0 && src.get(s_index..=s_index).unwrap() == target {
                is_ok = true;

                break;
            }
        }

        if is_ok {
            writeln!(out, "YES").ok();
        } else {
            writeln!(out, "NO").ok();
        }
    }
}


水道料金 (Water Rate)

 問題

JOI 君が住んでいる地域には水道会社が X 社と Y 社の 2 つある．2 つの会社の 1 ヶ月の水道料金は，1 ヶ月の水道の使用量に応じて次のように決まる．

X 社： 1 リットル あたり A 円かかる．

Y 社： 基本料金は B 円である．使用量が C リットル以下ならば，料金は基本料金 B 円のみがかかる．使用量が C リットルを超えると基本料金 B 円に加えて追加料金がかかる．追加料金は使用量が C リットルを 1 リットル超えるごとに D 円である．

JOI 君の家では 1 ヶ月の水道の使用量が P リットルである．

水道料金ができるだけ安くなるように水道会社を選ぶとき，JOI 君の家の 1 ヶ月の水道料金を求めよ．

入力

入力は 5 行からなり，1 行に 1 つずつ整数が書かれている．

1 行目には X 社の 1 リットルあたりの料金 A が書かれている．

2 行目には Y 社の基本料金 B が書かれている．

3 行目には Y 社の料金が基本料金のみになる使用量の上限 C が書かれている．

4 行目には Y 社の 1 リットルあたりの追加料金 D が書かれている．

5 行目には JOI 君の家の 1 ヶ月の水道の使用量 P が書かれている．

書かれている整数 A, B, C, D, P はすべて 1 以上 10000 以下である．

出力

JOI 君の家の 1 ヶ月の水道料金を表す整数を 1 行で出力せよ．

入出力例

入力例 1

9
100
20
3
10

出力例 1

90

入力例 2

8
300
100
10
250

出力例 2

1800

入出力例 1 では，JOI 君の家の 1 ヶ月の水道の使用量は 10 リットルである．

X 社の水道料金は 9 × 10 = 90 円である．

JOI 君の家の 1 ヶ月の水道の使用量は 20 リットル以下なので，Y 社の水道料金は基本料金の 100 円である．

JOI 君の家は水道料金がより安い X 社を選ぶ．そのときの JOI 君の家の 1 ヶ月の水道料金は 90 円である．

入出力例 2 では，JOI 君の家の 1 ヶ月の水道の使用量は 250 リットルである．

X 社の水道料金は 8 × 250 = 2000 円である．

JOI 君の家の 1 ヶ月の水道の使用量は 100 リットル以上で，超過量は 250 - 100 = 150 リットルである．よって，Y 社の水道料金は基本料金の 300 円に加えて 10 × 150 = 1500 円の追加料金がかかり，合計の水道料金は 300 + 1500 = 1800 円である．

JOI 君の家は水道料金がより安い Y 社を選ぶ．そのときの JOI 君の家の 1 ヶ月の水道料金は 1800 円である．

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

int solution(void) {

  int P = 0;
  int A = 0;
  int B = 0;
  int C = 0;
  int D = 0;
  scanf("%d %d %d %d %d", &A, &B, &C, &D, &P);

  int X = A * P;
  int Y = B;
  int y = ((P - C) * D) + B;
  if (P <= C) {
    if (X >= Y) {
      printf("%d\n", Y);
    } else if (X < Y) {
      printf("%d\n", X);
    }
  }

  if (P > C) {
    if (X >= y) {
      printf("%d\n", y);
    } else if (X < y) {
      printf("%d\n", X);
    }
  }

  return 0;
}

fn solution() {
    let input = {
        let mut buf = vec![];
        stdin().read_to_end(&mut buf);
        unsafe { String::from_utf8_unchecked(buf) }
    };
    let mut lines = input.split('\n').map(|s| s.parse::<u32>().unwrap());

    let a = lines.next().unwrap();
    let b = lines.next().unwrap();
    let c = lines.next().unwrap();
    let d = lines.next().unwrap();
    let p = lines.next().unwrap();

    let x = p * a;
    let y = b + p.saturating_sub(c) * d;

    println!("{}", if x < y { x } else { y });
}


Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options:  on this day the gym is closed and the contest is not carried out;  on this day the gym is closed and the contest is carried out;  on this day the gym is open and the contest is not carried out;  on this day the gym is open and the contest is carried out. On each of days Vasya can either have a rest or write the contest (if it is carried out on this day), or do sport (if the gym is open on this day).Find the minimum number of days on which Vasya will have a rest (it means, he will not do sport and write the contest at the same time). The only limitation that Vasya has — he does not want to do the same activity on two consecutive days: it means, he will not do sport on two consecutive days, and write the contest on two consecutive days.

fn solution() {
    let stdin = std::io::stdin();
    let n = {
        let mut buf = String::new();
        stdin.read_line(&mut buf).unwrap();
        buf.trim().parse::<usize>().unwrap()
    };

    let mut a = vec![0; n];
    for (i, cur) in stdin.lock().split(b' ').enumerate() {
        let str = String::from_utf8(cur.unwrap()).unwrap();
        a[i] = str.trim().parse::<u32>().unwrap();
    }

    let mut dp1 = vec![0; n + 1];
    let mut dp2 = vec![0; n + 1];

    for i in 1..n + 1 {
        {
            let do_nothing = min(dp1[i - 1], dp2[i - 1]) + 1;
            dp1[i] = do_nothing;
            dp2[i] = do_nothing;
        }

        let cur = a[i - 1];

        if cur & 1 != 0 {
            dp1[i] = min(dp1[i], dp2[i - 1]);
        }

        if cur & 2 != 0 {
            dp2[i] = min(dp2[i], dp1[i - 1]);
        }
    }

    println!("{}", min(dp2[n], dp1[n]));
}


Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The $$$i$$$-th page contains some mystery that will be explained on page $$$a_i$$$ ($$$a_i \ge i$$$).Ivan wants to read the whole book. Each day, he reads the first page he didn't read earlier, and continues to read the following pages one by one, until all the mysteries he read about are explained and clear to him (Ivan stops if there does not exist any page $$$i$$$ such that Ivan already has read it, but hasn't read page $$$a_i$$$). After that, he closes the book and continues to read it on the following day from the next page.How many days will it take to read the whole book?

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

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

    if (a > max) {
      max = a;
    }

    if (a == max && a == i) {
      days++;
    }
  }

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

  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let _n = input.trim().parse::<usize>().unwrap();
    input.clear();
    io::stdin().read_line(&mut input).unwrap();
    let v: Vec<usize> = input
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap())
        .collect();

    let mut day = 0;
    let mut idx = 0;
    let mut max = 0;
    loop {
        if v[idx] >= max {
            max = v[idx];
        }
        if max <= idx + 1 {
            day += 1;
        }
        idx += 1;
        if idx == v.len() {
            break;
        }
    }
    println!("{}", day);
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> cities on a number line. The <var>i</var>-th city is located at coordinate <var>x_i</var>.

Your objective is to visit all these cities at least once.

In order to do so, you will first set a positive integer <var>D</var>.

Then, you will depart from coordinate <var>X</var> and perform Move <var>1</var> and Move <var>2</var> below, as many times as you like:

Move <var>1</var>: travel from coordinate <var>y</var> to coordinate <var>y + D</var>.

Move <var>2</var>: travel from coordinate <var>y</var> to coordinate <var>y - D</var>.

Find the maximum value of <var>D</var> that enables you to visit all the cities.

Here, to visit a city is to travel to the coordinate where that city is located.

Constraints

All values in input are integers.

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

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

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

<var>x_i</var> are all different.

<var>x_1, x_2, ..., x_N \neq X</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>X</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_N</var>

Output

Print the maximum value of <var>D</var> that enables you to visit all the cities.

Sample Input 1

3 3
1 7 11

Sample Output 1

2

Setting <var>D = 2</var> enables you to visit all the cities as follows, and this is the maximum value of such <var>D</var>.

Perform Move <var>2</var> to travel to coordinate <var>1</var>.

Perform Move <var>1</var> to travel to coordinate <var>3</var>.

Perform Move <var>1</var> to travel to coordinate <var>5</var>.

Perform Move <var>1</var> to travel to coordinate <var>7</var>.

Perform Move <var>1</var> to travel to coordinate <var>9</var>.

Perform Move <var>1</var> to travel to coordinate <var>11</var>.

Sample Input 2

3 81
33 105 57

Sample Output 2

24

Sample Input 3

1 1
1000000000

Sample Output 3

999999999

int solution() {
  int n;
  int x;
  int y;
  int d;
  int i;
  int j;
  int k;
  int t;

  scanf("%d %d", &n, &x);
  for (d = i = 0; i < n; i++) {
    scanf("%d", &y);
    if (d == 0) {
      d = abs(x - y);
    } else {
      j = d;
      k = abs(x - y);
      if (k > j) {
        t = j;
        j = k;
        k = t;
      }
      while (k > 0) {
        t = j % k;
        j = k;
        k = t;
      }
      d = j;
      x = y;
    }
  }
  printf("%d\n", d);
  return 0;
}

fn solution() {
    input! {
        n: usize,
        init: i32,
        xs: [i32; n],
    }
    let xs = {
        let mut xs: Vec<_> = xs.iter().map(|x| x - init).collect();
        xs.push(0);
        xs.sort();
        xs
    };
    let min_d = xs.windows(2).map(|w| w[1] - w[0]).min().unwrap();
    for d in (1..min_d + 1).rev() {
        if xs.iter().all(|x| x % d == 0) {
            println!("{}", d);
            return;
        }
    }
}


Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now she is solving the following problem. You are given four positive integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, such that $$$a \leq b \leq c \leq d$$$. Your task is to find three integers $$$x$$$, $$$y$$$, $$$z$$$, satisfying the following conditions: $$$a \leq x \leq b$$$. $$$b \leq y \leq c$$$. $$$c \leq z \leq d$$$. There exists a triangle with a positive non-zero area and the lengths of its three sides are $$$x$$$, $$$y$$$, and $$$z$$$.Ichihime desires to get the cookie, but the problem seems too hard for her. Can you help her?

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let test: i64 = str.trim().parse().unwrap();
    for _ in 0..test {
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        let mut iter = str.split_whitespace();
        let _: i64 = iter.next().unwrap().parse().unwrap();
        let b: i64 = iter.next().unwrap().parse().unwrap();
        let c: i64 = iter.next().unwrap().parse().unwrap();
        println!("{} {} {}", b, c, c);
    }
}


Score : <var>200</var> points

Problem Statement

Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has <var>3</var> keys on it: the 0 key, the 1 key and the backspace key.

To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this string is empty. When each key on the keyboard is pressed, the following changes occur to the string:

The 0 key: a letter 0 will be inserted to the right of the string.

The 1 key: a letter 1 will be inserted to the right of the string.

The backspace key: if the string is empty, nothing happens. Otherwise, the rightmost letter of the string is deleted.

Sig has launched the editor, and pressed these keys several times. You are given a string <var>s</var>, which is a record of his keystrokes in order. In this string, the letter 0 stands for the 0 key, the letter 1 stands for the 1 key and the letter B stands for the backspace key. What string is displayed in the editor now?

Constraints

<var>1 ≦ |s| ≦ 10</var> (<var>|s|</var> denotes the length of <var>s</var>)

<var>s</var> consists of the letters 0, 1 and B.

The correct answer is not an empty string.

Input

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

<var>s</var>

Output

Print the string displayed in the editor in the end.

Sample Input 1

01B0

Sample Output 1

00

Each time the key is pressed, the string in the editor will change as follows: 0, 01, 0, 00.

Sample Input 2

0BB1

Sample Output 2

1

Each time the key is pressed, the string in the editor will change as follows: 0, (empty), (empty), 1.

int solution(void) {
  char str[15];
  int i = 0;
  while ((str[i] = getchar()) != '\n') {
    if (str[i] == 'B' && i != 0) {
      i--;
      str[i] = '\0';
      continue;
    }
    if (str[i] == 'B') {
      continue;
    }
    i++;
  }
  str[i] = '\0';
  printf("%s\n", str);
  return 0;
}

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

    let s = buf.trim();
    let mut stack = Vec::with_capacity(s.len());

    for c in s.chars() {
        match c {
            'B' => {
                stack.pop();
            }
            _ => {
                stack.push(c);
            }
        }
    }

    println!("{}", stack.iter().copied().collect::<String>());
}


Score : <var>200</var> points

Problem Statement

Let <var>w</var> be a string consisting of lowercase letters.
We will call <var>w</var> beautiful if the following condition is satisfied:

Each lowercase letter of the English alphabet occurs even number of times in <var>w</var>.

You are given the string <var>w</var>. Determine if <var>w</var> is beautiful.

Constraints

<var>1 \leq |w| \leq 100</var>

<var>w</var> consists of lowercase letters (a-z).

Input

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

<var>w</var>

Output

Print Yes if <var>w</var> is beautiful. Print No otherwise.

Sample Input 1

abaccaba

Sample Output 1

Yes

a occurs four times, b occurs twice, c occurs twice and the other letters occur zero times.

Sample Input 2

hthth

Sample Output 2

No

int solution() {
  char w[101];
  int keys[26] = {0};
  int flag = 0;
  scanf("%s", w);

  for (int i = 0; w[i] != '\0'; i++) {
    keys[w[i] - 'a']++;
  }

  for (int i = 0; i < 26; i++) {
    flag = (flag | keys[i]);
  }

  printf((flag & 1) == 0 ? "Yes\n" : "No\n");
  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let w = s.trim();
    let mut d = HashMap::new();

    for e in w.chars() {
        *d.entry(e).or_insert(0) += 1;
    }

    println!(
        "{}",
        if d.iter().all(|e| *e.1 % 2 == 0) {
            "Yes"
        } else {
            "No"
        }
    );
}


Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.

int solution() {
  long long int n;
  long long int m;
  scanf("%lli %lli", &n, &m);
  int i;
  int rows[n + 1];
  int columns[n + 1];
  int rws = 0;
  int cols = 0;
  long long int frees[m];
  long long int freeCounter = 0;
  for (i = 1; i <= n; i++) {
    rows[i] = columns[i] = 0;
  }
  long long int free = n * n;
  for (i = 0; i < m; i++) {
    int x;
    int y;
    scanf("%d %d", &x, &y);
    if (rows[x] + columns[y] == 2) {
      frees[freeCounter] = free;
      freeCounter++;
      continue;
    }
    if (rows[x] + columns[y] == 0) {
      free -= 2 * n - 1 - (rws + cols);
      rws++;
      cols++;
      rows[x] = 1;
      columns[y] = 1;
    } else if (columns[y] == 1) {
      free -= n - cols;
      rows[x] = 1;
      rws++;
    } else if (rows[x] == 1) {
      free -= n - rws;
      columns[y] = 1;
      cols++;
    }
    frees[freeCounter] = free;
    freeCounter++;
  }
  for (i = 0; i < freeCounter; i++) {
    printf("%lli ", frees[i]);
  }
  printf("\n");
  return 0;
}

fn solution() {
    let mut buffer = String::new();
    std::io::stdin().read_to_string(&mut buffer).unwrap();
    let mut cin = buffer
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());

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

    let mut cntx = n as u64;
    let mut cnty = n as u64;
    let mut usedx = vec![false; n];
    let mut usedy = vec![false; n];

    while let Some(x) = cin.next() {
        let x = x - 1;
        let y = cin.next().unwrap() - 1;
        if !usedx[x] {
            usedx[x] = true;
            cntx -= 1;
        }
        if !usedy[y] {
            usedy[y] = true;
            cnty -= 1;
        }

        print!("{} ", cntx * cnty);
    }

    println!();
}


As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.  Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.

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

    let mut lines = buffer.lines();

    let nm: Vec<i32> = lines
        .next()
        .unwrap()
        .split_whitespace()
        .map(|s| s.parse::<i32>().unwrap())
        .collect();
    let (n, m) = (nm[0], nm[1]);
    let mut ip_to_name = HashMap::new();

    for _ in 0..n {
        let l = lines.next().unwrap();
        let index = l.find(' ').unwrap();
        let name = l[..index].to_string();
        let ip = l[(index + 1)..l.len()].to_string();

        ip_to_name.insert(ip, name);
    }
    for _ in 0..m {
        let l = lines.next().unwrap();
        let index = l.find(' ').unwrap();
        let index_end = l.find(';').unwrap();

        let ip = l[(index + 1)..index_end].to_string();

        let name = ip_to_name.get(&ip).unwrap();
        println!("{} #{}", l.trim(), name);
    }
}


You are given a square grid with $$$n$$$ rows and $$$n$$$ columns. Each cell contains either $$$0$$$ or $$$1$$$. In an operation, you can select a cell of the grid and flip it (from $$$0 \to 1$$$ or $$$1 \to 0$$$). Find the minimum number of operations you need to obtain a square that remains the same when rotated $$$0^{\circ}$$$, $$$90^{\circ}$$$, $$$180^{\circ}$$$ and $$$270^{\circ}$$$.The picture below shows an example of all rotations of a grid.

fn solution() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());
    let t = scan.next();
    for _ in 0..t {
        let n: usize = scan.next();
        let mut v: Vec<Vec<char>> = Vec::new();
        for _i in 0..n {
            let s: String = scan.next();
            v.push(s.chars().collect());
        }
        let mut ans = 0;
        for i in 0..n {
            for j in 0..n {
                if n - i - 1 == i && n - j - 1 == j {
                    continue;
                }
                let mut cnt0 = 0;
                let mut cnt1 = 0;
                let mut ii = i;
                let mut jj = j;
                for _ in 0..4 {
                    let nx = jj;
                    let ny = n - ii - 1;
                    if v[ii][jj] == '1' {
                        cnt1 += 1;
                    } else {
                        cnt0 += 1;
                    }
                    ii = nx;
                    jj = ny;
                }
                assert_eq!(cnt0 + cnt1, 4);
                ans += min(cnt0, cnt1);
            }
        }
        writeln!(out, "{}", ans / 4);
    }
}


Given an array $$$a$$$ of $$$n$$$ elements, print any value that appears at least three times or print -1 if there is no such value.

int solution() {
  int n;
  scanf("%d", &n);
  int number = 0;
  int count = 0;
  int frq[200001] = {0};
  for (int j = 0; j < n; j++) {
    scanf("%d", &number);
    for (int f = 0; f < 200001; f++) {
      frq[f] = 0;
    }
    for (int i = 0; i < number; i++) {
      int arr[i];
      scanf("%d", &arr[i]);
      frq[arr[i]]++;
    }

    for (int k = 1; k <= number; k++) {
      if (frq[k] > 2) {
        printf("%d\n", k);
        count++;
        break;
      }
    }
    if (count == 0) {
      printf("-1\n");
    }
    count = 0;
  }

  return 0;
}

fn solution() {
    let mut input = String::new();
    std::io::stdin()
        .read_line(&mut input)
        .expect("couldn't read from input");

    let num_test_cases: isize = input.trim().parse().expect("couldn't parse number");
    for _ in 0..num_test_cases {
        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .expect("couldn't read from input");

        let mut tmp: HashMap<u32, u32> = HashMap::new();
        let mut input = String::new();

        std::io::stdin()
            .read_line(&mut input)
            .expect("couldn't read from input");

        let str: String = input.trim().parse().expect("couldn't parse numbers");
        for c in str.split(' ') {
            let c: u32 = c.parse().expect("couldn't parse char");
            let counter = tmp.entry(c).or_insert(0);
            *counter += 1;
        }

        let mut result = false;

        for (n, o) in tmp.drain() {
            if o >= 3 {
                println!("{n}");
                result = true;
                break;
            }
        }

        if !result {
            println!("-1");
        }
    }
}


Score : <var>100</var> points

Problem Statement

You have decided to give an allowance to your child depending on the outcome of the game that he will play now.

The game is played as follows:

There are three "integer panels", each with a digit between <var>1</var> and <var>9</var> (inclusive) printed on it, and one "operator panel" with a + printed on it.

The player should construct a formula of the form <var>X + Y</var>, by arranging the four panels from left to right. (The operator panel should not be placed at either end of the formula.)

Then, the amount of the allowance will be equal to the resulting value of the formula.

Given the values <var>A, B</var> and <var>C</var> printed on the integer panels used in the game, find the maximum possible amount of the allowance.

Constraints

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible amount of the allowance.

Sample Input 1

1 5 2

Sample Output 1

53

The amount of the allowance will be <var>53</var> when the panels are arranged as 52+1, and this is the maximum possible amount.

Sample Input 2

9 9 9

Sample Output 2

108

Sample Input 3

6 6 7

Sample Output 3

82

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

    let mut s = String::new();
    let _ = reader.read_line(&mut s);

    let mut v: Vec<u32> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();

    v.sort();

    println!("{}", v[2] * 10 + v[1] + v[0]);
}


Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes he visited in a row, in order of visiting them. Now, Vlad wants to find such a cafe that his last visit to that cafe was before his last visits to every other cafe. In other words, he wants to find such a cafe that he hasn't been there for as long as possible. Help Vlad to find that cafe.

fn solution() {
    let mut text = String::new();
    stdin().read_line(&mut text).unwrap();
    text.clear();
    stdin().read_line(&mut text).unwrap();
    let a: Vec<usize> = text
        .split_whitespace()
        .map(|e| e.parse().unwrap())
        .collect();
    let mut hash: HashMap<usize, usize> = HashMap::new();
    for (i, val) in a.iter().enumerate() {
        hash.insert(*val, i);
    }
    let a: Vec<(&usize, &usize)> = hash.iter().collect();
    let mut v = vec![];
    for i in &a {
        v.push(*i.1)
    }
    v.sort();

    for i in a {
        if *i.1 == v[0] {
            println!("{:?}", i.0);
            break;
        }
    }
}


You are given a system of pipes. It consists of two rows, each row consists of $$$n$$$ pipes. The top left pipe has the coordinates $$$(1, 1)$$$ and the bottom right — $$$(2, n)$$$.There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:  Types of pipes You can turn each of the given pipes $$$90$$$ degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types $$$1$$$ and $$$2$$$ can become each other and types $$$3, 4, 5, 6$$$ can become each other).You want to turn some pipes in a way that the water flow can start at $$$(1, 0)$$$ (to the left of the top left pipe), move to the pipe at $$$(1, 1)$$$, flow somehow by connected pipes to the pipe at $$$(2, n)$$$ and flow right to $$$(2, n + 1)$$$.Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes:  Examples of connected pipes Let's describe the problem using some example:  The first example input And its solution is below:   The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $$$(1, 2)$$$ $$$90$$$ degrees clockwise, the pipe at $$$(2, 3)$$$ $$$90$$$ degrees, the pipe at $$$(1, 6)$$$ $$$90$$$ degrees, the pipe at $$$(1, 7)$$$ $$$180$$$ degrees and the pipe at $$$(2, 7)$$$ $$$180$$$ degrees. Then the flow of water can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$.You have to answer $$$q$$$ independent queries.

int solution(void) {
  int n;
  int q;
  static int a[2][200000];
  static int b[100000];
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    scanf("%d", &n);
    for (int j = 0; j < 2; j++) {
      for (int k = 0; k < n; k++) {
        scanf("%1d", &a[j][k]);
      }
    }
    int g = 1;
    int l = 0;
    int r = 0;
    while (l < n && r < 2 && r > -1) {
      switch (g) {
      case 1:
        switch (a[r][l]) {
        case 1:
        case 2:
          l++;
          break;
        default:
          switch (r) {
          case 0:
            r++;
            g = 2;
            break;
          case 1:
            r--;
            g = 2;
            break;
          }
          break;
        }
        break;
      case 2:
        switch (a[r][l]) {
        case 1:
        case 2:
          r = 3;
          break;
        default:
          l++;
          g = 1;
          break;
        }
        break;
      }
    }
    if (r == 3 || r == 0) {
      b[i] = 0;
    } else {
      if (g == 1) {
        b[i] = 1;
      } else {
        b[i] = 0;
      }
    }
  }
  for (int i = 0; i < q; i++) {
    switch (b[i]) {
    case 1:
      printf("YES\n");
      break;
    case 0:
      printf("NO\n");
      break;
    }
  }
}

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

    let mut result = Vec::new();

    let queries_count = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<u32>()
        .unwrap();

    for _i in 0..queries_count {
        let n = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .parse::<u32>()
            .unwrap();

        let row1: Vec<u8> = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .chars()
            .map(|s| s.to_string().parse::<u8>().unwrap())
            .collect();

        let row2: Vec<u8> = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .chars()
            .map(|s| s.to_string().parse::<u8>().unwrap())
            .collect();

        let mut cur_row = 1;
        let mut flag = true;
        for col in 0..(n as usize) {
            match cur_row {
                1 => match row1[col] {
                    3..=6 => {
                        match row2[col] {
                            1 | 2 => {
                                flag = false;
                                break;
                            }
                            _ => {}
                        }

                        cur_row = 2;
                    }
                    _ => {}
                },
                2 => match row2[col] {
                    3..=6 => {
                        match row1[col] {
                            1 | 2 => {
                                flag = false;
                                break;
                            }
                            _ => {}
                        }

                        cur_row = 1;
                    }
                    _ => {}
                },
                _ => {}
            }
        }

        if flag && cur_row == 2 {
            result.push("YES")
        } else {
            result.push("NO")
        }
    }

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


You are given a string $$$s$$$, consisting of lowercase Latin letters. Every letter appears in it no more than twice.Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.It can be shown that the answer always exists. If there are multiple answers, print any of them.

int solution() {
  unsigned int tests;
  scanf("%u\n", &tests);

  for (unsigned int l = 0; l != tests; ++l) {
    char s[64];
    fgets(s, sizeof(s), stdin);

    char frec['z' + 1] = {0};
    for (const char *i = s; *i && *i != '\n'; ++i) {
      ++frec[*i];
    }

    for (char i = 'a'; i <= 'z'; ++i) {
      while (frec[i]--) {
        putchar(i);
      }
    }
    putchar('\n');
  }
}

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

    let t: i32 = input.trim().parse().expect("invalid input");

    let mut i = 0;
    while i < t {
        let mut s = String::new();
        io::stdin()
            .read_line(&mut s)
            .expect("failed to read input.");

        i += 1;

        let mut l: Vec<char> = s.chars().collect();
        l.sort();
        let a: String = l.into_iter().collect();

        println!("{}", a.trim());
    }
}


Score : <var>100</var> points

Problem Statement

An uppercase or lowercase English letter <var>\alpha</var> will be given as input.
If <var>\alpha</var> is uppercase, print A; if it is lowercase, print a.

Constraints

<var>\alpha</var> is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

<var>α</var>

Output

If <var>\alpha</var> is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.

int solution() {

  char str[2];
  char *pt = &str[0];

  scanf("%s", str);

  if ('A' <= *pt && *pt <= 'Z') {
    printf("A\n");
  } else if ('a' <= *pt && *pt <= 'z') {
    printf("a\n");
  }

  return 0;
}

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    is.pop();
    println!(
        "{}",
        if is.chars().all(|c| c.is_ascii_uppercase()) {
            'A'
        } else {
            'a'
        }
    );
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$.In one operation you can choose two elements $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$) and decrease each of them by one.You need to check whether it is possible to make all the elements equal to zero or not.

int solution() {
  long long int Arraylength = 0;
  long long int i = 0;
  long long int num = 0;
  long long int sum = 0;
  long long int ara[100001] = {0};
  scanf("%lld", &Arraylength);
  for (i = 0; i < Arraylength; i++) {
    scanf("%lld", &num);
    ara[i] = num;
    sum += num;
  }
  for (i = 0; i < Arraylength; i++) {
    if (ara[i] > (sum / 2)) {
      printf("NO");
      return 0;
    }
  }
  if (sum % 2 == 0) {
    printf("YES");
  } else {
    printf("NO");
  }
  return 0;
}

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

    let mut sum: u64 = 0;
    let mut max: u64 = 0;
    let numbers = buf.split_whitespace().map(|x| x.parse::<u64>().unwrap());
    for x in numbers {
        max = std::cmp::max(x, max);
        sum += x;
    }
    let is_zeroable = sum.is_multiple_of(2) && max * 2 <= sum;

    println!("{}", if is_zeroable { "YES" } else { "NO" });
}


Score : <var>100</var> points

Problem Statement

Given is an integer <var>N</var>.

Takahashi chooses an integer <var>a</var> from the positive integers not greater than <var>N</var> with equal probability.

Find the probability that <var>a</var> is odd.

Constraints

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the probability that <var>a</var> is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most <var>10^{-6}</var>.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than <var>4</var>: <var>1</var>, <var>2</var>, <var>3</var>, and <var>4</var>. Among them, we have two odd numbers: <var>1</var> and <var>3</var>. Thus, the answer is <var>\frac{2}{4} = 0.5</var>.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000

int solution(void) {
  int N = 0;
  scanf("%d", &N);
  if (N % 2 == 0) {
    printf("%f\n", 0.5);
  } else {
    double a = N;
    printf("%f\n", (a + 1) / (2 * a));
  }
  return 0;
}

fn solution() {
    let _stdin: String = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.trim_end().to_owned()
    };
    let n: f32 = _stdin.parse().unwrap();
    if n % 2. == 0.0 {
        println!("{}", 1. - (n / 2. / n));
    } else {
        println!("{}", 1. - ((n - 1.) / 2. / n));
    }
}


Score : <var>300</var> points

Problem Statement

Snuke has <var>N</var> dogs and <var>M</var> monkeys. He wants them to line up in a row.

As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there are neither two adjacent dogs nor two adjacent monkeys.

How many such arrangements there are? Find the count modulo <var>10^9+7</var> (since animals cannot understand numbers larger than that).
Here, dogs and monkeys are both distinguishable. Also, two arrangements that result from reversing each other are distinguished.

Constraints

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of possible arrangements, modulo <var>10^9+7</var>.

Sample Input 1

2 2

Sample Output 1

8

We will denote the dogs by A and B, and the monkeys by C and D. There are eight possible arrangements: ACBD, ADBC, BCAD, BDAC, CADB, CBDA, DACB and DBCA.

Sample Input 2

3 2

Sample Output 2

12

Sample Input 3

1 8

Sample Output 3

0

Sample Input 4

100000 100000

Sample Output 4

530123477

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let d: usize = std::cmp::max(v[0], v[1]) - std::cmp::min(v[0], v[1]);
    if d > 1 {
        println!("0");
        return;
    }
    const Q: usize = 1000000007;
    let mut x = 1;
    let mut y = 1;
    for i in 1..v[0] + 1 {
        x = (x * i) % Q;
    }
    for i in 1..v[1] + 1 {
        y = (y * i) % Q;
    }
    println!(
        "{}",
        if d == 1 {
            (x * y) % Q
        } else {
            (2 * ((x * y) % Q)) % Q
        }
    );
}


Three friends are going to meet each other. Initially, the first friend stays at the position $$$x = a$$$, the second friend stays at the position $$$x = b$$$ and the third friend stays at the position $$$x = c$$$ on the coordinate axis $$$Ox$$$.In one minute each friend independently from other friends can change the position $$$x$$$ by $$$1$$$ to the left or by $$$1$$$ to the right (i.e. set $$$x := x - 1$$$ or $$$x := x + 1$$$) or even don't change it.Let's introduce the total pairwise distance — the sum of distances between each pair of friends. Let $$$a'$$$, $$$b'$$$ and $$$c'$$$ be the final positions of the first, the second and the third friend, correspondingly. Then the total pairwise distance is $$$|a' - b'| + |a' - c'| + |b' - c'|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.Friends are interested in the minimum total pairwise distance they can reach if they will move optimally. Each friend will move no more than once. So, more formally, they want to know the minimum total pairwise distance they can reach after one minute.You have to answer $$$q$$$ independent test cases.

fn solution() {
    let mut str = String::new();
    let _b1 = stdin().read_line(&mut str).unwrap();
    let N: i32 = str.trim().parse().unwrap();
    for _test in 0..N {
        let mut str = String::new();
        let _b1 = stdin().read_line(&mut str).unwrap();
        let mut iter = str.split_whitespace();
        let a: i64 = iter.next().unwrap().parse().unwrap();
        let b: i64 = iter.next().unwrap().parse().unwrap();
        let c: i64 = iter.next().unwrap().parse().unwrap();
        let m = min(min(a, b), c);
        let M = max(max(a, b), c);
        println!("{}", max(2 * (M - m - 2), 0));
    }
}


A and B are preparing themselves for programming contests.B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.Initially, the compiler displayed n compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.Can you help B find out exactly what two errors he corrected?

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

    io::stdin().read_line(&mut n).unwrap();

    let _n: i64 = n.trim().parse().unwrap();

    let mut line = String::new();

    io::stdin().read_line(&mut line).unwrap();

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

    let mut line = String::new();

    io::stdin().read_line(&mut line).unwrap();

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

    let mut line = String::new();

    io::stdin().read_line(&mut line).unwrap();

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

    let mut errors_first = HashMap::new();

    for item in &a {
        let count = errors_first.entry(item).or_insert(0);
        *count += 1;
    }

    let mut errors_second = HashMap::new();
    for item in &b {
        let count = errors_second.entry(item).or_insert(0);
        *count += 1;
    }

    for (key, value) in &errors_first {
        match errors_second.get(key) {
            Some(item) => {
                if item != value {
                    println!("{}", key);
                }
            }
            None => println!("{}", key),
        }
    }

    let mut errors_third = HashMap::new();
    for item in &c {
        let count = errors_third.entry(item).or_insert(0);
        *count += 1;
    }

    for (key, value) in &errors_second {
        match errors_third.get(key) {
            Some(item) => {
                if item != value {
                    println!("{}", key);
                }
            }
            None => println!("{}", key),
        }
    }
}


Score : <var>200</var> points

Problem Statement

You have <var>N</var> apples, called Apple <var>1</var>, Apple <var>2</var>, Apple <var>3</var>, ..., Apple <var>N</var>. The flavor of Apple <var>i</var> is <var>L+i-1</var>, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining <var>N-1</var> apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the <var>N</var> apples.

Find the flavor of the apple pie made of the remaining <var>N-1</var> apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

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

<var>-100 \leq L \leq 100</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>L</var>

Output

Find the flavor of the apple pie made of the remaining <var>N-1</var> apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple <var>1</var>, <var>2</var>, <var>3</var>, <var>4</var>, and <var>5</var> are <var>2</var>, <var>3</var>, <var>4</var>, <var>5</var>, and <var>6</var>, respectively. The optimal choice is to eat Apple <var>1</var>, so the answer is <var>3+4+5+6=18</var>.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple <var>1</var>, <var>2</var>, and <var>3</var> are <var>-1</var>, <var>0</var>, and <var>1</var>, respectively. The optimal choice is to eat Apple <var>2</var>, so the answer is <var>(-1)+1=0</var>.

Sample Input 3

30 -50

Sample Output 3

-1044

int solution(void) {
  int N = 0;
  int L = 0;
  int sweet = 0;
  int pie = 0;
  int i = 1;
  int j = 1;

  scanf("%d %d", &N, &L);

  sweet = L * L;

  for (i = 2; i <= N; i++) {
    if (sweet > (L + i - 1) * (L + i - 1)) {
      sweet = (L + i - 1) * (L + i - 1);
      j = i;
    }
  }

  for (i = 1; i <= N; i++) {
    pie += L + i - 1;
  }

  pie -= L + j - 1;

  printf("%d", pie);

  return 0;
}

fn solution() {
    let mut x = String::new();
    stdin().read_line(&mut x).unwrap();
    let x: Vec<isize> = x.split_whitespace().flat_map(str::parse).collect();
    let (n, l) = (x[0], x[1]);

    let mut tastes: Vec<(isize, isize)> = (1..n + 1)
        .map(|i| l + i - 1)
        .map(|i| (if i < 0 { -i } else { i }, i))
        .collect();
    tastes.sort();
    println!(
        "{}",
        tastes.into_iter().skip(1).map(|(_, i)| i).sum::<isize>()
    );
}


Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present — the clock that shows not only the time, but also the date.The clock's face can display any number from 1 to d. It is guaranteed that ai ≤ d for all i from 1 to n. The clock does not keep information about the current month, so when a new day comes, it simply increases the current day number by one. The clock cannot display number d + 1, so after day number d it shows day 1 (the current day counter resets). The mechanism of the clock allows you to increase the day number by one manually. When you execute this operation, day d is also followed by day 1.Vasya begins each day checking the day number on the clock. If the day number on the clock does not match the actual day number in the current month, then Vasya manually increases it by one. Vasya is persistent and repeats this operation until the day number on the clock matches the actual number of the current day in the current month.A year passed and Vasya wonders how many times he manually increased the day number by one, from the first day of the first month to the last day of the n-th month inclusive, considering that on the first day of the first month the clock display showed day 1.

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

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

    let mut s = String::new();
    stdin.read_line(&mut s).unwrap();
    let d = s.trim().parse::<i32>().unwrap();

    s = String::new();
    stdin.read_line(&mut s).unwrap();
    let _n = s.trim().parse::<i32>().unwrap();

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

    let mut sum = 0;
    for i in 0..a.len() - 1 {
        sum += d - a[i];
    }

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


Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.It's known that they have worked together on the same file for $$$n + m$$$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $$$k$$$ lines written in the file.Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.Monocarp worked in total for $$$n$$$ minutes and performed the sequence of actions $$$[a_1, a_2, \dots, a_n]$$$. If $$$a_i = 0$$$, then he adds a new line to the end of the file. If $$$a_i > 0$$$, then he changes the line with the number $$$a_i$$$. Monocarp performed actions strictly in this order: $$$a_1$$$, then $$$a_2$$$, ..., $$$a_n$$$.Polycarp worked in total for $$$m$$$ minutes and performed the sequence of actions $$$[b_1, b_2, \dots, b_m]$$$. If $$$b_j = 0$$$, then he adds a new line to the end of the file. If $$$b_j > 0$$$, then he changes the line with the number $$$b_j$$$. Polycarp performed actions strictly in this order: $$$b_1$$$, then $$$b_2$$$, ..., $$$b_m$$$.Restore their common sequence of actions of length $$$n + m$$$ such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence $$$[a_1, a_2, \dots, a_n]$$$ and Polycarp's — subsequence $$$[b_1, b_2, \dots, b_m]$$$. They can replace each other at the computer any number of times.Let's look at an example. Suppose $$$k = 3$$$. Monocarp first changed the line with the number $$$2$$$ and then added a new line (thus, $$$n = 2, \: a = [2, 0]$$$). Polycarp first added a new line and then changed the line with the number $$$5$$$ (thus, $$$m = 2, \: b = [0, 5]$$$).Since the initial length of the file was $$$3$$$, in order for Polycarp to change line number $$$5$$$ two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be $$$[0, 2, 0, 5]$$$ and $$$[2, 0, 0, 5]$$$. Changes $$$[0, 0, 5, 2]$$$ (wrong order of actions) and $$$[0, 5, 2, 0]$$$ (line $$$5$$$ cannot be edited yet) are not correct.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int k;
    int n;
    int m;
    scanf("%d %d %d\n", &k, &n, &m);
    int a[n];
    int b[m];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    for (int i = 0; i < m; i++) {
      scanf("%d", &b[i]);
    }
    int x = 0;
    int y = 0;
    int steps[n + m];
    int limexc = 0;
    while (!(x == n && y == m)) {
      if (x < n && a[x] == 0) {
        steps[x + y] = 0;
        x++;
        k++;
      } else if (y < m && b[y] == 0) {
        steps[x + y] = 0;
        y++;
        k++;
      } else if (x < n && a[x] <= k) {
        steps[x + y] = a[x];
        x++;
      } else if (y < m && b[y] <= k) {
        steps[x + y] = b[y];
        y++;
      } else {
        limexc = 1;
        break;
      }
    }
    if (!limexc) {
      for (int i = 0; i < n + m; i++) {
        printf("%d ", steps[i]);
      }
    } else {
      printf("-1");
    }
    printf("\n");
  }

  return 0;
}

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

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

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

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

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

    'cases: for _case_index in 1..=t {
        lines.next();

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

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

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

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

        let mut ans = Vec::with_capacity(n + m);

        while ans.len() < n + m {
            let a1 = it1.peek().cloned();
            match a1 {
                Some(a1) if a1 <= k => {
                    if a1 == 0 {
                        k += 1;
                    }
                    it1.next();
                    ans.push(a1);
                }
                _ => match it2.next() {
                    Some(a2) if a2 <= k => {
                        if a2 == 0 {
                            k += 1;
                        }
                        ans.push(a2);
                    }
                    _ => {
                        writeln!(&mut output, "-1").unwrap();
                        continue 'cases;
                    }
                },
            }
        }

        for x in ans {
            write!(&mut output, "{} ", x).unwrap();
        }

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