For the given integer $$$n$$$ ($$$n > 2$$$) let's write down all the strings of length $$$n$$$ which contain $$$n-2$$$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string $$$s$$$ of length $$$n$$$ is lexicographically less than string $$$t$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$s_i < t_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$s_j = t_j$$$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if $$$n=5$$$ the strings are (the order does matter):  aaabb  aabab  aabba  abaab  ababa  abbaa  baaab  baaba  babaa  bbaaa It is easy to show that such a list of strings will contain exactly $$$\frac{n \cdot (n-1)}{2}$$$ strings.You are given $$$n$$$ ($$$n > 2$$$) and $$$k$$$ ($$$1 \le k \le \frac{n \cdot (n-1)}{2}$$$). Print the $$$k$$$-th string from the list.

int solution() {
  int t = 0;
  scanf("%d", &t);
  for (int i = 1; i <= t; i++) {
    int n;
    int k;
    scanf("%d%d", &n, &k);
    long long int j = 1;
    while (k > (j * (j + 1)) / 2) {
      j++;
    }
    long long int c = k - ((j * (j - 1)) / 2);
    if ((n - 1 - j) > 0) {
      for (int k = 1; k <= n - 1 - j; k++) {
        printf("a");
      }
    }
    printf("b");
    for (int m = 1; m <= j - c; m++) {
      printf("a");
    }
    printf("b");
    for (int p = 1; p <= c - 1; p++) {
      printf("a");
    }
    printf("\n");
  }
}

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

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

        let x = ((1. + (1. + 8. * k as f32).sqrt()) / 2.).ceil() as u32;
        let mut res = String::new();

        let mut i = n;
        while i > x {
            res += "a";
            i -= 1;
        }

        res += "b";
        i -= 1;

        while i > k - (x - 1) * (x - 2) / 2 {
            res += "a";
            i -= 1;
        }

        res += "b";
        while i > 1 {
            res += "a";
            i -= 1;
        }

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


Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \{1, 4, 3\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \{1, 3, 4, 4, 5, 7, 8\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$.

fn solution() {
    let t: u16 = {
        let mut buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        buffer.trim().parse::<u16>().unwrap()
    };

    for _ in 0..t {
        let a: Vec<u32> = {
            let mut buffer = String::new();
            io::stdin().read_line(&mut buffer).unwrap();
            buffer
                .split_whitespace()
                .map(|x| x.parse::<u32>().unwrap())
                .collect()
        };

        let result: (u32, u32, u32) = (a[0], a[1], a[6] - a[0] - a[1]);

        println!("{} {} {}", result.0, result.1, result.2);
    }
}


int solution() {
  int i, n, l = 0;

  printf("Enter size of array = ");
  scanf("%d", &n);

  int *a = (int *)malloc(n * sizeof(int));
  printf("Enter %d elements in array :\n", n);
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    if (a[i] > l)
      l = a[i];
  }

  int *b = (int *)malloc((l + 1) * sizeof(int));
  memset(b, 0, (l + 1) * sizeof(b[0]));

  for (i = 0; i < n; i++)
    b[a[i]]++;

  for (i = 0; i < (l + 1); i++) {
    if (b[i] > 0) {
      while (b[i] != 0) {
        printf("%d ", i);
        b[i]--;
      }
    }
  }

  free(a);
  free(b);
  return 0;
}

fn solution<T>(arr: &mut [T], maxval: usize)
where
    T: Into<u64> + From<u8> + AddAssign + Copy,
{
    let mut occurrences: Vec<usize> = vec![0; maxval + 1];

    for &value in arr.iter() {
        occurrences[value.into() as usize] += 1;
    }

    let mut index = 0;
    let mut current = T::from(0);

    for &count in occurrences.iter() {
        for _ in 0..count {
            arr[index] = current;
            index += 1;
        }

        current += T::from(1);
    }
}


Score : <var>300</var> points

Problem Statement

You have <var>N</var> bamboos. The lengths (in centimeters) of these are <var>l_1, l_2, ..., l_N</var>, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length <var>A, B, C</var>. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes <var>1</var> MP (magic point). Choose one bamboo and increase its length by <var>1</var>.

Shortening Magic: Consumes <var>1</var> MP. Choose one bamboo of length at least <var>2</var> and decrease its length by <var>1</var>.

Composition Magic: Consumes <var>10</var> MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

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

<var>1 \leq C < B < A \leq 1000</var>

<var>1 \leq l_i \leq 1000</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>A</var> <var>B</var> <var>C</var>
<var>l_1</var>
<var>l_2</var>
<var>:</var>
<var>l_N</var>

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths <var>100, 90, 80</var> from five bamboos <var>98, 40, 30, 21, 80</var>. We already have a bamboo of length <var>80</var>, and we can obtain bamboos of lengths <var>100, 90</var> by using the magics as follows at the total cost of <var>23</var> MP, which is optimal.

Use Extension Magic twice on the bamboo of length <var>98</var> to obtain a bamboo of length <var>100</var>. (MP consumed: <var>2</var>)

Use Composition Magic on the bamboos of lengths <var>40, 30</var> to obtain a bamboo of length <var>70</var>. (MP consumed: <var>10</var>)

Use Shortening Magic once on the bamboo of length <var>21</var> to obtain a bamboo of length <var>20</var>. (MP consumed: <var>1</var>)

Use Composition Magic on the bamboo of length <var>70</var> obtained in step 2 and the bamboo of length <var>20</var> obtained in step 3 to obtain a bamboo of length <var>90</var>. (MP consumed: <var>10</var>)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is <var>0</var>. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243

int solution() {
  int n;
  int i;
  int j;
  int a;
  int b;
  int c;
  int min = 10000;
  int max = 1;
  scanf("%d%d%d%d", &n, &a, &b, &c);
  int l[n + 1];
  for (i = 0; i < n; i++) {
    scanf("%d", &l[i]);
    max *= 4;
  }
  for (i = 1; i < max; i++) {
    int anum = 0;
    int bnum = 0;
    int cnum = 0;
    int k = i;
    int mp = 0;
    for (j = 0; j < n; j++) {
      if (k % 4 == 1) {
        if (anum != 0) {
          mp += 10;
        }
        anum += l[j];
      } else if (k % 4 == 2) {
        if (bnum != 0) {
          mp += 10;
        }
        bnum += l[j];
      } else if (k % 4 == 3) {
        if (cnum != 0) {
          mp += 10;
        }
        cnum += l[j];
      }
      k /= 4;
    }
    if (anum != 0 && bnum != 0 && cnum != 0) {
      mp += abs(anum - a) + abs(bnum - b) + abs(cnum - c);
      if (mp < min) {
        min = mp;
      }
    }
  }
  printf("%d\n", min);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let a: i32 = iter.next().unwrap().parse().unwrap();
    let b: i32 = iter.next().unwrap().parse().unwrap();
    let c: i32 = iter.next().unwrap().parse().unwrap();
    let l: Vec<i32> = (0..n)
        .map(|_| iter.next().unwrap().parse().unwrap())
        .collect();

    let x = 4u32.pow(n as u32);
    let mut ans = std::i32::MAX;

    for bit in 0..x {
        let mut sumA = 0i32;
        let mut sumB = 0i32;
        let mut sumC = 0i32;
        let mut cost = 0i32;
        let mut t = bit;
        let mut cursor = 0;
        while t > 0 {
            let m = t % 4;
            if m == 1 {
                if sumA > 0 {
                    cost += 10;
                }
                sumA += l[cursor];
            } else if m == 2 {
                if sumB > 0 {
                    cost += 10;
                }
                sumB += l[cursor];
            } else if m == 3 {
                if sumC > 0 {
                    cost += 10;
                }
                sumC += l[cursor];
            }
            t /= 4;
            cursor += 1;
        }
        if sumA == 0 || sumB == 0 || sumC == 0 {
            continue;
        }
        ans = std::cmp::min(
            ans,
            cost + (a - sumA).abs() + (b - sumB).abs() + (c - sumC).abs(),
        );
    }

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


Alice and Bob are playing a game. They have an array of positive integers $$$a$$$ of size $$$n$$$.Before starting the game, Alice chooses an integer $$$k \ge 0$$$. The game lasts for $$$k$$$ stages, the stages are numbered from $$$1$$$ to $$$k$$$. During the $$$i$$$-th stage, Alice must remove an element from the array that is less than or equal to $$$k - i + 1$$$. After that, if the array is not empty, Bob must add $$$k - i + 1$$$ to an arbitrary element of the array. Note that both Alice's move and Bob's move are two parts of the same stage of the game. If Alice can't delete an element during some stage, she loses. If the $$$k$$$-th stage ends and Alice hasn't lost yet, she wins.Your task is to determine the maximum value of $$$k$$$ such that Alice can win if both players play optimally. Bob plays against Alice, so he tries to make her lose the game, if it's possible.

int solution() {
  int a[101];
  int b;
  int t;
  int n;
  scanf("%d", &t);
  while (t--) {
    memset(a, 0, sizeof(a));
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%d", &b);
      a[b]++;
    }
    int ans = 0;
    for (int k = 1; k <= n; k++) {
      int now = 0;
      int pd = 0;
      for (int i = 1; i <= k; i++) {
        now += a[i];
        if (now < k + i - 1) {
          pd = 1;
          break;
        }
      }
      if (pd == 0) {
        ans = k;
      }
    }
    printf("%d\n", ans);
  }
}

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let t = buffer.trim().parse::<u16>().unwrap();
    for _ in 0..t {
        buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        let n = buffer.trim().parse::<usize>().unwrap();

        buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        let mut a: Vec<usize> = buffer
            .split_whitespace()
            .map(|s| s.parse::<usize>().unwrap())
            .collect();

        a.sort();

        let mut max_k = 0;
        for k in (0..n.div_ceil(2) + 1).rev() {
            let mut k_ok: bool = true;
            for i in 0..k {
                if a[2 * (k - 1) - i] > k - i {
                    k_ok = false;
                    break;
                }
            }
            if k_ok {
                max_k = k;
                break;
            }
        }
        println!("{}", max_k);
    }
}


Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.

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

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let t = s.trim().parse::<i32>().unwrap();
    let mut writer = io::BufWriter::new(io::stdout());

    for _ in 0..t {
        s.clear();
        io::stdin().read_line(&mut s).unwrap();
        let n = s.trim().parse::<i32>().unwrap();
        let mut m = 7;
        if n != 2 {
            m = 3;
        }
        writeln!(writer, "{}", m).unwrap();
    }
}


Sorting Three Numbers

  Write a program which reads three integers, and prints them in ascending order.

Input

  Three integers separated by a single space are given in a line.

Output

  Print the given integers in ascending order in a line. Put a single space between two integers.

Constraints

 1 ≤ the three integers ≤ 10000

Sample Input 1

3 8 1

Sample Output 1

1 3 8

int solution() {

  int a = 0;
  int b = 0;
  int c = 0;

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

  if (a <= b && b <= c) {
    printf("%d %d %d\n", a, b, c);
  } else if (a <= c && c <= b) {
    printf("%d %d %d\n", a, c, b);
  } else if (b <= c && c <= a) {
    printf("%d %d %d\n", b, c, a);
  } else if (b <= a && a <= c) {
    printf("%d %d %d\n", b, a, c);
  } else if (c <= a && a <= b) {
    printf("%d %d %d\n", c, a, b);
  } else if (c <= b && b <= a) {
    printf("%d %d %d\n", c, b, a);
  }

  return 0;
}

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

    let _ = scan.read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();

    let a: u32 = vec[0].parse().unwrap_or(0);
    let b: u32 = vec[1].parse().unwrap_or(0);
    let c: u32 = vec[2].parse().unwrap_or(0);

    let mut v = [a, b, c];
    v.sort();

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


Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.

int solution() {
  long num;
  long max = 0;
  long pos = 0;
  long i;
  long j;
  unsigned long long count;
  long l[1000000];
  long r[1000000];
  long arr[1000000];
  long h[1000000];
  long c[1000000];
  scanf("%ld", &num);
  for (i = 0; i < num; ++i) {
    c[i] = 0;
    scanf("%ld", &h[i]);
    if (h[i] > max) {
      max = h[i];
      pos = i;
    }
  }
  for (i = pos; i < num; ++i) {
    arr[count++] = h[i];
  }
  for (i = 0; i < pos; ++i) {
    arr[count++] = h[i];
  }

  arr[count] = max;

  for (i = num - 1; i >= 0; --i) {
    r[i] = i + 1;
    while (r[i] < num && arr[i] > arr[r[i]]) {
      r[i] = r[r[i]];
    }
    if (r[i] < num && arr[i] == arr[r[i]]) {
      c[i] = c[r[i]] + 1;
      r[i] = r[r[i]];
    }
  }

  for (i = 1; i <= num; ++i) {
    l[i] = i - 1;
    while (l[i] > 0 && arr[i] > arr[l[i]]) {
      l[i] = l[l[i]];
    }
    if (arr[i] > 0 && arr[i] == arr[l[i]]) {
      l[i] = l[l[i]];
    }
  }
  count = 0;

  for (i = 1; i < num; ++i) {
    if (r[i] == num && l[i] == 0) {
      count += c[i] + 1;
    } else {
      count += c[i] + 2;
    }
  }

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

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

    let n = read!(usize);
    let mut hs = read!([u64; n]);

    let max = *hs.iter().max().unwrap();
    let i = hs.iter().position(|&h| h == max).unwrap();
    let xs = hs
        .iter()
        .skip(i)
        .chain(hs.iter().take(i))
        .copied()
        .collect::<Vec<u64>>();
    let mut vs = vec![0; n];
    let mut ans = 0;
    let mut i = 0;
    for &h in &xs {
        let mut v = 1;
        while i > 0 && h >= hs[i - 1] {
            i -= 1;
            ans += vs[i];
            if h == hs[i] {
                v += vs[i];
            }
        }
        if i > 0 {
            ans += 1;
        }
        vs[i] = v;
        hs[i] = h;
        i += 1;
    }
    ans += vs
        .iter()
        .take(i)
        .skip(if vs[0] == 1 { 2 } else { 1 })
        .sum::<u64>();

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You want to distribute these $$$n$$$ integers into two groups $$$s_1$$$ and $$$s_2$$$ (groups can be empty) so that the following conditions are satisfied:  For each $$$i$$$ $$$(1 \leq i \leq n)$$$, $$$a_i$$$ goes into exactly one group. The value $$$|sum(s_1)| - |sum(s_2)|$$$ is the maximum possible among all such ways to distribute the integers.Here $$$sum(s_1)$$$ denotes the sum of the numbers in the group $$$s_1$$$, and $$$sum(s_2)$$$ denotes the sum of the numbers in the group $$$s_2$$$.Determine the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

int solution() {
  int case_num = 0;
  scanf("%d", &case_num);
  for (int i = 0; i < case_num; ++i) {
    int arr_len = 0;
    scanf("%d", &arr_len);
    long long int arr[100000] = {0};
    long long int sum = 0;
    for (int j = 0; j < arr_len; ++j) {
      scanf("%lld", &arr[j]);
      sum += arr[j];
    }
    sum >= 0 ? printf("%lld\n", sum) : printf("%lld\n", -sum);
  }
  return 0;
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(2)
        .step_by(2)
        .flatten()
        .for_each(|s| {
            let ans = s
                .split_ascii_whitespace()
                .flat_map(str::parse::<isize>)
                .sum::<isize>()
                .abs();
            writeln!(buf, "{ans}").ok();
        });
}


Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$).

fn solution() {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).expect("error!");
    let mut nums = Vec::new();
    let mut max = 0;
    for item in buffer.split_whitespace() {
        let num: i32 = item.parse().expect("invalid number");
        nums.push(num);
        max = std::cmp::max(num, max);
    }
    let mut out = String::new();
    for item in nums.into_iter() {
        if item != max {
            out.push_str(&format!("{} ", max - item));
        }
    }
    println!("{}", out.trim());
}


Bubble Sort

Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

BubbleSort(A)
1 for i = 0 to A.length-1
2     for j = A.length-1 downto i+1
3         if A[j] < A[j-1]
4             swap A[j] and A[j-1]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by spaces characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9

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

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

  int flag = 1;
  while (flag) {
    flag = 0;
    for (int i = n - 1; i > -1; i--) {
      if (nums[i] < nums[i - 1]) {
        count++;
        int tmp = nums[i - 1];
        nums[i - 1] = nums[i];
        nums[i] = tmp;
        flag = 1;
      }
    }
  }

  for (int i = 0; i < n - 1; i++) {
    printf("%d ", nums[i]);
  }
  printf("%d\n", nums[n - 1]);
  printf("%d\n", count);
}

fn solution() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("");
    input = String::new();
    std::io::stdin().read_line(&mut input).expect("");
    let mut v: Vec<u8> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let mut temp: u8;
    let mut step: u16 = 0;
    let mut sorted: bool;
    let mut first: bool = true;
    loop {
        sorted = true;
        for i in 0..v.len() - 1 {
            if v[i] > v[i + 1] {
                sorted = false;
                temp = v[i + 1];
                v[i + 1] = v[i];
                v[i] = temp;
                step += 1;
            }
        }
        if sorted {
            break;
        }
    }
    println!(
        "{}",
        v.iter().fold(String::new(), |a, &b| a.to_string()
            + if !first {
                " "
            } else {
                first = false;
                ""
            }
            + &b.to_string())
    );
    println!("{}", step);
}


Score : <var>200</var> points

Problem Statement

Snuke has <var>N</var> integers. Among them, the smallest is <var>A</var>, and the largest is <var>B</var>.
We are interested in the sum of those <var>N</var> integers. How many different possible sums there are?

Constraints

<var>1 ≤ N,A,B ≤ 10^9</var>

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of the different possible sums.

Sample Input 1

4 4 6

Sample Output 1

5

There are five possible sums: <var>18=4+4+4+6</var>, <var>19=4+4+5+6</var>, <var>20=4+5+5+6</var>, <var>21=4+5+6+6</var> and <var>22=4+6+6+6</var>.

Sample Input 2

5 4 3

Sample Output 2

0

Sample Input 3

1 7 10

Sample Output 3

0

Sample Input 4

1 3 3

Sample Output 4

1

int solution() {
  long n;
  long a;
  long b;
  scanf("%ld %ld %ld", &n, &a, &b);
  long ans = 0;
  if (n <= 2 || a > b) {
    if ((n == 1 && a == b) || (n == 2 && a <= b)) {
      ans = 1;
    }
    printf("%ld\n", ans);
    return 0;
  }

  ans = (b - a) * (n - 2) + 1;

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

  return 0;
}

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

    if a > b || (n == 1 && a != b) {
        println!("0")
    } else if n == 1 {
        println!("1")
    } else {
        let mx = a + (n - 1) * b;
        let mn = a * (n - 1) + b;
        println!("{}", mx - mn + 1);
    }
}


You are given a set of $$$n$$$ segments on the axis $$$Ox$$$, each segment has integer endpoints between $$$1$$$ and $$$m$$$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — coordinates of the left and of the right endpoints. Consider all integer points between $$$1$$$ and $$$m$$$ inclusive. Your task is to print all such points that don't belong to any segment. The point $$$x$$$ belongs to the segment $$$[l; r]$$$ if and only if $$$l \le x \le r$$$.

int solution() {
  int n = 0;
  int m = 0;
  int l[100];
  int r[100];
  int temp[100];
  int i = 0;
  int j = 0;
  int c = 1;
  int count = 0;
  scanf("%d %d", &n, &m);
  for (i = 0; i < n; i++) {
    scanf("%d %d", &l[i], &r[i]);
  }
  for (i = 1; i <= m; i++) {
    c = 1;
    for (j = 0; j < n; j++) {
      if (i <= r[j] && i >= l[j]) {
        c = 0;
        break;
      }
    }
    if (c == 1) {
      temp[count] = i;
      count++;
    }
  }

  printf("%d\n", count);
  if (count != 0) {
    for (i = 0; i < count; i++) {
      printf("%d ", temp[i]);
    }
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s);
    let mut si = s.split_whitespace();
    let n: u32 = si.next().unwrap().parse().unwrap();
    let m: u32 = si.next().unwrap().parse().unwrap();
    drop(si);
    let mut dots = BTreeSet::new();
    for i in 1..=m {
        dots.insert(i);
    }
    for _ in 0..n {
        let mut s = String::new();
        io::stdin().read_line(&mut s);
        let mut si = s.split_whitespace();
        let l: u32 = si.next().unwrap().parse().unwrap();
        let r: u32 = si.next().unwrap().parse().unwrap();
        for i in l..=r {
            dots.remove(&i);
        }
    }
    println!("{}", dots.len());
    for i in dots {
        print!("{} ", i);
    }
    println!();
}


Score : <var>100</var> points

Problem Statement

You are given a string <var>S</var> of length <var>3</var> consisting of a, b and c. Determine if <var>S</var> can be obtained by permuting abc.

Constraints

<var>|S|=3</var>

<var>S</var> consists of a, b and c.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> can be obtained by permuting abc, print Yes; otherwise, print No.

Sample Input 1

bac

Sample Output 1

Yes

Swapping the first and second characters in bac results in abc.

Sample Input 2

bab

Sample Output 2

No

Sample Input 3

abc

Sample Output 3

Yes

Sample Input 4

aaa

Sample Output 4

No

fn solution() {
    let stdin = io::stdin();
    let mut s = String::new();
    stdin.read_line(&mut s).ok();
    s.pop();
    if s == "abc" || s == "acb" || s == "bac" || s == "bca" || s == "cab" || s == "cba" {
        println!("Yes");
    } else {
        println!("No");
    }
}


In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.

int solution() {
  int n;
  scanf("%d", &n);
  long long numbers[n];
  long long sum[n];
  for (int i = 0; i < n; ++i) {
    scanf("%lld", &numbers[i]);
    sum[i] = (numbers[i] * (numbers[i] + 1)) / 2;
  }
  for (int i = 0; i < n; ++i) {
    for (long long j = 1; j <= numbers[i]; j *= 2) {
      sum[i] = sum[i] - 2 * j;
    }
    printf("%lld\n", sum[i]);
  }
  return 0;
}

fn solution() {
    let mut temp_str = String::new();
    let mut sum: i64;
    let mut two_mult;

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

    let req_count: usize = temp_str.trim().parse().expect("");

    let mut numbers = vec![0; req_count];

    for i in 0..req_count {
        let mut temp = String::new();

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

        numbers[i] = temp.trim().parse().unwrap();

        sum = (1 + numbers[i] as i64) * numbers[i] as i64 / 2;

        sum -= 2;

        two_mult = 2;

        while two_mult <= numbers[i] {
            sum -= 2 * two_mult as i64;

            two_mult *= 2;
        }

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


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$.Let $$$\operatorname{MEX}$$$ of a binary string be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the string. For example, $$$\operatorname{MEX}$$$ of $$$001011$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the string at least once, $$$\operatorname{MEX}$$$ of $$$1111$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the string and $$$0 < 2$$$.A binary string $$$s$$$ is given. You should cut it into any number of substrings such that each character is in exactly one substring. It is possible to cut the string into a single substring — the whole string.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.What is the minimal sum of $$$\operatorname{MEX}$$$ of all substrings pieces can be?

fn solution() {
    let stdin = std::io::stdin();
    let mut string = String::new();
    stdin.read_line(&mut string).unwrap();
    for _ in 0..string.trim().parse::<usize>().unwrap() {
        string.clear();
        stdin.read_line(&mut string).unwrap();
        let last = string.rfind("0");
        let first = string.find("0");
        println!("{}", {
            if last.is_none() {
                0
            } else {
                if last == first {
                    1
                } else {
                    if string
                        .drain(first.unwrap()..last.unwrap())
                        .any(|f| f == '1')
                    {
                        2
                    } else {
                        1
                    }
                }
            }
        })
    }
}


It is the hard version of the problem. The only difference is that in this version $$$3 \le k \le n$$$.You are given a positive integer $$$n$$$. Find $$$k$$$ positive integers $$$a_1, a_2, \ldots, a_k$$$, such that:  $$$a_1 + a_2 + \ldots + a_k = n$$$  $$$LCM(a_1, a_2, \ldots, a_k) \le \frac{n}{2}$$$ Here $$$LCM$$$ is the least common multiple of numbers $$$a_1, a_2, \ldots, a_k$$$.We can show that for given constraints the answer always exists.

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

    use std::io::Write;
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    let t: usize = scan!(usize);
    for _ in 1..=t {
        let (n, k) = scan!(usize, usize);
        for _ in 0..k - 3 {
            print!("{} ", 1);
        }
        let n = n - (k - 3);
        match n % 4 {
            0 => {
                let m = n / 4;
                print!("{} {} {}", 2 * m, m, m);
            }

            1 => {
                let m = n / 4;
                print!("{} {} {}", 2 * m, 2 * m, 1);
            }

            2 => {
                let m = n / 4;
                print!("{} {} {}", 2 * m, 2 * m, 2);
            }

            3 => {
                let m = n / 4;
                print!("{} {} {}", 2 * m + 1, 2 * m + 1, 1);
            }

            _ => {
                panic!("wtf!");
            }
        }
        print!("\n");
    }
}


You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long int n;
    scanf("%lld", &n);
    long long int c3 = 0;
    long long int c2 = 0;
    long long int f = 0;
    if (n == 1) {
      printf("0\n");
      continue;
    }
    while (1) {
      if (n % 3 == 0) {
        c3++;
        n /= 3;
      }
      if (n % 2 == 0) {
        c2++;
        n /= 2;
      }
      if ((n % 2 != 0 && n % 3 != 0) && (n != 1)) {
        f = 1;
        break;
      }
      if (n == 1) {
        break;
      }
    }
    if (f == 1) {
      printf("-1\n");
    } else {
      if (c3 < c2) {
        printf("-1\n");
      } else {
        printf("%lld\n", c2 + ((c3 - c2) * 2));
      }
    }
  }
  return 0;
}

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

    for t in stdin.lock().lines().skip(1) {
        let mut n = t.unwrap().parse::<u64>().unwrap();
        let mut s = 0;

        while n % 6 == 0 {
            n /= 6;
            s += 1;
        }

        while n % 3 == 0 {
            n /= 3;
            s += 2;
        }

        println!("{}", if n == 1 { s } else { -1 });
    }
}


ロシアの旗 (Russian Flag)

  問題

K 理事長はロシアで開催される IOI 2016 に合わせて旗を作ることにした．K 理事長はまず倉庫から古い旗を取り出してきた．この旗は N 行 M 列のマス目に分けられていて，それぞれのマスには白・青・赤のいずれかの色が塗られている．

K 理事長はこの旗のいくつかのマスを塗り替えてロシアの旗にしようとしている．ただし，この問題でいうロシアの旗とは以下のようなものである．

上から何行か (1 行以上) のマスが全て白で塗られている．

続く何行か (1 行以上) のマスが全て青で塗られている．

それ以外の行 (1 行以上) のマスが全て赤で塗られている．

K 理事長が古い旗をロシアの旗にするために塗り替える必要のあるマスの個数の最小値を求めよ．

 入力

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

1 行目には，2 つの整数 N, M (3 ≦ N ≦ 50, 3 ≦ M ≦ 50) が空白を区切りとして書かれている．これは，旗が N 行 M 列のマス目に区切られていることを表す．

続く N 行にはそれぞれ M 文字からなる文字列が書かれており，古い旗のマス目に塗られている色の情報を表す．N 行のうちの i 行目の j 文字目 (1 ≦ i ≦ N, 1 ≦ j ≦ M) は，古い旗のマス目の i 行目 j 列目のマスの色を表す 'W', 'B', 'R' のいずれかの文字である．
'W' は白，'B' は青，'R' は赤を表す．

  出力

K 理事長が古い旗をロシアの旗にするために塗り替える必要のあるマスの個数の最小値を 1 行で出力せよ．

  入出力例

入力例 1

4 5
WRWRW
BWRWB
WRWRW
RWBWR

出力例 1

11

入力例 2

6 14
WWWWWWWWWWWWWW
WBBBWWRRWWBBBW
WWBWWRRRRWWBWW
BWBWWRRRRWWBWW
WBBWWWRRWWBBBW
WWWWWWWWWWWWWW

出力例 2

44

入出力例 1 において，古い旗には下図のように色が塗られている．

下図において，'X' の書かれた 11 個のマスを塗り替える．

これにより下図のようなロシアの旗にすることができる．

11 個未満のマスを塗り替えることではロシアの旗にすることはできないため，11 を出力する．

入出力例 2 においては，古い旗には下図のように色が塗られている．

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

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

    let (n, m) = {
        let line = lines.next().unwrap();
        let mut iter = line.split(' ').map(|s| s.parse::<usize>().unwrap());

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

    let mut cost = lines
        .next()
        .unwrap()
        .bytes()
        .filter(|&ch| ch != b'W')
        .count();

    let mut wr = Vec::with_capacity(n - 2);
    wr.extend(lines.by_ref().take(n - 2).map(|l| {
        l.bytes().fold((0, 0), |(w, r), ch| match ch {
            b'W' => (w + 1, r),
            b'R' => (w, r + 1),
            _ => (w, r),
        })
    }));

    let mut min = usize::max_value();

    for i in 0..(n - 2) {
        let w: usize = wr[..i].iter().map(|&(w, _)| m - w).sum();

        for j in (i + 1)..(n - 1) {
            let b: usize = wr[i..j].iter().map(|&(w, r)| w + r).sum();
            let r: usize = wr[j..].iter().map(|&(_, r)| m - r).sum();

            let cost = w + b + r;
            if min > cost {
                min = cost;
            }
        }
    }
    cost += min;

    cost += lines
        .next()
        .unwrap()
        .bytes()
        .filter(|&ch| ch != b'R')
        .count();

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


Score: <var>200</var> points

Problem Statement

Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.

As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by <var>100</var> exactly <var>D</var> times.

Find the <var>N</var>-th smallest integer that would make Ringo happy.

Constraints

<var>D</var> is <var>0</var>, <var>1</var> or <var>2</var>.

<var>N</var> is an integer between <var>1</var> and <var>100</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>D</var> <var>N</var>

Output

Print the <var>N</var>-th smallest integer that can be divided by <var>100</var> exactly <var>D</var> times.

Sample Input 1

0 5

Sample Output 1

5

The integers that can be divided by <var>100</var> exactly <var>0</var> times (that is, not divisible by <var>100</var>) are as follows: <var>1</var>, <var>2</var>, <var>3</var>, <var>4</var>, <var>5</var>, <var>6</var>, <var>7</var>, ...

Thus, the <var>5</var>-th smallest integer that would make Ringo happy is <var>5</var>.

Sample Input 2

1 11

Sample Output 2

1100

The integers that can be divided by <var>100</var> exactly once are as follows: <var>100</var>, <var>200</var>, <var>300</var>, <var>400</var>, <var>500</var>, <var>600</var>, <var>700</var>, <var>800</var>, <var>900</var>, <var>1 \ 000</var>, <var>1 \ 100</var>, ...

Thus, the integer we are seeking is <var>1 \ 100</var>.

Sample Input 3

2 85

Sample Output 3

850000

The integers that can be divided by <var>100</var> exactly twice are as follows: <var>10 \ 000</var>, <var>20 \ 000</var>, <var>30 \ 000</var>, ...

Thus, the integer we are seeking is <var>850 \ 000</var>.

fn solution() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).ok();
    let mut it = input.split_whitespace();
    let a: u32 = it.next().unwrap().parse().unwrap();
    let b: u32 = it.next().unwrap().parse().unwrap();
    let base: u32 = 100;
    println!(
        "{}",
        if b < 100 {
            base.pow(a) * b
        } else {
            base.pow(a) * 101
        }
    );
}


Score : <var>400</var> points

Problem Statement

Given is a number sequence <var>A</var> of length <var>N</var>.

Find the number of integers <var>i</var> <var>\left(1 \leq i \leq N\right)</var> with the following property:

For every integer <var>j</var> <var>\left(1 \leq j \leq N\right)</var> such that <var>i \neq j </var>, <var>A_j</var> does not divide <var>A_i</var>.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>\cdots</var> <var>A_N</var>

Output

Print the answer.

Sample Input 1

5
24 11 8 3 16

Sample Output 1

3

The integers with the property are <var>2</var>, <var>3</var>, and <var>4</var>.

Sample Input 2

4
5 5 5 5

Sample Output 2

0

Note that there can be multiple equal numbers.

Sample Input 3

10
33 18 45 28 8 19 89 86 2 4

Sample Output 3

5

int solution(void) {

  long n;
  scanf("%ld", &n);
  long size = 1000000;
  long list[size + 1];
  for (long i = 0; i <= size; i++) {
    list[i] = 0;
  }
  long a;
  for (long i = 0; i < n; i++) {
    scanf("%ld", &a);
    list[a]++;
  }
  long count = 0;
  for (long i = 0; i <= size; i++) {
    if (list[i] != 0) {
      for (long j = 2; i * j <= size; j++) {
        list[i * j] = 0;
      }
      if (list[i] == 1) {
        count++;
      }
    }
  }
  printf("%ld\n", count);

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<usize>().unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let mut xs: Vec<_> = buf
        .split_ascii_whitespace()
        .map(|x| x.parse::<usize>().unwrap())
        .collect();
    assert!(xs.len() == n);
    xs.sort_by(|a, b| a.partial_cmp(b).unwrap());

    let mut dp = vec![true; *xs.last().unwrap() + 1];

    let mut i = 0;
    while i < xs.len() {
        if dp[xs[i]] {
            let x = xs[i];
            if i < xs.len() - 1 && x == xs[i + 1] {
                dp[x] = false;
            }
            let mut xx = x + x;
            while xx < dp.len() {
                dp[xx] = false;
                xx += x;
            }
        }
        i += 1;
    }

    println!(
        "{}",
        xs.iter().filter(|x| dp[**x]).collect::<Vec<_>>().len()
    );
}


Score : <var>500</var> points

Problem Statement

We have a sequence of <var>N</var> integers: <var>A_1, A_2, \cdots, A_N</var>.

You can perform the following operation between <var>0</var> and <var>K</var> times (inclusive):

Choose two integers <var>i</var> and <var>j</var> such that <var>i \neq j</var>, each between <var>1</var> and <var>N</var> (inclusive). Add <var>1</var> to <var>A_i</var> and <var>-1</var> to <var>A_j</var>, possibly producing a negative element.

Compute the maximum possible positive integer that divides every element of <var>A</var> after the operations. Here a positive integer <var>x</var> divides an integer <var>y</var> if and only if there exists an integer <var>z</var> such that <var>y = xz</var>.

Constraints

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>A_1</var> <var>A_2</var> <var>\cdots</var> <var>A_{N-1}</var> <var>A_{N}</var>

Output

Print the maximum possible positive integer that divides every element of <var>A</var> after the operations.

Sample Input 1

2 3
8 20

Sample Output 1

7

<var>7</var> will divide every element of <var>A</var> if, for example, we perform the following operation:

Choose <var>i = 2, j = 1</var>. <var>A</var> becomes <var>(7, 21)</var>.

We cannot reach the situation where <var>8</var> or greater integer divides every element of <var>A</var>.

Sample Input 2

2 10
3 5

Sample Output 2

8

Consider performing the following five operations:

Choose <var>i = 2, j = 1</var>. <var>A</var> becomes <var>(2, 6)</var>.

Choose <var>i = 2, j = 1</var>. <var>A</var> becomes <var>(1, 7)</var>.

Choose <var>i = 2, j = 1</var>. <var>A</var> becomes <var>(0, 8)</var>.

Choose <var>i = 2, j = 1</var>. <var>A</var> becomes <var>(-1, 9)</var>.

Choose <var>i = 1, j = 2</var>. <var>A</var> becomes <var>(0, 8)</var>.

Then, <var>0 = 8 \times 0</var> and <var>8 = 8 \times 1</var>, so <var>8</var> divides every element of <var>A</var>. We cannot reach the situation where <var>9</var> or greater integer divides every element of <var>A</var>.

Sample Input 3

4 5
10 1 2 22

Sample Output 3

7

Sample Input 4

8 7
1 7 5 6 8 2 6 5

Sample Output 4

5

fn solution() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    input! {
      n: usize,
      k: i64,
      a: [i64; n],
    }
    let s: i64 = a.iter().sum();
    let mut div = vec![];
    let mut i = 1;
    while i * i <= s {
        if s % i == 0 {
            div.push(i);
            div.push(s / i);
        }
        i += 1;
    }
    div.sort();
    use std::collections::VecDeque;
    for &d in div.iter().rev() {
        let mut v = vec![];
        for &x in &a {
            v.push(x % d);
        }
        v.sort();
        let mut q: VecDeque<_> = v.into_iter().collect();
        let mut c = 0;
        let mut mv = 0i64;
        while !q.is_empty() {
            if c > 0 {
                let x = q.pop_back().unwrap();
                c += x - d;
                mv += d - x;
            } else {
                let x = q.pop_front().unwrap();
                c += x;
                mv += x;
            }
        }
        if mv / 2 <= k {
            puts!("{}\n", d);
            return;
        }
    }
}


This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.To bake a Napoleon cake, one has to bake $$$n$$$ dry layers first, and then put them on each other in one stack, adding some cream. Arkady started with an empty plate, and performed the following steps $$$n$$$ times:   place a new cake layer on the top of the stack;  after the $$$i$$$-th layer is placed, pour $$$a_i$$$ units of cream on top of the stack. When $$$x$$$ units of cream are poured on the top of the stack, top $$$x$$$ layers of the cake get drenched in the cream. If there are less than $$$x$$$ layers, all layers get drenched and the rest of the cream is wasted. If $$$x = 0$$$, no layer gets drenched.  The picture represents the first test case of the example. Help Arkady determine which layers of the cake eventually get drenched when the process is over, and which don't.

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

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

    while (ii >= 0) {
      if (a[ii] == 0 && f == 0) {
        ii--;
        continue;
      }
      if (a[ii] != 0 && temp < a[ii]) {
        temp = a[ii];
        f = 1;
      }
      if (f == 1 && temp > 0) {
        a[ii] = 1;
        temp--;
      }
      if (temp == 0) {
        f = 0;
      }
      ii--;
    }
    for (long long int q = 0; q < n; q++) {
      printf("%lld ", a[q]);
    }

    printf("\n");
  }
}

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

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

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

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

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

    for _ in 0..t {
        let s = lines.next().unwrap();
        let mut it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());
        let n = it.next().unwrap();

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

        let mut stack = Vec::new();

        for (i, a) in it.enumerate().filter(|&(_, a)| a > 0) {
            let e = i + 1;
            let mut s = e.saturating_sub(a);

            loop {
                match stack.pop() {
                    None => {
                        stack.push((s, e));
                        break;
                    }
                    Some((s0, e0)) => {
                        if s <= e0 {
                            s = std::cmp::min(s0, s);
                        } else {
                            stack.push((s0, e0));
                            stack.push((s, e));
                            break;
                        }
                    }
                }
            }
        }

        let mut i = 0;

        for (s, e) in stack {
            for _ in i..s {
                write!(&mut output, "0 ").unwrap();
            }
            for _ in s..e {
                write!(&mut output, "1 ").unwrap();
            }
            i = e;
        }

        for _ in i..n {
            write!(&mut output, "0 ").unwrap();
        }

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


Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives.

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

  int count[1001];
  memset(count, 0, sizeof(count));

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

  int ans = 0;
  int i = 1000;
  while (i > 0 && m > 0) {
    if (count[i] == 0) {
      i--;
      continue;
    }

    m -= i;
    count[i]--;
    ans++;
    if (count[i] == 0) {
      i--;
    }
  }
  printf("%d\n", ans);

  return 0;
}

fn solution() {
    let mut usb_num = String::new();
    io::stdin()
        .read_line(&mut usb_num)
        .expect("Cannot Read Input");
    let usb_num: i32 = usb_num.trim().parse().expect("WHY!");

    let mut size_file = String::new();
    io::stdin().read_line(&mut size_file).expect("WHY!");
    let mut size_file: i32 = size_file.trim().parse().expect("WHY!");

    let mut usb_mem: Vec<i32> = Vec::new();
    let mut c = 0;
    let mut min = 0;

    while c < usb_num {
        let mut temp = String::new();
        io::stdin().read_line(&mut temp).expect("WHY!");
        let temp: i32 = temp.trim().parse().expect("WHY!");
        usb_mem.push(temp);
        c += 1;
    }
    usb_mem.sort_by(|a, b| b.cmp(a));
    for i in &usb_mem {
        size_file -= i;

        if size_file > 0 {
            min += 1
        } else {
            min += 1;
            break;
        }
    }
    println!("{}", min);
}


Score : <var>300</var> points

Problem Statement

As a token of his gratitude, Takahashi has decided to give his mother an integer sequence.
The sequence <var>A</var> needs to satisfy the conditions below:

<var>A</var> consists of integers between <var>X</var> and <var>Y</var> (inclusive).

For each <var>1\leq i \leq |A|-1</var>, <var>A_{i+1}</var> is a multiple of <var>A_i</var> and strictly greater than <var>A_i</var>.

Find the maximum possible length of the sequence.

Constraints

<var>1 \leq X \leq Y \leq 10^{18}</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible length of the sequence.

Sample Input 1

3 20

Sample Output 1

3

The sequence <var>3,6,18</var> satisfies the conditions.

Sample Input 2

25 100

Sample Output 2

3

Sample Input 3

314159265 358979323846264338

Sample Output 3

31

int solution() {
  long long int X;
  long long int Y;
  long long int count = 1;
  scanf("%lld %lld", &X, &Y);
  while (X * 2 <= Y) {
    count++;
    X *= 2;
  }
  printf("%lld\n", count);
  return 0;
}

fn solution() {
    let scan = std::io::stdin();
    let mut line = String::new();
    let _ = scan.read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();

    let mut n: Vec<i64> = Vec::new();

    for x in vec {
        n.push(x.parse().unwrap());
    }

    let mut cnt: i32 = 0;

    let mut tmp: i64 = n[0];
    while tmp <= n[1] {
        cnt += 1;
        tmp *= 2;
    }

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


Score : <var>200</var> points

Problem Statement

Given are strings <var>s</var> and <var>t</var> of length <var>N</var> each, both consisting of lowercase English letters.

Let us form a new string by alternating the characters of <var>S</var> and the characters of <var>T</var>, as follows: the first character of <var>S</var>, the first character of <var>T</var>, the second character of <var>S</var>, the second character of <var>T</var>, <var>...</var>, the <var>N</var>-th character of <var>S</var>, the <var>N</var>-th character of <var>T</var>. Print this new string.

Constraints

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

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

<var>S</var> and <var>T</var> are strings consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

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

Output

Print the string formed.

Sample Input 1

2
ip cc

Sample Output 1

icpc

Sample Input 2

8
hmhmnknk uuuuuuuu

Sample Output 2

humuhumunukunuku

Sample Input 3

5
aaaaa aaaaa

Sample Output 3

aaaaaaaaaa

int solution(void) {
  int n = 0;
  int count1 = 0;
  int count2 = 0;
  char str1[110];
  char str2[110];

  scanf("%d%s%s", &n, str1, str2);

  for (int i = 0; i < n * 2; i++) {
    if (i % 2 == 0) {
      printf("%c", str1[count1++]);
    } else {
      printf("%c", str2[count2++]);
    }
  }

  printf("\n");

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let mut iter = buf.split_whitespace();
    let s: Vec<char> = iter.next().unwrap().chars().collect();
    let t: Vec<char> = iter.next().unwrap().chars().collect();
    for i in 0..s.len() {
        print!("{}{}", s[i], t[i]);
    }
    println!();
}


Score : <var>300</var> points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square <var>(i,j)</var> contains the integer <var>i \times j</var>. Initially, Takahashi is standing at <var>(1,1)</var>.

In one move, he can move from <var>(i,j)</var> to either <var>(i+1,j)</var> or <var>(i,j+1)</var>.

Given an integer <var>N</var>, find the minimum number of moves needed to reach a square that contains <var>N</var>.

Constraints

<var>2 \leq N \leq 10^{12}</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the minimum number of moves needed to reach a square that contains the integer <var>N</var>.

Sample Input 1

10

Sample Output 1

5

<var>(2,5)</var> can be reached in five moves. We cannot reach a square that contains <var>10</var> in less than five moves.

Sample Input 2

50

Sample Output 2

13

<var>(5, 10)</var> can be reached in <var>13</var> moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.

int solution(void) {
  long n = 0;
  long count = 0;
  long min = 0;
  scanf("%ld", &n);
  for (int i = 1; i <= sqrt(n); i++) {
    if (n % i == 0) {
      count = (i - 1) + (n / i - 1);
      if (min > count || min == 0) {
        min = count;
      }
    }
  }
  printf("%ld", min);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let line: Vec<i64> = buf.split_whitespace().map(|s| s.parse().unwrap()).collect();
    let N = line[0];
    let mut x = 1;
    let mut y = N;
    let mut i = 1;
    loop {
        i += 1;
        if i * i > N {
            break;
        }
        if N % i != 0 {
            continue;
        }
        x = i;
        y = N / i;
    }
    println!("{}", x + y - 2)
}


Reservation System

The supercomputer system L in the PCK Research Institute performs a variety of calculations upon request from external institutes, companies, universities and other entities. To use the L system, you have to reserve operation time by specifying the start and end time. No two reservation periods are allowed to overlap each other.

  Write a program to report if a new reservation overlaps with any of the existing reservations. Note that the coincidence of start and end times is not considered to constitute an overlap. All the temporal data is given as the elapsed time from the moment at which the L system starts operation.

Input

  The input is given in the following format.

<var>a</var> <var>b</var>
<var>N</var>
<var>s_1</var> <var>f_1</var>
<var>s_2</var> <var>f_2</var>
:
<var>s_N</var> <var>f_N</var>

The first line provides new reservation information, i.e., the start time <var>a</var> and end time <var>b</var> (0 ≤ <var>a</var> < <var>b</var> ≤ 1000) in integers. The second line specifies the number of existing reservations <var>N</var> (0 ≤ <var>N</var> ≤ 100). Subsequent <var>N</var> lines provide temporal information for the <var>i</var>-th reservation: start time <var>s_i</var> and end time <var>f_i</var> (0 ≤ <var>s_i</var> < <var>f_i</var> ≤ 1000) in integers. No two existing reservations overlap.

Output

  Output "1" if the new reservation temporally overlaps with any of the existing ones, or "0" otherwise.

Sample Input 1

5 7
3
1 4
4 5
7 10

Sample Output 1

0

Sample Input 2

3 7
3
7 10
1 4
4 5

Sample Output 2

1

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

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

    for _ in 0..n {
        let aa: usize = iter.next().unwrap().parse().unwrap();
        let bb: usize = iter.next().unwrap().parse().unwrap();
        if !(a >= bb || b <= aa) {
            println!("{}", 1);
            return;
        }
    }

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


Score : <var>400</var> points

Problem Statement

In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.

In the plan developed by the president Takahashi, the trains will run as follows:

A train will run for <var>(t_1 + t_2 + t_3 + ... + t_N)</var> seconds.

In the first <var>t_1</var> seconds, a train must run at a speed of at most <var>v_1</var> m/s (meters per second). Similarly, in the subsequent <var>t_2</var> seconds, a train must run at a speed of at most <var>v_2</var> m/s, and so on.

According to the specifications of the trains, the acceleration of a train must be always within <var>±1m/s^2</var>. Additionally, a train must stop at the beginning and the end of the run.

Find the maximum possible distance that a train can cover in the run.

Constraints

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

<var>1 \leq t_i \leq 200</var>

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>t_1</var> <var>t_2</var> <var>t_3</var> … <var>t_N</var>
<var>v_1</var> <var>v_2</var> <var>v_3</var> … <var>v_N</var>

Output

Print the maximum possible that a train can cover in the run.

Output is considered correct if its absolute difference from the judge's output is at most <var>10^{-3}</var>.

Sample Input 1

1
100
30

Sample Output 1

2100.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>30</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>450</var> meters.

In the subsequent <var>40</var> seconds, it maintains the velocity of <var>30m/s</var>, covering <var>1200</var> meters.

In the last <var>30</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>450</var> meters.

The total distance covered is <var>450</var> + <var>1200</var> + <var>450</var> = <var>2100</var> meters.

Sample Input 2

2
60 50
34 38

Sample Output 2

2632.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>34</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>578</var> meters.

In the subsequent <var>26</var> seconds, it maintains the velocity of <var>34m/s</var>, covering <var>884</var> meters.

In the subsequent <var>4</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>144</var> meters.

In the subsequent <var>8</var> seconds, it maintains the velocity of <var>38m/s</var>, covering <var>304</var> meters.

In the last <var>38</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>722</var> meters.

The total distance covered is <var>578</var> + <var>884</var> + <var>144</var> + <var>304</var> + <var>722</var> = <var>2632</var> meters.

Sample Input 3

3
12 14 2
6 2 7

Sample Output 3

76.000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>6</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>18</var> meters.

In the subsequent <var>2</var> seconds, it maintains the velocity of <var>6m/s</var>, covering <var>12</var> meters.

In the subsequent <var>4</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>16</var> meters.

In the subsequent <var>14</var> seconds, it maintains the velocity of <var>2m/s</var>, covering <var>28</var> meters.

In the last <var>2</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>2</var> meters.

The total distance covered is <var>18</var> + <var>12</var> + <var>16</var> + <var>28</var> + <var>2</var> = <var>76</var> meters.

Sample Input 4

1
9
10

Sample Output 4

20.250000000000000000

The maximum distance is achieved when a train runs as follows:

In the first <var>4.5</var> seconds, it accelerates at a rate of <var>1m/s^2</var>, covering <var>10.125</var> meters.

In the last <var>4.5</var> seconds, it decelerates at the acceleration of <var>-1m/s^2</var>, covering <var>10.125</var> meters.

The total distance covered is <var>10.125</var> + <var>10.125</var> = <var>20.25</var> meters.

Sample Input 5

10
64 55 27 35 76 119 7 18 49 100
29 19 31 39 27 48 41 87 55 70

Sample Output 5

20291.000000000000

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

  int t[N];
  int v[N];
  int endtime = 0;
  int time = 0;

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

  double speed[2 * endtime];
  double ans = 0;

  for (int i = 0; i < 2 * endtime; i++) {
    speed[i] = 60000;
  }
  for (double i = 0; i < endtime; i += 0.5) {
    double sample[N + 2];
    sample[N] = i;
    sample[N + 1] = endtime - i;
    time = 0;
    for (int j = 0; j < N; j++) {
      if (i < time) {
        sample[j] = v[j] + (time - i);
      } else if (time + t[j] < i) {
        sample[j] = v[j] + (i - (time + t[j]));
      } else {
        sample[j] = v[j];
      }
      time += t[j];
    }
    for (int j = 0; j < N + 2; j++) {
      if (speed[(int)(i * 2)] > sample[j]) {
        speed[(int)(i * 2)] = sample[j];
      }
    }
  }

  for (int i = 0; i < 2 * endtime; i++) {
    ans += 0.25 * (speed[i] + speed[i + 1]);
  }

  printf("%lf\n", ans);
  return 0;
}


Score : <var>300</var> points

Problem Statement

Given is a positive integer <var>L</var>.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is <var>L</var>.

Constraints

<var>1 ≤ L ≤ 1000</var>

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

Input

Input is given from Standard Input in the following format:

<var>L</var>

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is <var>L</var>.
Your output is considered correct if its absolute or relative error from our answer is at most <var>10^{-6}</var>.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are <var>0.8</var>, <var>1</var>, and <var>1.2</var> has a volume of <var>0.96</var>.

On the other hand, if the dimensions are <var>1</var>, <var>1</var>, and <var>1</var>, the volume of the rectangular cuboid is <var>1</var>, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000

int solution(void) {
  double l = 0;
  scanf("%lf", &l);
  printf("%.6lf", l * l * l / 27.0);
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let l = s.trim().parse::<f64>().unwrap();
    let n = l / 3.;

    println!("{}", n * n * n);
}


There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.

int solution() {
  int n = 0;
  scanf("%d", &n);
  char arr[n + 1];
  scanf("%s", arr);
  int black = 0;
  int white = 0;
  for (int i = 0; i < n; ++i) {
    if (arr[i] == 'B') {
      black++;
    } else {
      white++;
    }
  }
  int flagB = 0;
  int flagW = 0;
  if (black % 2 == 0) {
    flagB = 1;
  }
  if (white % 2 == 0) {
    flagW = 1;
  }
  if (flagB == 0 && flagW == 0) {
    printf("-1");
    return 0;
  }
  int index[n];
  int count = 0;
  int j = 0;
  if (flagW == 1) {
    for (int i = 0; i < n; i++) {
      if (arr[i] == 'W') {
        count++;
        arr[i] = 'B';
        (arr[i + 1] == 'W') ? (arr[i + 1] = 'B') : (arr[i + 1] = 'W');
        index[j++] = i + 1;
      }
    }
  }
  if (flagW == 0 && flagB == 1) {
    for (int i = 0; i < n; i++) {
      if (arr[i] == 'B') {
        count++;
        arr[i] = 'W';
        (arr[i + 1] == 'W') ? (arr[i + 1] = 'B') : (arr[i + 1] = 'W');
        index[j++] = i + 1;
      }
    }
  }
  printf("%d\n", count);
  for (int i = 0; i < j; i++) {
    printf("%d ", index[i]);
  }

  return 0;
}

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let _N: i32 = str.trim().parse().unwrap();
    str.clear();
    let _ = stdin().read_line(&mut str).unwrap();
    str.trim();
    let mut w_s: i32 = 0;
    let mut b_s: i32 = 0;
    let mut del_char = 'x';
    for ch in str.chars() {
        if ch == 'W' {
            w_s += 1;
        }
        if ch == 'B' {
            b_s += 1;
        }
    }
    if w_s % 2 == 0 {
        del_char = 'W';
    }
    if b_s % 2 == 0 {
        del_char = 'B';
    }
    if del_char == 'x' {
        println!("-1");
    } else {
        let mut trig: bool = false;
        let mut fin_str = String::new();
        let mut num = 0;
        let mut ind = 0;
        for ch in str.chars() {
            ind += 1;
            trig ^= ch == del_char;
            if trig {
                num += 1;
                fin_str += &format!("{} ", ind);
            }
        }
        println!("{}", num);
        println!("{}", fin_str);
    }
}


Score: <var>100</var> points

Problem Statement

The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.

When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "<var>N</var> 本" for a positive integer <var>N</var> not exceeding <var>999</var> is as follows:

hon when the digit in the one's place of <var>N</var> is <var>2</var>, <var>4</var>, <var>5</var>, <var>7</var>, or <var>9</var>;

pon when the digit in the one's place of <var>N</var> is <var>0</var>, <var>1</var>, <var>6</var> or <var>8</var>;

bon when the digit in the one's place of <var>N</var> is <var>3</var>.

Given <var>N</var>, print the pronunciation of "本" in the phrase "<var>N</var> 本".

Constraints

<var>N</var> is a positive integer not exceeding <var>999</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer.

Sample Input 1

16

Sample Output 1

pon

The digit in the one's place of <var>16</var> is <var>6</var>, so the "本" in "<var>16</var> 本" is pronounced pon.

Sample Input 2

2

Sample Output 2

hon

Sample Input 3

183

Sample Output 3

bon

int solution() {

  int num = 0;

  scanf("%d", &num);

  switch (num % 10) {
  case 3:
    printf("bon\n");
    break;
  case 0:
  case 1:
  case 6:
  case 8:
    printf("pon\n");
    break;
  default:
    printf("hon\n");
    break;
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let n: i64 = s.trim().parse::<i64>().unwrap() % 10;

    println!(
        "{}",
        if n == 3 {
            "bon"
        } else if [2, 4, 5, 7, 9].contains(&n) {
            "hon"
        } else {
            "pon"
        }
    );
}


Score : <var>200</var> points

Problem Statement

We will say that two integer sequences of length <var>N</var>, <var>x_1, x_2, ..., x_N</var> and <var>y_1, y_2, ..., y_N</var>, are similar when <var>|x_i - y_i| \leq 1</var> holds for all <var>i</var> (<var>1 \leq i \leq N</var>).

In particular, any integer sequence is similar to itself.

You are given an integer <var>N</var> and an integer sequence of length <var>N</var>, <var>A_1, A_2, ..., A_N</var>.

How many integer sequences <var>b_1, b_2, ..., b_N</var> are there such that <var>b_1, b_2, ..., b_N</var> is similar to <var>A</var> and the product of all elements, <var>b_1 b_2 ... b_N</var>, is even?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of integer sequences that satisfy the condition.

Sample Input 1

2
2 3

Sample Output 1

7

There are seven integer sequences that satisfy the condition:

<var>1, 2</var>

<var>1, 4</var>

<var>2, 2</var>

<var>2, 3</var>

<var>2, 4</var>

<var>3, 2</var>

<var>3, 4</var>

Sample Input 2

3
3 3 3

Sample Output 2

26

Sample Input 3

1
100

Sample Output 3

1

Sample Input 4

10
90 52 56 71 44 8 13 30 57 84

Sample Output 4

58921

int solution(void) {
  int n;
  scanf("%d", &n);
  int a[n];
  long long int min = 1;
  long long int plu = 1;
  for (int p = 0; p < n; p++) {
    scanf("%d", &a[p]);
    if (a[p] % 2 == 0) {
      min *= 2;
    }
    plu *= 3;
  }
  long long int ans = plu - min;
  printf("%lld", ans);
}

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

    let mut c = 1;
    let mut b = 1;
    for i in 0..n {
        b *= 3;
        if a[i].is_multiple_of(2) {
            c *= 2;
        }
    }
    println!("{}", b - c);
}


A class of students wrote a multiple-choice test.There are $$$n$$$ students in the class. The test had $$$m$$$ questions, each of them had $$$5$$$ possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question $$$i$$$ worth $$$a_i$$$ points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class.

fn solution() {
    let stdin = std::io::stdin();
    let stdin_lock = stdin.lock();
    let mut student_count = 0;
    let mut question_count = 0;
    let mut answers = Vec::<Vec<u8>>::new();
    let mut points = Vec::<u32>::new();
    for (line_count, line) in stdin_lock.lines().enumerate() {
        let line = line.unwrap();
        if line_count == 0 {
            let mut splitted = line.split_whitespace();
            student_count = usize::from_str(splitted.next().unwrap()).unwrap();
            question_count = usize::from_str(splitted.next().unwrap()).unwrap();
        } else if line_count > 0 && line_count <= student_count {
            answers.push(line.as_bytes().to_vec());
        } else {
            for s in line.split_whitespace() {
                points.push(u32::from_str(s).unwrap());
            }
            break;
        }
    }

    let mut out = 0;

    for i in 0..question_count {
        let mut v = [0u32; 5];
        for a in answers.iter() {
            match a[i] {
                b'A' => v[0] += 1,
                b'B' => v[1] += 1,
                b'C' => v[2] += 1,
                b'D' => v[3] += 1,
                b'E' => v[4] += 1,
                _ => {
                    unreachable!()
                }
            }
        }
        v.sort();
        out += v[4] * points[i];
    }
    println!("{}", out);
}


Three guys play a game: first, each person writes down $$$n$$$ distinct words of length $$$3$$$. Then, they total up the number of points as follows:   if a word was written by one person — that person gets 3 points,  if a word was written by two people — each of the two gets 1 point,  if a word was written by all — nobody gets any points.  In the end, how many points does each player have?

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

#define MAX_WORDS 1000

  int first[MAX_WORDS];
  int second[MAX_WORDS];
  int third[MAX_WORDS];

#define AMOUNT_OF_WORDS_OF_LENGTH_3 17576

  int hystogram[AMOUNT_OF_WORDS_OF_LENGTH_3];

  for (int currentSet = 0; currentSet < numSets; ++currentSet) {
    int numWords = 0;
    scanf("%d", &numWords);

    for (int i = 0; i < AMOUNT_OF_WORDS_OF_LENGTH_3; ++i) {
      hystogram[i] = 0;
    }

    for (int i = 0; i < numWords; ++i) {
      char symbols[4];
      int word = 0;
      scanf(" %s", symbols);
      word = (symbols[0] - 'a');
      word = 26 * word + (symbols[1] - 'a');
      word = 26 * word + (symbols[2] - 'a');
      ++hystogram[word];
      first[i] = word;
    }

    for (int i = 0; i < numWords; ++i) {
      char symbols[4];
      int word = 0;
      scanf(" %s", symbols);
      word = (symbols[0] - 'a');
      word = 26 * word + (symbols[1] - 'a');
      word = 26 * word + (symbols[2] - 'a');
      ++hystogram[word];
      second[i] = word;
    }

    for (int i = 0; i < numWords; ++i) {
      char symbols[4];
      int word = 0;
      scanf(" %s", symbols);
      word = (symbols[0] - 'a');
      word = 26 * word + (symbols[1] - 'a');
      word = 26 * word + (symbols[2] - 'a');
      ++hystogram[word];
      third[i] = word;
    }

    int firstScore = 0;
    for (int i = 0; i < numWords; ++i) {
      int histElem = hystogram[first[i]];
      switch (histElem) {
      case 1: {
        firstScore += 3;
        break;
      }
      case 2: {
        firstScore += 1;
        break;
      }
      }
    }

    int secondScore = 0;
    for (int i = 0; i < numWords; ++i) {
      int histElem = hystogram[second[i]];
      switch (histElem) {
      case 1: {
        secondScore += 3;
        break;
      }
      case 2: {
        secondScore += 1;
        break;
      }
      }
    }

    int thirdScore = 0;
    for (int i = 0; i < numWords; ++i) {
      int histElem = hystogram[third[i]];
      switch (histElem) {
      case 1: {
        thirdScore += 3;
        break;
      }
      case 2: {
        thirdScore += 1;
        break;
      }
      }
    }

    printf("%d %d %d\n", firstScore, secondScore, thirdScore);
  }

  return 0;
}

fn solution() {
    let t: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    for _i in 0..t {
        let n: usize = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        };
        let s1: Vec<String> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.trim().to_string())
                .collect()
        };
        let s2: Vec<String> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.trim().to_string())
                .collect()
        };
        let s3: Vec<String> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.trim().to_string())
                .collect()
        };
        let mut counter = HashMap::new();
        for i in 0..n {
            *counter.entry(&s1[i]).or_insert(0) += 1;
            *counter.entry(&s2[i]).or_insert(0) += 1;
            *counter.entry(&s3[i]).or_insert(0) += 1;
        }
        let mut p1 = 0;
        let mut p2 = 0;
        let mut p3 = 0;
        for s in &s1 {
            let cnt = counter[s];
            if cnt == 1 {
                p1 += 3;
            } else if cnt == 2 {
                p1 += 1;
            }
        }
        for s in &s2 {
            let cnt = counter[s];
            if cnt == 1 {
                p2 += 3;
            } else if cnt == 2 {
                p2 += 1;
            }
        }
        for s in &s3 {
            let cnt = counter[s];
            if cnt == 1 {
                p3 += 3;
            } else if cnt == 2 {
                p3 += 1;
            }
        }
        println!("{} {} {}", p1, p2, p3);
    }
}


Score : <var>1000</var> points

Problem Statement

There are <var>N</var> balls and <var>N+1</var> holes in a line. Balls are numbered <var>1</var> through <var>N</var> from left to right. Holes are numbered <var>1</var> through <var>N+1</var> from left to right. The <var>i</var>-th ball is located between the <var>i</var>-th hole and <var>(i+1)</var>-th hole. We denote the distance between neighboring items (one ball and one hole) from left to right as <var>d_i</var> (<var>1 \leq i \leq 2 \times N</var>). You are given two parameters <var>d_1</var> and <var>x</var>. <var>d_i - d_{i-1}</var> is equal to <var>x</var> for all <var>i</var> (<var>2 \leq i \leq 2 \times N</var>).

We want to push all <var>N</var> balls into holes one by one. When a ball rolls over a hole, the ball will drop into the hole if there is no ball in the hole yet. Otherwise, the ball will pass this hole and continue to roll. (In any scenario considered in this problem, balls will never collide.)

In each step, we will choose one of the remaining balls uniformly at random and then choose a direction (either left or right) uniformly at random and push the ball in this direction. Please calculate the expected total distance rolled by all balls during this process.

For example, when <var>N = 3</var>, <var>d_1 = 1</var>, and <var>x = 1</var>, the following is one possible scenario:

first step: push the ball numbered <var>2</var> to its left, it will drop into the hole numbered <var>2</var>. The distance rolled is <var>3</var>.

second step: push the ball numbered <var>1</var> to its right, it will pass the hole numbered <var>2</var> and drop into the hole numbered <var>3</var>. The distance rolled is <var>9</var>.

third step: push the ball numbered <var>3</var> to its right, it will drop into the hole numbered <var>4</var>. The distance rolled is <var>6</var>.

So the total distance in this scenario is <var>18</var>.

Note that in all scenarios every ball will drop into some hole and there will be a hole containing no ball in the end.

Constraints

<var>1 \leq N \leq 200,000</var>

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

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

All input values are integers.

Input

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

<var>N</var> <var>d_1</var> <var>x</var>

Output

Print a floating number denoting the answer. The relative or absolute error of your answer should not be higher than <var>10^{-9}</var>.

Sample Input 1

1 3 3

Sample Output 1

4.500000000000000

The distance between the only ball and the left hole is <var>3</var> and distance between the only ball and the right hole is <var>6</var>. There are only two scenarios (i.e. push left and push right). The only ball will roll <var>3</var> and <var>6</var> unit distance, respectively. So the answer for this example is <var>(3+6)/2 = 4.5</var>.

Sample Input 2

2 1 0

Sample Output 2

2.500000000000000

Sample Input 3

1000 100 100

Sample Output 3

649620280.957660079002380

int solution() {
  int N;
  int i;
  double ans = 0;
  scanf("%d", &N);
  double *d1 = (double *)malloc(sizeof(double) * (N + 1));
  double *x = (double *)malloc(sizeof(double) * (N + 1));
  scanf("%lf%lf", &d1[N], &x[N]);
  for (i = N; i > 1; i--) {
    d1[i - 1] = (2 * (i + 1) * d1[i] + 5 * x[i]) / (2 * i);
    x[i - 1] = ((i + 2) * x[i]) / i;
  }
  for (i = 1; i <= N; i++) {
    ans += d1[i] + ((2 * i - 1) * x[i]) / 2;
  }
  printf("%.12lf\n", ans);
  return 0;
}


Recently you have bought a snow walking robot and brought it home. Suppose your home is a cell $$$(0, 0)$$$ on an infinite grid.You also have the sequence of instructions of this robot. It is written as the string $$$s$$$ consisting of characters 'L', 'R', 'U' and 'D'. If the robot is in the cell $$$(x, y)$$$ right now, he can move to one of the adjacent cells (depending on the current instruction).  If the current instruction is 'L', then the robot can move to the left to $$$(x - 1, y)$$$;  if the current instruction is 'R', then the robot can move to the right to $$$(x + 1, y)$$$;  if the current instruction is 'U', then the robot can move to the top to $$$(x, y + 1)$$$;  if the current instruction is 'D', then the robot can move to the bottom to $$$(x, y - 1)$$$. You've noticed the warning on the last page of the manual: if the robot visits some cell (except $$$(0, 0)$$$) twice then it breaks.So the sequence of instructions is valid if the robot starts in the cell $$$(0, 0)$$$, performs the given instructions, visits no cell other than $$$(0, 0)$$$ two or more times and ends the path in the cell $$$(0, 0)$$$. Also cell $$$(0, 0)$$$ should be visited at most two times: at the beginning and at the end (if the path is empty then it is visited only once). For example, the following sequences of instructions are considered valid: "UD", "RL", "UUURULLDDDDLDDRRUU", and the following are considered invalid: "U" (the endpoint is not $$$(0, 0)$$$) and "UUDD" (the cell $$$(0, 1)$$$ is visited twice).The initial sequence of instructions, however, might be not valid. You don't want your robot to break so you decided to reprogram it in the following way: you will remove some (possibly, all or none) instructions from the initial sequence of instructions, then rearrange the remaining instructions as you wish and turn on your robot to move. Your task is to remove as few instructions from the initial sequence as possible and rearrange the remaining ones so that the sequence is valid. Report the valid sequence of the maximum length you can obtain.Note that you can choose any order of remaining instructions (you don't need to minimize the number of swaps or any other similar metric).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 lr = [0, 0];
        let mut ud = [0, 0];
        for letter in str.chars() {
            match letter {
                'L' => lr[0] += 1,
                'R' => lr[1] += 1,
                'U' => ud[0] += 1,
                'D' => ud[1] += 1,
                _ => break,
            }
        }
        let m: i64 = *lr.iter().min().unwrap();
        let M: i64 = *ud.iter().min().unwrap();
        if M + m == 0 {
            println!("0");
        } else if m == 0 {
            println!("2");
            println!("UD");
        } else if M == 0 {
            println!("2");
            println!("LR");
        } else {
            println!("{}", 2 * (M + m));
            let mut answ = String::new();
            for _i in 0..M {
                answ = answ + "U";
            }
            for _i in 0..m {
                answ = answ + "L";
            }
            for _i in 0..M {
                answ = answ + "D";
            }
            for _i in 0..m {
                answ = answ + "R";
            }

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


Score : <var>400</var> points

Problem Statement

You are given an integer <var>N</var>. Among the divisors of <var>N!</var> <var>(= 1 \times 2 \times ... \times N)</var>, how many Shichi-Go numbers (literally "Seven-Five numbers") are there?

Here, a Shichi-Go number is a positive integer that has exactly <var>75</var> divisors.

Note

When a positive integer <var>A</var> divides a positive integer <var>B</var>, <var>A</var> is said to a divisor of <var>B</var>.
For example, <var>6</var> has four divisors: <var>1, 2, 3</var> and <var>6</var>.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of the Shichi-Go numbers that are divisors of <var>N!</var>.

Sample Input 1

9

Sample Output 1

0

There are no Shichi-Go numbers among the divisors of <var>9! = 1 \times 2 \times ... \times 9 = 362880</var>.

Sample Input 2

10

Sample Output 2

1

There is one Shichi-Go number among the divisors of <var>10! = 3628800</var>: <var>32400</var>.

Sample Input 3

100

Sample Output 3

543

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 div = vec![0; 101];
    for mut i in 2..n + 1 {
        let mut j = 2;
        while j * j <= i {
            while i % j == 0 {
                i /= j;
                div[j] += 1;
            }
            j += 1;
        }
        if i != 1 {
            div[i] += 1;
        }
    }

    let mut c3 = 0i32;
    let mut c5 = 0i32;
    let mut c15 = 0i32;
    let mut c25 = 0i32;
    let mut c75 = 0i32;

    for i in 2..101 {
        div[i] += 1;
        if div[i] >= 3 {
            c3 += 1;
        }
        if div[i] >= 5 {
            c5 += 1;
        }
        if div[i] >= 15 {
            c15 += 1;
        }
        if div[i] >= 25 {
            c25 += 1;
        }
        if div[i] >= 75 {
            c75 += 1;
        }
    }
    let mut ans = 0;
    ans += c5 * (c5 - 1) / 2 * (c3 - 2);
    ans += c15 * (c5 - 1);
    ans += c25 * (c3 - 1);
    ans += c75;
    println!("{}", ans);
}


People worry that computers will get too smart and take over the world, but the real problem is that they're too stupid and they've already taken over the world.— Pedro DomingosYou work for a well-known department store that uses leading technologies and employs mechanistic work — that is, robots!The department you work in sells $$$n \cdot k$$$ items. The first item costs $$$1$$$ dollar, the second item costs $$$2$$$ dollars, and so on: $$$i$$$-th item costs $$$i$$$ dollars. The items are situated on shelves. The items form a rectangular grid: there are $$$n$$$ shelves in total, and each shelf contains exactly $$$k$$$ items. We will denote by $$$a_{i,j}$$$ the price of $$$j$$$-th item (counting from the left) on the $$$i$$$-th shelf, $$$1 \le i \le n, 1 \le j \le k$$$.Occasionally robots get curious and ponder on the following question: what is the mean price (arithmetic average) of items $$$a_{i,l}, a_{i,l+1}, \ldots, a_{i,r}$$$ for some shelf $$$i$$$ and indices $$$l \le r$$$? Unfortunately, the old robots can only work with whole numbers. If the mean price turns out not to be an integer, they break down.You care about robots' welfare. You want to arrange the items in such a way that the robots cannot theoretically break. Formally, you want to choose such a two-dimensional array $$$a$$$ that:  Every number from $$$1$$$ to $$$n \cdot k$$$ (inclusively) occurs exactly once.  For each $$$i, l, r$$$, the mean price of items from $$$l$$$ to $$$r$$$ on $$$i$$$-th shelf is an integer. Find out if such an arrangement is possible, and if it is, give any example of such arrangement.

int solution() {
  long int t;
  long int n;
  long int k;
  scanf("%ld", &t);

  for (long int i = 0; i < t; i++) {
    scanf("%ld%ld", &n, &k);
    if (k == 1) {
      printf("YES\n");
      for (long int j = 0; j < n; j++) {
        printf("%ld\n", j + 1);
      }
      continue;
    }

    if (n % 2 == 1) {
      printf("NO\n");
      continue;
    }

    printf("YES\n");
    for (long int j = 0; j < n / 2; j++) {
      for (long int l = 0; l < k; l++) {
        printf("%ld ", (j * (2 * k)) + (2 * l) + 1);
      }
      printf("\n");
      for (long int l = 0; l < k; l++) {
        printf("%ld ", (j * (2 * k)) + (2 * l) + 2);
      }
      printf("\n");
    }
  }

  return 0;
}

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

    let stdout = io::stdout();
    let handle = stdout.lock();
    let mut buffer = BufWriter::with_capacity(65536, handle);
    for _t in 0..t {
        line.clear();
        stdin.read_line(&mut line).unwrap();
        let mut n_k = line.split_ascii_whitespace();
        let shelf_count: u32 = n_k.next().unwrap().parse().unwrap();
        let shelf_length: u32 = n_k.next().unwrap().parse().unwrap();

        if shelf_length == 1 || shelf_count & 1 == 0 {
            writeln!(&mut buffer, "YES").unwrap();

            let mut write_shelf = |start: &mut u32| {
                for _i in 0..shelf_length {
                    write!(&mut buffer, "{} ", start).unwrap();
                    *start += 2;
                }
                writeln!(&mut buffer).unwrap();
            };

            let mut last_even: u32 = 2;
            let mut last_odd: u32 = 1;
            for _i in 0..(shelf_count >> 1) {
                write_shelf(&mut last_odd);
                write_shelf(&mut last_even);
            }

            if shelf_count & 1 != 0 {
                write_shelf(&mut last_odd)
            }
        } else {
            writeln!(&mut buffer, "NO").unwrap();
        }
    }
    buffer.flush().unwrap();
}


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

int solution() {
  int countz = 0;
  int countn = 0;
  int n = 0;

  scanf("%d", &n);

  char mystring[n];

  scanf("%s", mystring);

  for (int i = 0; mystring[i] != '\0'; ++i) {
    if (mystring[i] == 'z') {
      ++countz;
    }
  }

  for (int i = 0; mystring[i] != '\0'; ++i) {
    if (mystring[i] == 'n') {
      ++countn;
    }
  }

  for (int i = 0; i < countn; i++) {
    printf("1 ");
  }
  for (int i = 0; i < countz; i++) {
    printf("0 ");
  }

  return 0;
}

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

    let mut s = String::new();
    std::io::stdin().read_line(&mut s).expect("Error  input");

    let len = s.len();
    s.retain(|c| c != 'z');
    let no_zeros = len - s.len();

    let remaining_count = s.len() - (no_zeros * 3);
    let no_ones = remaining_count / 3;

    let mut answer = std::iter::repeat_n("1", no_ones).collect::<Vec<_>>();
    answer.append(&mut std::iter::repeat_n("0", no_zeros).collect::<Vec<_>>());

    print!("{}", answer.join(" "));
}


A string $$$s$$$ of length $$$n$$$ ($$$1 \le n \le 26$$$) is called alphabetical if it can be obtained using the following algorithm:  first, write an empty string to $$$s$$$ (i.e. perform the assignment $$$s$$$ := "");  then perform the next step $$$n$$$ times;  at the $$$i$$$-th step take $$$i$$$-th lowercase letter of the Latin alphabet and write it either to the left of the string $$$s$$$ or to the right of the string $$$s$$$ (i.e. perform the assignment $$$s$$$ := $$$c+s$$$ or $$$s$$$ := $$$s+c$$$, where $$$c$$$ is the $$$i$$$-th letter of the Latin alphabet). In other words, iterate over the $$$n$$$ first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string $$$s$$$ or append a letter to the right of the string $$$s$$$. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical.

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

  for (int i = 0; i < t; i++) {
    char str[27] = {'\0'};
    scanf("%s", str);

    int len = strlen(str);

    int cnt[27] = {0};

    int j = 0;
    while (str[j] != '\0') {
      cnt[str[j] - 'a']++;
      j++;
    }
    bool alpha = true;
    int c = 0;
    for (int k = 0; k < 26 && k < j; k++) {
      if (cnt[k] != 1) {
        alpha = false;
      }

      c += cnt[k];
    }

    if (c > j) {
      alpha = false;
    }

    if (alpha == false) {
      printf("NO\n");
      continue;
    }

    j = 1;
    while (str[j] != '\0' && str[j - 1] > str[j]) {
      j++;
    }

    while (str[j] != '\0' && str[j - 1] < str[j]) {
      j++;
    }

    if (j != len) {
      printf("NO\n");
    } else {
      printf("YES\n");
    }
  }
}

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

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

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

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

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

    for _case_index in 1..=t {
        let s = lines.next().unwrap();
        let a = s.as_bytes();

        let ans = match a.iter().cloned().position(|x| x == b'a') {
            Some(i) => {
                let mut l = i;
                let mut r = i + 1;

                let mut x = true;

                for c in (b'b'..=b'z').take(a.len() - 1) {
                    match a.iter().cloned().position(|b| b == c) {
                        Some(i) => {
                            if i + 1 == l {
                                l -= 1;
                            } else if i == r {
                                r += 1;
                            } else {
                                x = false;
                                break;
                            }
                        }
                        None => {
                            x = false;
                            break;
                        }
                    }
                }

                x
            }
            None => false,
        };

        let ans = if ans { "Yes" } else { "No" };

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


Coin Changing Problem

Find the minimum number of coins to make change for <var>n</var> cents using coins of denominations <var>d1</var>, <var>d2</var>,.., <var>d</var><var>m</var>. The coins can be used any number of times.

Input

<var>n</var> <var>m</var>
<var>d1</var> <var>d2</var> ... <var>d</var><var>m</var>

Two integers <var>n</var> and <var>m</var> are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ <var>n</var> ≤ 50000

1 ≤ <var>m</var> ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3

fn solution() {
    let mut stdin = io::stdin();
    let mut buf = String::new();
    let _ = stdin.read_to_string(&mut buf);
    let mut iter = buf.split_whitespace();

    let n: usize = iter.next().unwrap().parse().unwrap();
    let _m: usize = iter.next().unwrap().parse().unwrap();
    let c: Vec<usize> = iter.map(|s| s.parse().unwrap()).collect();

    let mut dp = vec![std::usize::MAX; n + 1];
    dp[0] = 0;

    while dp[n] == std::usize::MAX {
        for i in 0..n {
            for c_i in c.iter() {
                if i + c_i <= n && dp[i] < std::usize::MAX {
                    dp[i + c_i] = min(dp[i + c_i], dp[i] + 1);
                }
            }
        }
    }

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


Score : <var>400</var> points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side <var>a~\mathrm{cm}</var> and whose height is <var>b~\mathrm{cm}</var>. (The thickness of the bottle can be ignored.)

We will pour <var>x~\mathrm{cm}^3</var> of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

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

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

<var>1 \leq x \leq a^2b</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most <var>10^{-6}</var>.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than <var>45</var> degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.

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

    let strs: Vec<&str> = line.split_whitespace().collect();
    let a: f64 = strs[0].parse().unwrap();
    let b: f64 = strs[1].parse().unwrap();
    let x: f64 = strs[2].parse().unwrap();

    let s = a * a * b;
    if x > s / 2.0 {
        let y = 2.0 * (s - x) / (a * a);
        println!("{:.7}", 90.0 - (a / y).atan() / f64::consts::PI * 180.0);
    } else {
        let y = 2.0 * x / (a * b);
        println!("{:.7}", 90.0 - (y / b).atan() / f64::consts::PI * 180.0);
    }
}