Score : <var>400</var> points

Problem Statement

Snuke has an empty sequence <var>a</var>.

He will perform <var>N</var> operations on this sequence.

In the <var>i</var>-th operation, he chooses an integer <var>j</var> satisfying <var>1 \leq j \leq i</var>, and insert <var>j</var> at position <var>j</var> in <var>a</var> (the beginning is position <var>1</var>).

You are given a sequence <var>b</var> of length <var>N</var>. Determine if it is possible that <var>a</var> is equal to <var>b</var> after <var>N</var> operations. If it is, show one possible sequence of operations that achieves it.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>b_1</var> <var>\dots</var> <var>b_N</var>

Output

If there is no sequence of <var>N</var> operations after which <var>a</var> would be equal to <var>b</var>, print -1.
If there is, print <var>N</var> lines. In the <var>i</var>-th line, the integer chosen in the <var>i</var>-th operation should be printed. If there are multiple solutions, any of them is accepted.

Sample Input 1

3
1 2 1

Sample Output 1

1
1
2

In this sequence of operations, the sequence <var>a</var> changes as follows:

After the first operation: <var>(1)</var>

After the second operation: <var>(1,1)</var>

After the third operation: <var>(1,2,1)</var>

Sample Input 2

2
2 2

Sample Output 2

-1

<var>2</var> cannot be inserted at the beginning of the sequence, so this is impossible.

Sample Input 3

9
1 1 1 2 2 1 2 3 2

Sample Output 3

1
2
2
3
1
2
2
1
1

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

fn solution() {
    use std::io::Read;
    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::<usize>().unwrap();
    let mut b: Vec<usize> = (&mut iter)
        .take(n)
        .map(|x| x.parse::<usize>().unwrap() - 1)
        .collect();

    let mut ret = vec![];
    let mut no_ans = false;
    while !b.is_empty() {
        let mut t = None;
        for i in 0..b.len() {
            let j = b.len() - 1 - i;
            if b[j] == j {
                t = Some(j);
                break;
            }
        }
        if let Some(v) = t {
            ret.push(v);
            b.remove(v);
        } else {
            no_ans = true;
            break;
        }
    }
    if no_ans {
        println!("-1");
    } else {
        ret = ret.iter().map(|x| *x + 1).collect();
        ret.reverse();
        for r in ret {
            println!("{}", r);
        }
    }
}


You are given two positive integers $$$n$$$ and $$$s$$$. Find the maximum possible median of an array of $$$n$$$ non-negative integers (not necessarily distinct), such that the sum of its elements is equal to $$$s$$$.A median of an array of integers of length $$$m$$$ is the number standing on the $$$\lceil {\frac{m}{2}} \rceil$$$-th (rounding up) position in the non-decreasing ordering of its elements. Positions are numbered starting from $$$1$$$. For example, a median of the array $$$[20,40,20,50,50,30]$$$ is the $$$\lceil \frac{m}{2} \rceil$$$-th element of $$$[20,20,30,40,50,50]$$$, so it is $$$30$$$. There exist other definitions of the median, but in this problem we use the described definition.

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

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

    mid = (s[i] / (n[i] / 2 + 1));

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

fn solution() {
    let stdin = std::io::stdin();
    let mut string = String::new();
    stdin.read_line(&mut string).unwrap();
    for _ in 0..string.trim().parse::<u128>().unwrap() {
        string.clear();
        stdin.read_line(&mut string).unwrap();
        let (num, sum) = {
            let mut s = string.trim().split_ascii_whitespace();
            (
                s.next().unwrap().parse::<u128>().unwrap(),
                s.next().unwrap().parse::<u128>().unwrap(),
            )
        };
        let average_num = {
            if num.checked_div(2).is_none() {
                num / 2
            } else {
                num / 2 + 1
            }
        };
        println!("{}", sum / average_num);
    }
}


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int n;
  scanf("%d", &n);
  int arr[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
    int temp = arr[i];
    arr[i] = temp - (temp / 2) - 1;
  }
  for (int i = 0; i < n; i++) {
    printf("%d\n", arr[i]);
  }
  return 0;
}

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

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

    let cases: u32 = cases.trim().parse().expect("nan");

    for _ in 0..cases {
        let mut line = String::new();
        io::stdin().read_line(&mut line).expect("bad line");

        let first: u32 = line.trim().parse().expect("nan");
        println!("{}", (first - 1) / 2);
    }
}


Score : <var>200</var> points

Problem Statement

You are given a positive integer <var>X</var>.
Find the largest perfect power that is at most <var>X</var>.
Here, a perfect power is an integer that can be represented as <var>b^p</var>, where <var>b</var> is an integer not less than <var>1</var> and <var>p</var> is an integer not less than <var>2</var>.

Constraints

<var>1</var> <var>≤</var> <var>X</var> <var>≤</var> <var>1000</var>

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

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

Print the largest perfect power that is at most <var>X</var>.

Sample Input 1

10

Sample Output 1

9

There are four perfect powers that are at most <var>10</var>: <var>1</var>, <var>4</var>, <var>8</var> and <var>9</var>.
We should print the largest among them, <var>9</var>.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

999

Sample Output 3

961

int solution() {
  double a = 1;
  double b = 2;
  int X = 0;
  int MAX = 0;

  scanf("%d", &X);

  if (X != 1) {
    for (a = 2; 2 * a < X; a++) {
      for (b = 2; pow(a, b) <= X; b++) {
        if (pow(a, b) > MAX) {
          MAX = (int)pow(a, b);
        }
      }
    }
  } else {
    MAX = X;
  }

  printf("%d", MAX);

  return 0;
}


Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple task. You are able to do it too, aren't you?Leha has two strings s and t. The hacker wants to change the string s at such way, that it can be found in t as a substring. All the changes should be the following: Leha chooses one position in the string s and replaces the symbol in this position with the question mark "?". The hacker is sure that the question mark in comparison can play the role of an arbitrary symbol. For example, if he gets string s="ab?b" as a result, it will appear in t="aabrbb" as a substring.Guaranteed that the length of the string s doesn't exceed the length of the string t. Help the hacker to replace in s as few symbols as possible so that the result of the replacements can be found in t as a substring. The symbol "?" should be considered equal to any other symbol.

int solution(void) {
  int n = 0;
  int m = 0;
  int i = 0;
  int j = 0;
  int match = 0;
  int max = 0;
  int pos = 0;
  char s[1001] = {
      0,
  };
  char t[1001] = {
      0,
  };

  scanf("%d %d", &n, &m);
  scanf("%s", s);
  scanf("%s", t);

  for (i = 0; i <= m - n; i++) {
    match = 0;
    for (j = 0; j < n; j++) {
      if (t[i + j] == s[j]) {
        match++;
      }
    }

    if (match > max) {
      max = match;
      pos = i;
    }
  }

  printf("%d\n", n - max);

  for (i = 0; i < n; i++) {
    if (s[i] != t[i + pos]) {
      printf("%d ", i + 1);
    }
  }
  printf("\n");

  return 0;
}

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

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

    let mut iter = input.split_whitespace();

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

    let mut ans: Option<usize> = None;

    let mut s = String::new();
    let mut t = String::new();

    io::stdin().read_line(&mut s).unwrap();
    io::stdin().read_line(&mut t).unwrap();

    let s = s.trim();
    let t = t.trim();

    let mut ansInd: Vec<usize> = Vec::new();

    let mut iter = t.chars().take(m - n + 1);
    let mut iter2 = t.chars();
    loop {
        let mut tmp: usize = 0;
        let other_iter = iter2.clone();
        match iter.next() {
            Some(_c) => {
                let other_iter = other_iter.zip(s.char_indices());
                let mut indices: Vec<usize> = Vec::new();
                for i in other_iter {
                    let (x, y) = i;
                    let (indice, y) = y;
                    if x != y {
                        tmp += 1;
                        indices.push(indice + 1);
                    }
                }
                match ans {
                    Some(i) if tmp < i => {
                        ans = Some(tmp);
                        ansInd = indices;
                    }
                    None => {
                        ans = Some(tmp);
                        ansInd = indices;
                    }
                    _ => (),
                }
            }
            None => break,
        }
        iter2.next();
    }

    println!("{}", ans.unwrap());
    if !ansInd.is_empty() {
        let mut ans_str = ansInd[0].to_string();
        let mut iter = ansInd.iter();
        iter.next();
        for i in iter {
            ans_str.push(' ');
            ans_str.push_str(&i.to_string()[..]);
        }
        println!("{}", ans_str);
    }
}


Casimir has a string $$$s$$$ which consists of capital Latin letters 'A', 'B', and 'C' only. Each turn he can choose to do one of the two following actions:  he can either erase exactly one letter 'A' and exactly one letter 'B' from arbitrary places of the string (these letters don't have to be adjacent);  or he can erase exactly one letter 'B' and exactly one letter 'C' from arbitrary places in the string (these letters don't have to be adjacent). Therefore, each turn the length of the string is decreased exactly by $$$2$$$. All turns are independent so for each turn, Casimir can choose any of two possible actions.For example, with $$$s$$$ $$$=$$$ "ABCABC" he can obtain a string $$$s$$$ $$$=$$$ "ACBC" in one turn (by erasing the first occurrence of 'B' and the second occurrence of 'A'). There are also many other options for a turn aside from this particular example.For a given string $$$s$$$ determine whether there is a sequence of actions leading to an empty string. In other words, Casimir's goal is to erase all letters from the string. Is there a way to do this?

fn solution() {
    let mut out = BufWriter::new(io::stdout().lock());
    io::stdin().lines().skip(1).flatten().for_each(|s| {
        match s.chars().fold((0usize, 0usize), |(b, len), c| match c {
            'B' => (b.wrapping_add(2), len.wrapping_add(1)),
            _ => (b, len.wrapping_add(1)),
        }) {
            (a, b) if a == b => writeln!(out, "YES"),
            _ => writeln!(out, "NO"),
        }
        .ok();
    });
}


int solution(int x) {
  int n = 0;
  int temp = x;
  int sum = 0;

  while (temp) {
    n++;
    temp /= 10;
  }

  temp = x;

  while (temp) {
    int r = temp % 10;

    int p = 1;
    for (int i = 0; i < n; i++) {
      p *= r;
    }

    sum += p;
    temp /= 10;
  }

  return (sum == x);
}

fn solution(number: u32) -> bool {
    let mut digits: Vec<u32> = Vec::new();
    let mut num: u32 = number;

    loop {
        digits.push(num % 10);
        num /= 10;
        if num == 0 {
            break;
        }
    }

    let sum_nth_power_of_digits: u32 = digits
        .iter()
        .map(|digit| digit.pow(digits.len() as u32))
        .sum();
    sum_nth_power_of_digits == number
}


Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \times 1 \times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

int solution() {
  int n;
  int m;
  int h;
  scanf("%d %d %d", &n, &m, &h);
  int f_arr[m];
  int l_arr[n];
  int arr[n][m];

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

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

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (arr[i][j]) {
        if (l_arr[i] < f_arr[j]) {
          arr[i][j] = l_arr[i];
        } else {
          arr[i][j] = f_arr[j];
        }
      }
    }
  }

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

  return 0;
}

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

    let n = get!(usize);
    let m = get!(usize);
    let _h = get!(usize);
    let mut front = vec![];
    for _ in 0..m {
        front.push(get!());
    }
    let mut left = vec![];
    for _ in 0..n {
        left.push(get!());
    }

    for i in 0..n {
        for j in 0..m {
            if j > 0 {
                print!(" ");
            }
            let mut p = get!();
            if p > 0 {
                p = std::cmp::min(front[j], left[i]);
            }
            print!("{}", p);
        }
        println!();
    }
}


You are given a multiset of n integers. You should select exactly k of them in a such way that the difference between any two of them is divisible by m, or tell that it is impossible.Numbers can be repeated in the original multiset and in the multiset of selected numbers, but number of occurrences of any number in multiset of selected numbers should not exceed the number of its occurrences in the original multiset.

fn solution() {
    let mut reader = io::BufReader::new(io::stdin());
    let mut s = String::new();
    reader.read_line(&mut s).unwrap();
    let input: Vec<i32> = s
        .trim_end()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let _N = input[0];
    let K = input[1];
    let M = input[2];
    s.clear();
    reader.read_line(&mut s).unwrap();
    let array: Vec<i32> = s
        .trim_end()
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let mut modulo: Vec<Vec<i32>> = Vec::new();
    for _i in 0..M {
        modulo.push(Vec::new());
    }
    for num in array {
        modulo[(num % M) as usize].push(num);
    }
    for i in 0..M {
        if modulo[i as usize].len() >= K as usize {
            println!("Yes");
            modulo[i as usize].truncate(K as usize);
            let mut s = String::new();
            while !modulo[i as usize].is_empty() {
                s.push_str(modulo[i as usize].pop().unwrap().to_string().as_ref());
                if !modulo[i as usize].is_empty() {
                    s.push(' ');
                }
            }
            println!("{}", s);
            process::exit(0);
        }
    }
    println!("No");
}


すごろくと駒 (Sugoroku and Pieces)

 問題文

JOI 君はすごろくを持っている．このすごろくは <var>2019</var> 個のマスが横一列に並んだ形をしている．これらのマスには，左端のスタートマスから右端のゴールマスへと順に <var>1</var> から <var>2019</var> までの番号がついている．

現在このすごろくの上には，<var>N</var> 個の駒が置かれている．これらの駒には，スタートに近い順に <var>1</var> から <var>N</var> までの番号がついている．駒 <var>i</var> (<var>1 ≦ i ≦ N</var>) は，マス <var>X_i</var> に置かれている．すべての駒は異なるマスに置かれている．

JOI 君はこれから <var>M</var> 回の操作を行う．<var>j</var> 回目 (<var>1 ≦ j ≦ M</var>) の操作では，駒 <var>A_j</var> を <var>1</var> マス先へ進める．ただし，移動元のマスがゴールマスであった場合，もしくは移動先のマスに別の駒が置かれている場合，駒 <var>A_j</var> は進まず，位置は変わらない．

すべての操作が終了した時点で，各駒が置かれているマスを求めよ．

制約

<var>1 ≦ N ≦ 100</var>

<var>1 ≦ X_1 < X_2 < ... < X_N ≦ 2019</var>

<var>1 ≦ M ≦ 100</var>

<var>1 ≦ A_j ≦ N</var> (<var>1 ≦ j ≦ M</var>)

入力・出力

入力

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

<var>N</var>

<var>X_1</var> <var>X_2</var> <var>...</var> <var>X_N</var>

<var>M</var>

<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_M</var>

出力

<var>N</var> 行出力せよ．<var>i</var> 行目 (<var>1 ≦ i ≦ N</var>) には，すべての操作が終了した時点で駒 <var>i</var> が置かれているマスの番号を出力せよ．

入出力例

入力例 1

3
2 3 6
2
1 3

出力例 1

2
3
7

<var>1</var> 回目の操作では，駒 <var>1</var> をマス <var>2</var> からマス <var>3</var> へと進めようする．しかし，駒 <var>2</var> がすでにマス <var>3</var> に置かれているため，駒 <var>1</var> は進まない．

<var>2</var> 回目の操作では，駒 <var>3</var> をマス <var>6</var> からマス <var>7</var> へと進める．

すべての操作が終了した時点で，駒 <var>1</var> はマス <var>2</var> に，駒 <var>2</var> はマス <var>3</var> に，駒 <var>3</var> はマス <var>7</var> に置かれている．

入力例 2

2
1 2016
4
2 2 2 2

出力例 2

1
2019

<var>3</var> 回目の操作が完了した時点で，駒 <var>2</var> はマス <var>2019</var> に置かれている．そのため，<var>4</var> 回目の操作では駒 <var>2</var> は進まない．

入力例 3

4
1001 1002 1003 1004
7
1 2 3 4 3 2 1

出力例 3

1002
1003
1004
1005

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

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

    lock.read_to_string(&mut buf);

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let mut x: Vec<usize> = iter
        .by_ref()
        .take(n)
        .map(|s| s.parse::<usize>().unwrap() - 1)
        .collect();
    let _m: usize = iter.next().unwrap().parse().unwrap();
    let a: Vec<usize> = iter.map(|s| s.parse::<usize>().unwrap() - 1).collect();

    let mut board: Vec<usize> = std::iter::repeat_n(0, 2019).collect();

    for (i, &place) in x.iter().enumerate() {
        board[place] = i;
    }

    for i in a {
        let place = x[i];
        if place < 2018 && board[place + 1] == 0 {
            x[i] += 1;
            board[place + 1] = board[place];
            board[place] = 0;
        }
    }

    for place in x {
        println!("{}", place + 1);
    }
}


Score : <var>400</var> points

Problem Statement

We have <var>N</var> balls. The <var>i</var>-th ball has an integer <var>A_i</var> written on it.

For each <var>k=1, 2, ..., N</var>, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the <var>N-1</var> balls other than the <var>k</var>-th ball so that the integers written on them are equal.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

For each <var>k=1,2,...,N</var>, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case <var>k=1</var> for example. The numbers written on the remaining balls are <var>1,2,1,2</var>.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for <var>k=1</var> is <var>2</var>.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5

fn solution() {
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let a: Vec<String> = st
        .split_whitespace()
        .map(|x| x.parse::<String>().unwrap())
        .collect();

    let mut dic: HashMap<&String, i64> = HashMap::new();
    for i in a.iter() {
        let count = dic.entry(i).or_insert(0);
        *count += 1;
    }
    let mut result: i64 = 0;
    for (_x, y) in dic.iter() {
        result += y * (y - 1) / 2;
    }

    for i in a.iter() {
        println!("{}", result - (dic[&i] - 1));
    }
}


Score : <var>300</var> points

Problem Statement

Find the maximum possible sum of the digits (in base <var>10</var>) of a positive integer not greater than <var>N</var>.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the maximum possible sum of the digits (in base <var>10</var>) of a positive integer not greater than <var>N</var>.

Sample Input 1

100

Sample Output 1

18

For example, the sum of the digits in <var>99</var> is <var>18</var>, which turns out to be the maximum value.

Sample Input 2

9995

Sample Output 2

35

For example, the sum of the digits in <var>9989</var> is <var>35</var>, which turns out to be the maximum value.

Sample Input 3

3141592653589793

Sample Output 3

137

int solution() {
  char s[17];
  bool is9 = true;
  scanf("%s", s);
  int len = strlen(s);
  for (int i = 1; i < len; i++) {
    if (s[i] != '9') {
      is9 = false;
      break;
    }
  }
  if (is9) {
    printf("%d\n", s[0] - '0' + (9 * len) - 9);
  } else {
    printf("%d\n", s[0] - '0' - 1 + (9 * len) - 9);
  }
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut m = n;
    let mut o = 0;
    let mut p = 0;
    while m > 9 {
        o += m % 10;
        m /= 10;
        p += 1;
    }

    println!("{}", max(m - 1 + p * 9, m + o));
}


The robot is placed in the top left corner of a grid, consisting of $$$n$$$ rows and $$$m$$$ columns, in a cell $$$(1, 1)$$$.In one step, it can move into a cell, adjacent by a side to the current one:   $$$(x, y) \rightarrow (x, y + 1)$$$;  $$$(x, y) \rightarrow (x + 1, y)$$$;  $$$(x, y) \rightarrow (x, y - 1)$$$;  $$$(x, y) \rightarrow (x - 1, y)$$$. The robot can't move outside the grid.The cell $$$(s_x, s_y)$$$ contains a deadly laser. If the robot comes into some cell that has distance less than or equal to $$$d$$$ to the laser, it gets evaporated. The distance between two cells $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.Print the smallest number of steps that the robot can take to reach the cell $$$(n, m)$$$ without getting evaporated or moving outside the grid. If it's not possible to reach the cell $$$(n, m)$$$, print -1.The laser is neither in the starting cell, nor in the ending cell. The starting cell always has distance greater than $$$d$$$ to the laser.

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

  for (int currentSet = 0; currentSet < numSets; ++currentSet) {
    int width = 0;
    int height = 0;
    int laserX = 0;
    int laserY = 0;
    int laserRadius = 0;
    scanf("%d %d %d %d %d", &width, &height, &laserX, &laserY, &laserRadius);

    int touches = 0;
    if ((laserX - laserRadius <= 1) || (laserY + laserRadius >= height)) {
      ++touches;
    }
    if ((laserX + laserRadius >= width) || (laserY - laserRadius <= 1)) {
      ++touches;
    }
    if (touches == 2) {
      printf("-1\n");
    } else {
      printf("%d\n", width + height - 2);
    }
  }

  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 _tests in 0..t {
        let (n, m, sx, sy, d): (i64, i64, i64, i64, i64) = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };
        let mut ans: i64 = n + m - 2;

        if sx - d <= 1 && sx + d >= n {
            ans = -1;
        }

        if sy - d <= 1 && sy + d >= m {
            ans = -1;
        }

        if sx - d <= 1 && sy - d <= 1 {
            ans = -1;
        }

        if sx + d >= n && sy + d >= m {
            ans = -1;
        }

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


Score : <var>300</var> points

Problem Statement

Snuke loves puzzles.

Today, he is working on a puzzle using S- and c-shaped pieces.
In this puzzle, you can combine two c-shaped pieces into one S-shaped piece, as shown in the figure below:

Snuke decided to create as many Scc groups as possible by putting together one S-shaped piece and two c-shaped pieces.

Find the maximum number of Scc groups that can be created when Snuke has <var>N</var> S-shaped pieces and <var>M</var> c-shaped pieces.

Constraints

<var>1 ≤ N,M ≤ 10^{12}</var>

Input

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

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

Output

Print the answer.

Sample Input 1

1 6

Sample Output 1

2

Two Scc groups can be created as follows:

Combine two c-shaped pieces into one S-shaped piece

Create two Scc groups, each from one S-shaped piece and two c-shaped pieces

Sample Input 2

12345 678901

Sample Output 2

175897

int solution(void) {
  unsigned long long N = 0;
  unsigned long long M = 0;
  unsigned long long sum = 0;
  unsigned long long hen = 0;

  scanf("%llu %llu", &N, &M);
  if (M >= 4 && (N * 2 <= M - 4)) {
    hen += (M - N * 2) / 4;
    M -= hen * 2;
    N += hen;
  };
  if (N <= M / 2) {
    sum += N;
  } else {
    sum += M / 2;
  };
  printf("%llu\n", sum);
}

fn solution() {
    use std::io;
    let mut input = String::new();
    let _ = io::stdin().read_line(&mut input);
    let input_nums = input
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap())
        .collect::<Vec<_>>();
    let n = input_nums[0];
    let m = input_nums[1];
    if n * 2 >= m {
        println!("{}", m / 2);
    } else {
        println!("{}", (m + n * 2) / 4);
    }
}


ポイントカード (Point Card)

問題

JOI 商店街ではポイントカードのサービスを行っている．各ポイントカードには 2N 個のマスがある．商品を購入すると，くじを引くことができ，結果によって「当たり」か「はずれ」の印がマスに押される．同じマスに印が 2 回押されることはない．2N 個のマスのうち N 個以上のマスに当たりの印が書かれたポイントカードは，景品と交換することができる．
また，ポイントカードの印は，1 マスにつき 1 円で書き換えてもらうことができる．

JOI 君は 2N 個のマスが全て埋まっているポイントカードを M 枚持っている．ポイントカード i (1 ≦ i ≦ M) には，Ai 個の当たり印と，Bi 個のはずれ印が押されている．JOI 君は M - 1 個以上の景品が欲しい．

JOI 君が M - 1 個以上の景品を得るために必要な費用の最小値を求めよ．

入力

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

1 行目には，2 個の整数 N, M (1 ≦ N ≦ 1000, 1 ≦ M ≦ 1000) が空白を区切りとして書かれている．これは，ポイントカードには 2N 個のマスがあり，JOI 君が M 枚のポイントカードを持っていることを表す．

続く M 行のうちの i 行目 (1 ≦ i ≦ M) には，それぞれ 2 個の整数 Ai, Bi (0 ≦ Ai ≦ 2N, 0 ≦ Bi ≦ 2N, Ai + Bi = 2N) が書かれており，ポイントカード i には Ai 個の当たり印と Bi 個のはずれ印が押されていることを表す．

 出力

JOI 君が M - 1 個以上の景品を得るために必要な費用の最小値を 1 行で出力せよ．

入出力例

入力例 1

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

出力例 1

4

入力例 2

5 4
5 5
8 2
3 7
8 2

出力例 2

0

入力例 1 においては，ポイントカード 1 のはずれ印を 3 つ当たり印に書き換えてもらい，ポイントカード 3 のはずれ印を 1 つ当たり印に書き換えてもらうと，4 円で 4 (= 5 - 1) 枚のカードが景品と交換可能になり，これが最小の費用である．

入力例 2 においては，既に 3 (= 4 - 1) 枚のカードが景品と交換可能なので，書き換えてもらう必要ない．

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

int solution(void) {
  int a = 0;
  int b = 0;
  int c = 0;
  int sum = 0;
  int max = 0;
  int n = 0;
  int m = 0;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < m; i++) {
    scanf("%d %d", &a, &b);
    c = n - a;
    if (c > 0) {
      sum += c;
    }
    if (c > max) {
      max = c;
    }
  }
  printf("%d\n", sum - max);
  return 0;
}

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

    let mut tuples = input.split('\n').map(|l| {
        let mut iter = l.split(' ').map(|s| s.parse::<usize>().unwrap());

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

    let (n, m) = tuples.next().unwrap();

    let (mut sum, mut max) = (0, 0);

    for (a, _) in tuples.take(m) {
        if a < n {
            let cost = n - a;
            sum += cost;
            if max < cost {
                max = cost;
            }
        }
    }

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


Score : <var>100</var> points

Problem Statement

There are <var>N</var> students in a school.

We will divide these students into some groups, and in each group they will discuss some themes.

You think that groups consisting of two or less students cannot have an effective discussion, so you want to have as many groups consisting of three or more students as possible.

Divide the students so that the number of groups consisting of three or more students is maximized.

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If you can form at most <var>x</var> groups consisting of three or more students, print <var>x</var>.

Sample Input 1

8

Sample Output 1

2

For example, you can form a group of three students and another of five students.

Sample Input 2

2

Sample Output 2

0

Sometimes you cannot form any group consisting of three or more students, regardless of how you divide the students.

Sample Input 3

9

Sample Output 3

3

int solution() {
  int N = 0;

  scanf("%d", &N);

  printf("%d\n", N / 3);
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    println!("{}", n / 3);
}


For years, the Day of city N was held in the most rainy day of summer. New mayor decided to break this tradition and select a not-so-rainy day for the celebration. The mayor knows the weather forecast for the $$$n$$$ days of summer. On the $$$i$$$-th day, $$$a_i$$$ millimeters of rain will fall. All values $$$a_i$$$ are distinct.The mayor knows that citizens will watch the weather $$$x$$$ days before the celebration and $$$y$$$ days after. Because of that, he says that a day $$$d$$$ is not-so-rainy if $$$a_d$$$ is smaller than rain amounts at each of $$$x$$$ days before day $$$d$$$ and and each of $$$y$$$ days after day $$$d$$$. In other words, $$$a_d < a_j$$$ should hold for all $$$d - x \le j < d$$$ and $$$d < j \le d + y$$$. Citizens only watch the weather during summer, so we only consider such $$$j$$$ that $$$1 \le j \le n$$$.Help mayor find the earliest not-so-rainy day of summer.

fn solution() {
    let (n, x, y) = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse::<isize>().unwrap(),
            iter.next().unwrap().parse::<isize>().unwrap(),
            iter.next().unwrap().parse::<isize>().unwrap(),
        )
    };

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

    let mut answ = 0;
    for i in 0..n {
        let current = a[i as usize];
        let mut good = true;
        for j in i - x..=i + y {
            if j >= 0 && j < n && a[j as usize] <= current && i != j {
                good = false;
                break;
            }
        }
        if good {
            answ = i;
            break;
        }
    }

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


You have given an array $$$a$$$ of length $$$n$$$ and an integer $$$x$$$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $$$q$$$. If $$$q$$$ is divisible by $$$x$$$, the robot adds $$$x$$$ copies of the integer $$$\frac{q}{x}$$$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $$$q$$$ is not divisible by $$$x$$$, the robot shuts down.Please determine the sum of all values of the array at the end of the process.

int solution() {
  int t;
  int n;
  int k;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    long long int flag = 0;
    long long int sum = 0;
    scanf("%d%d", &n, &k);
    long long int a[n];
    long long int c[100000] = {0};
    long long int b[n];
    for (int j = 0; j < n; j++) {
      scanf("%lld", &a[j]);
      b[j] = a[j];
    }
    while (flag == 0) {
      for (int i = 0; i < n && flag == 0; i++) {
        if (b[i] % k == 0) {
          c[i]++;
          b[i] /= k;
        } else {
          flag = 1;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      sum += (c[i] + 1) * a[i];
    }
    printf("%lld\n", sum);
  }
}

fn solution() {
    let k = std::io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i128>()
        .unwrap();
    'rest: for _ls in 0..k {
        let mut l = String::new();
        std::io::stdin().read_line(&mut l).unwrap();
        let l = l
            .trim()
            .split(" ")
            .flat_map(str::parse::<i128>)
            .collect::<Vec<i128>>();
        let mut m = String::new();
        std::io::stdin().read_line(&mut m).unwrap();
        let mut m = m
            .trim()
            .split(" ")
            .flat_map(str::parse::<i128>)
            .collect::<Vec<i128>>();
        let mut ans: i128 = m.iter().sum();
        let pbool = true;
        let mut level = 1;
        'breaker: while pbool {
            for (_index, ls) in m.iter_mut().enumerate() {
                if *ls % l[1] == 0 {
                    *ls /= l[1];
                    ans += *ls * (l[1].pow(level));
                } else {
                    println!("{}", ans);
                    continue 'rest;
                }
            }
            level += 1;
        }
    }
}


Score : <var>100</var> points

Problem Statement

You are given three strings <var>A</var>, <var>B</var> and <var>C</var>. Check whether they form a word chain.

More formally, determine whether both of the following are true:

The last character in <var>A</var> and the initial character in <var>B</var> are the same.

The last character in <var>B</var> and the initial character in <var>C</var> are the same.

If both are true, print YES. Otherwise, print NO.

Constraints

<var>A</var>, <var>B</var> and <var>C</var> are all composed of lowercase English letters (a - z).

<var>1 ≤ |A|, |B|, |C| ≤ 10</var>, where <var>|A|</var>, <var>|B|</var> and <var>|C|</var> are the lengths of <var>A</var>, <var>B</var> and <var>C</var>, respectively.

Input

Input is given from Standard Input in the following format:

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

Output

Print YES or NO.

Sample Input 1

rng gorilla apple

Sample Output 1

YES

They form a word chain.

Sample Input 2

yakiniku unagi sushi

Sample Output 2

NO

<var>A</var> and <var>B</var> form a word chain, but <var>B</var> and <var>C</var> do not.

Sample Input 3

a a a

Sample Output 3

YES

Sample Input 4

aaaaaaaaab aaaaaaaaaa aaaaaaaaab

Sample Output 4

NO

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let iter = buf.split_whitespace();
    let mut v: Vec<Vec<char>> = Vec::new();
    for i in iter {
        v.push(i.chars().collect::<Vec<char>>());
    }
    let a = v[0].clone();
    let b = v[1].clone();
    let c = v[2].clone();
    if a[a.len() - 1] == b[0] && b[b.len() - 1] == c[0] {
        println!("YES");
    } else {
        println!("NO");
    }
}


You are given an array $$$a_1, a_2, \ldots, a_n$$$ of positive integers. A good pair is a pair of indices $$$(i, j)$$$ with $$$1 \leq i, j \leq n$$$ such that, for all $$$1 \leq k \leq n$$$, the following equality holds:$$$$$$ |a_i - a_k| + |a_k - a_j| = |a_i - a_j|, $$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Find a good pair. Note that $$$i$$$ can be equal to $$$j$$$.

int solution() {
  int t;
  scanf("%d", &t);
  if (t > 1000 || t < 0) {
    return 0;
  }
  int n[t];
  int **a = malloc(sizeof(int *) * t);
  for (int i = 0; i < t; i++) {
    scanf("%d", &n[i]);
    if (n[i] > 100000 || n[i] < 1) {
      return 0;
    }
    a[i] = malloc(sizeof(int) * n[i]);
    for (int j = 0; j < n[i]; j++) {
      scanf("%d", &a[i][j]);
      if (a[i][j] > 1000000000 || a[i][j] < 1) {
        return 0;
      }
    }
  }
  int sum = 0;
  for (int i = 0; i < t; i++) {
    sum += n[i];
  }
  if (sum > 200000) {
    return 0;
  }

  int count = 0;
  for (int x = 0; x < t; x++) {

    int max = a[x][0];
    int mai = 0;
    int min = a[x][0];
    int mii = 0;
    for (int i = 0; i < n[x]; i++) {
      if (a[x][i] > max) {
        max = a[x][i];
        mai = i;
      }
    }
    for (int i = 0; i < n[x]; i++) {
      if (a[x][i] < min) {
        min = a[x][i];
        mii = i;
      }
    }
    printf("%d %d\n", mii + 1, mai + 1);
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let _n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let a: Vec<u64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let x = 1 + a.iter().enumerate().max_by(|l, r| l.1.cmp(r.1)).unwrap().0;
        let y = 1 + a.iter().enumerate().min_by(|l, r| l.1.cmp(r.1)).unwrap().0;
        println!("{} {}", y, x);
    }
}


Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows:   $$$a_1 = -1$$$  $$$a_2 = 2$$$  $$$a_3 = -3$$$  $$$a_4 = 4$$$  $$$a_5 = -5$$$  And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers!

fn solution() -> std::io::Result<()> {
    let mut contents = String::new();
    std::io::stdin().read_line(&mut contents)?;
    let contents: Vec<&str> = contents.split("\r\n").collect();
    let contents: &str = contents[0];
    let q: u32 = contents.parse().unwrap();
    for _i in 0..q {
        let mut contents = String::new();
        std::io::stdin().read_line(&mut contents)?;
        let contents: Vec<&str> = contents.split("\r\n").collect();
        let contents: &str = contents[0];
        let contents: Vec<&str> = contents.split_whitespace().collect();
        let l: i64 = contents[0].parse().unwrap();
        let r: i64 = contents[1].parse().unwrap();
        let ll = if l % 2 == 0 && l == r {
            0
        } else if l % 2 == 1 {
            l
        } else {
            l + 1
        };
        let lr = if r % 2 == 0 && l == r {
            0
        } else if r % 2 == 1 {
            r
        } else {
            r - 1
        };
        let rl = if l % 2 == 1 && l == r {
            0
        } else if l % 2 == 0 {
            l
        } else {
            l + 1
        };
        let rr = if r % 2 == 1 && l == r {
            0
        } else if r % 2 == 0 {
            r
        } else {
            r - 1
        };
        let odd = ((ll + lr) / 2) * ((lr - ll) / 2 + 1);
        let even = ((rr + rl) / 2) * ((rr - rl) / 2 + 1);
        println!("{}", even - odd);
    }

    Ok(())
}


For some time the program of rounding numbers that had been developed by the Codeforces participants during one of the previous rounds, helped the citizens of Far Far Away to convert numbers into a more easily readable format. However, as time went by, the economy of the Far Far Away developed and the scale of operations grew. So the King ordered to found the Bank of Far Far Away and very soon even the rounding didn't help to quickly determine even the order of the numbers involved in operations. Besides, rounding a number to an integer wasn't very convenient as a bank needed to operate with all numbers with accuracy of up to 0.01, and not up to an integer.The King issued yet another order: to introduce financial format to represent numbers denoting amounts of money. The formal rules of storing a number in the financial format are as follows:   A number contains the integer part and the fractional part. The two parts are separated with a character "." (decimal point).  To make digits in the integer part of a number easier to read, they are split into groups of three digits, starting from the least significant ones. The groups are separated with the character "," (comma). For example, if the integer part of a number equals 12345678, then it will be stored in the financial format as 12,345,678  In the financial format a number's fractional part should contain exactly two digits. So, if the initial number (the number that is converted into the financial format) contains less than two digits in the fractional part (or contains no digits at all), it is complemented with zeros until its length equals 2. If the fractional part contains more than two digits, the extra digits are simply discarded (they are not rounded: see sample tests).  When a number is stored in the financial format, the minus sign is not written. Instead, if the initial number had the minus sign, the result is written in round brackets.  Please keep in mind that the bank of Far Far Away operates using an exotic foreign currency — snakes ($), that's why right before the number in the financial format we should put the sign "$". If the number should be written in the brackets, then the snake sign should also be inside the brackets. For example, by the above given rules number 2012 will be stored in the financial format as "$2,012.00" and number -12345678.9 will be stored as "($12,345,678.90)".The merchants of Far Far Away visited you again and expressed much hope that you supply them with the program that can convert arbitrary numbers to the financial format. Can you help them?

int solution() {
  char str[101];
  char minus = 0;
  scanf("%s", str);
  if (str[0] == '-') {
    minus = 1;
  }
  char integerStr[101];
  int integerLen = 0;
  for (int i = minus; str[i] != '.' && str[i]; ++i) {
    integerStr[integerLen++] = str[i];
  }
  int tail = 2;
  char fractionalStr[tail];
  int fractionalLen = 0;
  for (int i = 0; i < tail; ++i) {
    fractionalStr[i] = '0';
  }
  for (int i = minus + integerLen; str[i]; ++i) {
    if (str[i] >= '0' && str[i] <= '9') {
      fractionalStr[fractionalLen++] = str[i];
      if (fractionalLen == tail) {
        break;
      }
    }
  }
  if (minus) {
    putchar('(');
  }
  putchar('$');
  for (int i = 0; i < integerLen; ++i) {
    putchar(integerStr[i]);
    if (i != integerLen - 1 && (i + 1 - integerLen % 3) % 3 == 0) {
      putchar(',');
    }
  }
  putchar('.');
  for (int i = 0; i < tail; ++i) {
    putchar(fractionalStr[i]);
  }
  if (minus) {
    putchar(')');
  }
  return 0;
}

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

    let minus = s.contains('-');

    let mut r = String::new();

    if minus {
        r.push(')');
        s = s.get(1..).unwrap().to_string();
    }

    let mut frac = "00".to_string();
    if let Some(idx) = s.find('.') {
        frac.insert_str(0, s.get((idx + 1)..).unwrap());
        s.truncate(idx);
    }
    r.insert_str(0, frac.get(..2).unwrap());
    r.insert(0, '.');

    while s.len() > 3 {
        let b3 = s.len() - 3;
        r.insert_str(0, s.get(b3..).unwrap());
        r.insert(0, ',');
        s.truncate(b3);
    }
    r.insert_str(0, &s);

    r.insert(0, '$');
    if minus {
        r.insert(0, '(');
    }
    println!("{}", r);
}


Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.

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

        let num_m = n / m;
        let m10 = m % 10;
        let mut sum: u64 = 0;
        if num_m % 10 != 0 && m10 != 0 {
            sum = (m10..)
                .step_by(m10 as usize)
                .take((num_m % 10) as usize)
                .map(|x| x % 10)
                .sum();
        }
        match m10 {
            0 => (),
            5 => sum += 25 * (num_m / 10),
            2 | 4 | 6 | 8 => sum += 40 * (num_m / 10),
            _ => sum += 45 * (num_m / 10),
        }
        println!("{}", sum);
    }
}


A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island).Find a way to cover some cells with sand so that exactly k islands appear on the n × n map, or determine that no such way exists.

fn solution() {
    let inputstatus = 1;

    let mut buf = String::new();
    let filename = "inputrust.txt";

    if inputstatus == 0 {
        let mut f = File::open(filename).expect("file not found");
        f.read_to_string(&mut buf)
            .expect("something went wrong reading the file");
    } else {
        std::io::stdin().read_to_string(&mut buf).unwrap();
    }

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let mut k: usize = iter.next().unwrap().parse().unwrap();

    if n.is_multiple_of(2) && k > n * n / 2 {
        println!("NO");
        return;
    } else if n % 2 == 1 && k > n * n / 2 + 1 {
        println!("NO");
        return;
    }

    println!("YES");
    for i in 0..n {
        for j in 0..n {
            if k > 0 && (i + j) % 2 == 0 {
                k -= 1;
                print!("L");
            } else {
                print!("S");
            }
        }
        println!();
    }
}


You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands:  for $$$n$$$ — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every "for $$$n$$$" is matched with "end", thus the function is guaranteed to be valid. "for $$$n$$$" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some "add" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

int solution() {
  long long int32max = 4294967296 - 1;
  int ofc = 0;
  int i;
  int n;
  scanf("%d", &n);
  long long arr[n];
  int index = 0;
  long long mult = 1;
  int fnum[n];
  int fnumindex = 0;
  for (i = 0; i < n; i++) {
    arr[i] = 0;
  }
  for (i = 0; i < n; i++) {
    char inp[10];
    scanf(" %s", inp);

    if (inp[0] == 'a') {
      if (mult > int32max) {
        printf("OVERFLOW!!!");
        return 0;
      }
      arr[index++] = mult;

    } else if (inp[0] == 'f') {
      i--;
    } else if (inp[0] == 'e') {
      if (ofc == 0) {
        mult /= fnum[--fnumindex];
      } else {
        ofc--;
      }

    } else {
      if (mult < int32max) {
        fnum[fnumindex++] = atoi(inp);
        mult *= fnum[fnumindex - 1];
      } else {
        ofc++;
      }
    }
  }

  long long add = 0;
  for (i = 0; i < n; i++) {
    add += arr[i];
    if (add > int32max) {
      printf("OVERFLOW!!!");
      return 0;
    }
  }
  printf("%lld", add);
  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let t: i64 = line.trim().parse::<i64>().expect("error");
    let mut x = 0i64;
    let mut state: Vec<i64> = Vec::new();
    let num_iter = 1i64;
    state.push(num_iter);
    for _ in 0..t {
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let r: Vec<&str> = line.split_whitespace().collect();
        if r[0] == "add" {
            x += state[state.len() - 1];
            if x >= (1 << 32) {
                println!("OVERFLOW!!!");
                ::std::process::exit(0);
            }
        } else if r[0] == "for" {
            let amt: i64 = r[1].trim().parse::<i64>().expect("error");
            state.push(cmp::min(state[state.len() - 1] * amt, 1 << 32));
        } else {
            if !state.is_empty() {
                state.pop();
            }
        }
    }
    println!("{:?}", x);
}


Valera is a collector. Once he wanted to expand his collection with exactly one antique item.Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.

int solution(void) {
  int n;
  int net;
  scanf("%d %d", &n, &net);
  int a[n];
  int d[n];
  int count = 0;
  int **ptr = (int **)malloc(n * sizeof(int *));
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    ptr[i] = (int *)malloc(a[i] * sizeof(int));
    for (int j = 0; j < a[i]; j++) {
      scanf("%d", &ptr[i][j]);
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < a[i]; j++) {
      if (net > ptr[i][j]) {
        d[count++] = i;
        break;
      }
    }
  }
  printf("%d\n", count);
  for (int i = 0; i < count; i++) {
    printf("%d", d[i] + 1);
    if (i != count - 1) {
      printf(" ");
    }
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let a: Vec<i32> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();

    let n = a[0];
    let v = a[1];

    let mut sellers: Vec<Vec<i32>> = vec![];
    for _ in 0..n {
        let mut s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        sellers.push(s.split_whitespace().map(|x| x.parse().unwrap()).collect());
    }

    let mut r = 0;
    let mut s = String::new();

    for (idx, seller) in sellers.iter().enumerate() {
        for i in 1..seller.len() {
            if seller[i] < v {
                s = format!("{} {}", s, idx + 1);
                r += 1;
                break;
            }
        }
    }

    println!("{}", r);
    println!("{}", s.trim());
}


Monocarp is planning to host a martial arts tournament. There will be three divisions based on weight: lightweight, middleweight and heavyweight. The winner of each division will be determined by a single elimination system.In particular, that implies that the number of participants in each division should be a power of two. Additionally, each division should have a non-zero amount of participants.$$$n$$$ participants have registered for the tournament so far, the $$$i$$$-th of them weighs $$$a_i$$$. To split participants into divisions, Monocarp is going to establish two integer weight boundaries $$$x$$$ and $$$y$$$ ($$$x < y$$$). All participants who weigh strictly less than $$$x$$$ will be considered lightweight. All participants who weigh greater or equal to $$$y$$$ will be considered heavyweight. The remaining participants will be considered middleweight.It's possible that the distribution doesn't make the number of participants in each division a power of two. It can also lead to empty divisions. To fix the issues, Monocarp can invite an arbitrary number of participants to each division.Note that Monocarp can't kick out any of the $$$n$$$ participants who have already registered for the tournament.However, he wants to invite as little extra participants as possible. Help Monocarp to choose $$$x$$$ and $$$y$$$ in such a way that the total amount of extra participants required is as small as possible. Output that amount.

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

    let stdin = stdin.lock();
    let stdout = stdout.lock();
    let mut stdout = BufWriter::new(stdout);

    let mut stdin = stdin.lines();
    let mut read = || stdin.next().unwrap().unwrap();

    let nn: usize = read().parse().unwrap_or_default();
    for _i in 0..nn {
        let n: usize = read().parse().unwrap_or_default();
        let mut w: Box<[u32]> = read()
            .split_ascii_whitespace()
            .take(n)
            .map(|t| t.parse().unwrap_or_default())
            .collect();
        w.sort();

        let mut prev = None;
        let mut cnt = 0;
        let mut stat = Vec::new();
        for x in w.iter() {
            if prev == Some(x) {
                cnt += 1;
            } else {
                if let Some(_) = prev.replace(x) {
                    stat.push(cnt)
                }
                cnt = 1;
            }
        }
        if let Some(_) = prev {
            stat.push(cnt)
        }

        let mut stat_sums = vec![0_usize; stat.len()];
        let mut stat_sums_reverse = vec![0_usize; stat.len()];
        for i in 0..stat.len() {
            stat_sums[i] = stat[i] + if i > 0 { stat_sums[i - 1] } else { 0 };
        }

        for i in 0..stat.len() {
            stat_sums_reverse[i] =
                stat[stat.len() - (i + 1)] + if i > 0 { stat_sums_reverse[i - 1] } else { 0 };
        }

        let mut assign_lo = Vec::new();
        let mut assign_hi = Vec::new();
        let mut bucket = 1;
        while bucket <= n {
            let mut pos = stat_sums.partition_point(|&x| x <= bucket);
            let mut taken = if pos > 0 { stat_sums[pos - 1] } else { 0 };
            let mut added = bucket - taken;
            assign_lo.push((taken, added));

            pos = stat_sums_reverse.partition_point(|&x| x <= bucket);
            taken = if pos > 0 {
                stat_sums_reverse[pos - 1]
            } else {
                0
            };
            added = bucket - taken;
            assign_hi.push((taken, added));
            bucket *= 2;
        }

        let mut best = usize::MAX;
        for lo in &assign_lo {
            for hi in &assign_hi {
                let overflow;
                let mid_taken;
                if lo.0 + hi.0 > n {
                    overflow = lo.0 + hi.0 - n;
                    mid_taken = 0;
                } else {
                    overflow = 0;
                    mid_taken = n - lo.0 - hi.0;
                }

                let mid_added = if mid_taken > 0 {
                    mid_taken.next_power_of_two() - mid_taken
                } else {
                    1
                };

                let total_added = mid_added + lo.1 + hi.1 + overflow;

                best = min(total_added, best);
            }
        }

        writeln!(stdout, "{}", best).unwrap();
    }

    stdout.flush().unwrap();
}


The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:  ti = 1, if the i-th child is good at programming,  ti = 2, if the i-th child is good at maths,  ti = 3, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?

int solution() {
  int n;
  int c1 = 0;
  int c2 = 0;
  int c3 = 0;
  int mino = 0;
  scanf("%d", &n);
  int a[n];
  int one1[n];
  int duo2[n];
  int tre3[n];
  for (int i = 1; i <= n; i++) {
    scanf("%d", &a[i]);
    if (a[i] == 1) {
      one1[c1++] = i;
    } else if (a[i] == 2) {
      duo2[c2++] = i;
    } else {
      tre3[c3++] = i;
    }
  }
  if (c1 <= c2 && c1 <= c3) {
    mino = c1;
  } else if (c2 <= c1 && c2 <= c3) {
    mino = c2;
  } else {
    mino = c3;
  }
  printf("%d\n", mino);
  if (mino != 0) {
    for (int i = 0; i < mino; i++) {
      printf("%d %d %d\n", one1[i], duo2[i], tre3[i]);
    }
  }
}

fn solution() {
    use std::io;
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let students = buf
        .split_whitespace()
        .map(|str| str.trim().parse::<u32>().unwrap());
    let mut p = Vec::with_capacity(5000);
    let mut m = Vec::with_capacity(5000);
    let mut e = Vec::with_capacity(5000);
    for (i, student) in students.enumerate().map(|(i, x)| (i + 1, x)) {
        if student == 1 {
            p.push(i);
        } else if student == 2 {
            m.push(i);
        } else if student == 3 {
            e.push(i);
        }
    }
    use std::cmp::min;
    let teams = min(p.len(), min(m.len(), e.len()));
    println!("{}", teams);
    for _ in 0..teams {
        println!(
            "{} {} {}",
            p.pop().unwrap(),
            m.pop().unwrap(),
            e.pop().unwrap()
        );
    }
}


Score : <var>400</var> points

Problem Statement

We have <var>N</var> dice arranged in a line from left to right. The <var>i</var>-th die from the left shows <var>p_i</var> numbers from <var>1</var> to <var>p_i</var> with equal probability when thrown.

We will choose <var>K</var> adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this sum.

Constraints

<var>1 ≤ K ≤ N ≤ 200000</var>

<var>1 ≤ p_i ≤ 1000</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>p_1</var> ... <var>p_N</var>

Output

Print the maximum possible value of the expected value of the sum of the numbers shown.

Your output will be considered correct when its absolute or relative error from our answer is at most <var>10^{-6}</var>.

Sample Input 1

5 3
1 2 2 4 5

Sample Output 1

7.000000000000

When we throw the third, fourth, and fifth dice from the left, the expected value of the sum of the numbers shown is <var>7</var>. This is the maximum value we can achieve.

Sample Input 2

4 1
6 6 6 6

Sample Output 2

3.500000000000

Regardless of which die we choose, the expected value of the number shown is <var>3.5</var>.

Sample Input 3

10 4
17 13 13 12 15 20 10 13 17 11

Sample Output 3

32.000000000000

int solution() {
  int N;
  int K;
  scanf("%d%d", &N, &K);
  double p[N];
  double sum_E = 0;
  double ans = 0;
  for (int i = 0; i < N; i++) {
    scanf("%lf", &p[i]);
    p[i] = ((p[i] * (p[i] + 1)) / 2) / p[i];
  }

  for (int i = 0; i < K; i++) {
    sum_E += p[i];
  }

  if (N == K) {
    printf("%.12f", sum_E);
  } else {
    for (int i = 0; i <= N - K; i++) {
      sum_E += (p[K + i] - p[i]);
      if (ans < sum_E) {
        ans = sum_E;
      }
    }
    printf("%.12f", ans);
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    let (n, k): (usize, usize) = {
        std::io::stdin().read_line(&mut buf).unwrap();
        let words: Vec<usize> = buf.split_whitespace().map(|w| w.parse().unwrap()).collect();
        (words[0], words[1])
    };
    let ps: Vec<f64> = {
        buf.clear();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.split_whitespace().map(|w| w.parse().unwrap()).collect()
    };
    let mut cumsum = vec![0_f64; n + 1];
    for i in 0..n {
        cumsum[i + 1] = cumsum[i] + (ps[i] + 1.0) / 2.0;
    }
    let mut max = cumsum[k] - cumsum[0];
    for i in k + 1..n + 1 {
        let e = cumsum[i] - cumsum[i - k];
        if e > max {
            max = e;
        }
    }
    println!("{}", max);
}


Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across $$$n$$$ sessions follow the identity permutation (ie. in the first game he scores $$$1$$$ point, in the second game he scores $$$2$$$ points and so on). However, when he checks back to his record, he sees that all the numbers are mixed up! Define a special exchange as the following: choose any subarray of the scores and permute elements such that no element of subarray gets to the same position as it was before the exchange. For example, performing a special exchange on $$$[1,2,3]$$$ can yield $$$[3,1,2]$$$ but it cannot yield $$$[3,2,1]$$$ since the $$$2$$$ is in the same position. Given a permutation of $$$n$$$ integers, please help Patrick find the minimum number of special exchanges needed to make the permutation sorted! It can be proved that under given constraints this number doesn't exceed $$$10^{18}$$$.An array $$$a$$$ is a subarray of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

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

    let mut out = Vec::new();
    for _ in 0..t {
        let n: usize = itr.next().unwrap().parse().unwrap();
        let a: Vec<usize> = (0..n)
            .map(|_| itr.next().unwrap().parse().unwrap())
            .collect();

        let mut l = 0;
        let mut r = n - 1;
        while l < n && a[l] == l + 1 {
            l += 1;
        }
        while a[r] == r + 1 {
            r -= 1;
            if r == 0 {
                break;
            }
        }
        if l >= r {
            writeln!(out, "0").ok();
            continue;
        }
        let mut check = false;
        for i in l..r + 1 {
            if a[i] == i + 1 {
                check = true;
            }
        }
        writeln!(out, "{}", if check { 2 } else { 1 }).ok();
    }
    stdout().write_all(&out).unwrap();
}


You're given an array $$$a$$$ of $$$n$$$ integers, such that $$$a_1 + a_2 + \cdots + a_n = 0$$$.In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), decrement $$$a_i$$$ by one and increment $$$a_j$$$ by one. If $$$i < j$$$ this operation is free, otherwise it costs one coin.How many coins do you have to spend in order to make all elements equal to $$$0$$$?

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

    long long cur = 0;
    for (int i = 0; i < n; i++) {
      cur = cur + a[i];

      if (cur < 0) {
        cur = 0;
      }
    }
    printf("%lld\n", cur);
    t--;
  }
}

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

    let mut mx: i64;
    let mut count: i64;
    for _ in 0..t {
        let mut q;
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        q = input
            .split_whitespace()
            .map(|x| x.parse::<i64>().unwrap())
            .rev();
        mx = 0;
        count = 0;
        for num in &mut q {
            count += num;
            mx = max(count, mx);
        }
        println!("{}", mx);
        input.clear();
    }
}


Let $$$a$$$ and $$$b$$$ be two arrays of lengths $$$n$$$ and $$$m$$$, respectively, with no elements in common. We can define a new array $$$\mathrm{merge}(a,b)$$$ of length $$$n+m$$$ recursively as follows:  If one of the arrays is empty, the result is the other array. That is, $$$\mathrm{merge}(\emptyset,b)=b$$$ and $$$\mathrm{merge}(a,\emptyset)=a$$$. In particular, $$$\mathrm{merge}(\emptyset,\emptyset)=\emptyset$$$.  If both arrays are non-empty, and $$$a_1<b_1$$$, then $$$\mathrm{merge}(a,b)=[a_1]+\mathrm{merge}([a_2,\ldots,a_n],b)$$$. That is, we delete the first element $$$a_1$$$ of $$$a$$$, merge the remaining arrays, then add $$$a_1$$$ to the beginning of the result.  If both arrays are non-empty, and $$$a_1>b_1$$$, then $$$\mathrm{merge}(a,b)=[b_1]+\mathrm{merge}(a,[b_2,\ldots,b_m])$$$. That is, we delete the first element $$$b_1$$$ of $$$b$$$, merge the remaining arrays, then add $$$b_1$$$ to the beginning of the result. This algorithm has the nice property that if $$$a$$$ and $$$b$$$ are sorted, then $$$\mathrm{merge}(a,b)$$$ will also be sorted. For example, it is used as a subroutine in merge-sort. For this problem, however, we will consider the same procedure acting on non-sorted arrays as well. For example, if $$$a=[3,1]$$$ and $$$b=[2,4]$$$, then $$$\mathrm{merge}(a,b)=[2,3,1,4]$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).There is a permutation $$$p$$$ of length $$$2n$$$. Determine if there exist two arrays $$$a$$$ and $$$b$$$, each of length $$$n$$$ and with no elements in common, so that $$$p=\mathrm{merge}(a,b)$$$.

int solution() {
  int tests;
  scanf("%d", &tests);
  for (int t = 0; t < tests; ++t) {
    int n;
    scanf("%d", &n);
    int p[2 * n];
    int idx[(2 * n) + 1];
    bool seen[(2 * n) + 1];
    bool sol[(2 * n) + 1];
    for (int i = 0; i < 2 * n; ++i) {
      scanf("%d", p + i);
      idx[p[i]] = i;
      seen[p[i]] = false;
      sol[i] = false;
    }
    sol[0] = true;
    int last_idx = 2 * n;
    for (int max = 2 * n; max >= 1; --max) {
      if (!seen[max]) {
        for (int i = idx[max]; i < last_idx; ++i) {
          seen[p[i]] = true;
        }
        int len = last_idx - idx[max];
        last_idx = idx[max];
        for (int s = n; s >= len; --s) {
          if (sol[s - len]) {
            sol[s] = true;
          }
        }
      }
    }
    if (sol[n]) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let stdout = io::stdout();
    let mut output = BufWriter::new(stdout.lock());
    let mut stdin = io::stdin();
    let mut input_str = String::new();
    stdin.read_to_string(&mut input_str).unwrap();

    let mut input_iter = input_str.split_whitespace();

    let test_cases: usize = read!();

    for _ in 0..test_cases {
        let n: usize = read!();

        let mut v = Vec::<usize>::with_capacity(n * 2);

        for _ in 0..(n * 2) {
            v.push(read!());
        }

        let mut chunks = Vec::<usize>::with_capacity(n * 2);
        let mut count = 0;
        let mut max_in_aggregated_slice = 0;

        for x in &v {
            if *x > max_in_aggregated_slice {
                if count > 0 {
                    chunks.push(count);
                }
                count = 1;
                max_in_aggregated_slice = *x;
            } else {
                count += 1;
            }
        }

        chunks.push(count);

        let mut is_aggregate_size_possible = vec![false; 2 * n + 1 + 1];
        is_aggregate_size_possible[0] = true;
        for chunk_size in &chunks {
            for aggregate_size in (0..(2 * n + 1)).rev() {
                if is_aggregate_size_possible[aggregate_size] {
                    is_aggregate_size_possible[aggregate_size + *chunk_size] = true;
                }
            }
        }

        if is_aggregate_size_possible[n] {
            writeln!(output, "YES").unwrap();
        } else {
            writeln!(output, "NO").unwrap();
        }
    }
}


You have a sequence of $$$n$$$ colored blocks. The color of the $$$i$$$-th block is $$$c_i$$$, an integer between $$$1$$$ and $$$n$$$.You will place the blocks down in sequence on an infinite coordinate grid in the following way.   Initially, you place block $$$1$$$ at $$$(0, 0)$$$.  For $$$2 \le i \le n$$$, if the $$$(i - 1)$$$-th block is placed at position $$$(x, y)$$$, then the $$$i$$$-th block can be placed at one of positions $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ (but not at position $$$(x, y - 1)$$$), as long no previous block was placed at that position. A tower is formed by $$$s$$$ blocks such that they are placed at positions $$$(x, y), (x, y + 1), \ldots, (x, y + s - 1)$$$ for some position $$$(x, y)$$$ and integer $$$s$$$. The size of the tower is $$$s$$$, the number of blocks in it. A tower of color $$$r$$$ is a tower such that all blocks in it have the color $$$r$$$.For each color $$$r$$$ from $$$1$$$ to $$$n$$$, solve the following problem independently:   Find the maximum size of a tower of color $$$r$$$ that you can form by placing down the blocks according to the rules.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int d;
    scanf("%d", &d);
    int arr[d];
    for (int i = 0; i < d; i++) {
      scanf("%d", &arr[i]);
    }
    int finalans[d + 1];
    for (int i = 0; i < d + 1; i++) {
      finalans[i] = 0;
    }
    int index[d + 1];
    for (int i = 0; i < d + 1; i++) {
      index[i] = 0;
    }

    for (int i = 0; i < d; i++) {
      if (index[arr[i]] == 0) {
        index[arr[i]] = i + 1;
        finalans[arr[i]] = 1;
      } else if (((i + 1) - index[arr[i]]) % 2 == 1) {
        finalans[arr[i]]++;
        index[arr[i]] = i + 1;
      }
    }
    for (int i = 1; i < d + 1; i++) {
      printf("%d ", finalans[i]);
    }
    printf("\n");
  }
}

fn solution() {
    let lines = std::io::stdin().lines().skip(2).step_by(2);

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

        let n = c.len();

        let mut res = vec![0; n];
        let mut pos = vec![0_usize; n];

        for (i, n) in c.iter().enumerate() {
            res[n - 1] += if res[n - 1] == 0 || (i - pos[n - 1]) % 2 == 0 {
                pos[n - 1] = i + 1;
                1
            } else {
                0
            }
        }

        for i in res {
            print!("{i} ")
        }

        println!()
    }
}


Score : <var>400</var> points

Problem Statement

Given is a positive integer <var>N</var>. Consider repeatedly applying the operation below on <var>N</var>:

First, choose a positive integer <var>z</var> satisfying all of the conditions below:

<var>z</var> can be represented as <var>z=p^e</var>, where <var>p</var> is a prime number and <var>e</var> is a positive integer;

<var>z</var> divides <var>N</var>;

<var>z</var> is different from all integers chosen in previous operations.

Then, replace <var>N</var> with <var>N/z</var>.

Find the maximum number of times the operation can be applied.

Constraints

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the maximum number of times the operation can be applied.

Sample Input 1

24

Sample Output 1

3

We can apply the operation three times by, for example, making the following choices:

Choose <var>z=2 (=2^1)</var>. (Now we have <var>N=12</var>.)

Choose <var>z=3 (=3^1)</var>. (Now we have <var>N=4</var>.)

Choose <var>z=4 (=2^2)</var>. (Now we have <var>N=1</var>.)

Sample Input 2

1

Sample Output 2

0

We cannot apply the operation at all.

Sample Input 3

64

Sample Output 3

3

We can apply the operation three times by, for example, making the following choices:

Choose <var>z=2 (=2^1)</var>. (Now we have <var>N=32</var>.)

Choose <var>z=4 (=2^2)</var>. (Now we have <var>N=8</var>.)

Choose <var>z=8 (=2^3)</var>. (Now we have <var>N=1</var>.)

Sample Input 4

1000000007

Sample Output 4

1

We can apply the operation once by, for example, making the following choice:

<var>z=1000000007 (=1000000007^1)</var>. (Now we have <var>N=1</var>.)

Sample Input 5

997764507000

Sample Output 5

7

int solution() {
  long long int n = 0;
  int counter = 0;
  int tmp_counter = 0;

  scanf("%lld", &n);

  for (long long int i = 2; n != 1;) {
    tmp_counter = 0;

    if (i > pow(n, 0.5)) {
      counter += 1;
      break;
    }

    while ((n % i) == 0) {
      n = n / i;
      tmp_counter++;
    }

    for (int i = 1; tmp_counter >= i; i++) {
      counter++;
      tmp_counter = tmp_counter - i;
    }

    if (i == 2) {
      i++;
    } else {
      i += 2;
    }
  }

  printf("%d", counter);

  return 0;
}

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    let mut n = is.trim().parse::<usize>().unwrap();
    let mut map = HashMap::new();

    let mut i = 2;
    while i * i <= n {
        while n % i == 0 {
            *map.entry(i).or_insert(0) += 1;
            n /= i;
        }

        i += 1;
    }

    if n != 1 {
        *map.entry(n).or_insert(0) += 1;
    }

    let mut ans = 0;
    for (_, v) in map {
        let mut i = 1;
        let mut v = v;
        while v >= i {
            v -= i;
            i += 1;
            ans += 1;
        }
    }

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


There is a toy building consisting of $$$n$$$ towers. Each tower consists of several cubes standing on each other. The $$$i$$$-th tower consists of $$$h_i$$$ cubes, so it has height $$$h_i$$$.Let's define operation slice on some height $$$H$$$ as following: for each tower $$$i$$$, if its height is greater than $$$H$$$, then remove some top cubes to make tower's height equal to $$$H$$$. Cost of one "slice" equals to the total number of removed cubes from all towers.Let's name slice as good one if its cost is lower or equal to $$$k$$$ ($$$k \ge n$$$).  Calculate the minimum number of good slices you have to do to make all towers have the same height. Of course, it is always possible to make it so.

int solution(void) {

  long long int n;
  long long int k;
  long long int min = 200001;
  long long int max = 0;
  long long int aux;
  long long int aux2;
  long long int total = 0;
  long long int *v;

  scanf("%lld %lld", &n, &k);

  v = malloc(sizeof(long long int) * 200001);

  for (long long int j = 0; j <= 200001; j++) {
    v[j] = 0;
  }

  for (long long int i = 0; i < n; i++) {
    scanf("%lld", &aux);
    v[aux]++;
    if (aux < min) {
      min = aux;
    }
    if (aux > max) {
      max = aux;
    }
  }

  if (min == max) {
    printf("0\n");
    return 0;
  }

  while (min != max) {

    aux2 = 0;
    while (aux2 < k) {
      aux2 += v[max];
      if (aux2 <= k) {
        v[max - 1] += v[max];
        max--;
        if (max == min) {
          break;
        }
      }
    }

    total++;
  }

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

  return 0;
}

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

    let n = get!();
    let k = get!();
    let mut hs = vec![];
    for _ in 0..n {
        let h = get!();
        hs.push(h);
    }
    hs.sort();
    let hmin = hs[0];
    hs.reverse();
    let mut ans = 0;
    let mut hi = hs[0];
    let mut e = 0;
    let mut rem = 0;
    while hi > hmin {
        while hs[e] == hi {
            e += 1;
        }
        let df = hi - hs[e];
        for _ in 0..df {
            if rem + e as i64 > k {
                ans += 1;
                rem = 0;
            }
            rem += e as i64;
        }
        hi = hs[e];
    }
    if rem > 0 {
        ans += 1;
    }

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


X Cubic

Write a program which calculates the cube of a given integer <var>x</var>.

Input

An integer <var>x</var> is given in a line.

Output

Print the cube of <var>x</var> in a line.

Constraints

 1 ≤ <var>x</var> ≤ 100

Sample Input 1

2

Sample Output 1

8

Sample Input 2

3

Sample Output 2

27

int solution() {
  int x = 0;

  scanf("%d", &x);
  if (x > 0 && x < 101) {
    x = x * x * x;
    printf("%d\n", x);
  }

  return 0;
}

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

    let _ = stdin.read_line(&mut buf);
    let x: i64 = i64::from_str(buf.trim()).unwrap();

    println!("{}", x.pow(3));
}


Score : <var>300</var> points

Problem Statement

We have two permutations <var>P</var> and <var>Q</var> of size <var>N</var> (that is, <var>P</var> and <var>Q</var> are both rearrangements of <var>(1,~2,~...,~N)</var>).

There are <var>N!</var> possible permutations of size <var>N</var>. Among them, let <var>P</var> and <var>Q</var> be the <var>a</var>-th and <var>b</var>-th lexicographically smallest permutations, respectively. Find <var>|a - b|</var>.

Notes

For two sequences <var>X</var> and <var>Y</var>, <var>X</var> is said to be lexicographically smaller than <var>Y</var> if and only if there exists an integer <var>k</var> such that <var>X_i = Y_i~(1 \leq i < k)</var> and <var>X_k < Y_k</var>.

Constraints

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

<var>P</var> and <var>Q</var> are permutations of size <var>N</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>P_1</var> <var>P_2</var> <var>...</var> <var>P_N</var>
<var>Q_1</var> <var>Q_2</var> <var>...</var> <var>Q_N</var>

Output

Print <var>|a - b|</var>.

Sample Input 1

3
1 3 2
3 1 2

Sample Output 1

3

There are <var>6</var> permutations of size <var>3</var>: <var>(1,~2,~3)</var>, <var>(1,~3,~2)</var>, <var>(2,~1,~3)</var>, <var>(2,~3,~1)</var>, <var>(3,~1,~2)</var>, and <var>(3,~2,~1)</var>. Among them, <var>(1,~3,~2)</var> and <var>(3,~1,~2)</var> come <var>2</var>-nd and <var>5</var>-th in lexicographical order, so the answer is <var>|2 - 5| = 3</var>.

Sample Input 2

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

Sample Output 2

17517

Sample Input 3

3
1 2 3
1 2 3

Sample Output 3

0

int solution(void) {
  int n;
  int p[8 + 3];
  int q[8 + 3];
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &p[i]);
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &q[i]);
  }

  int num_p = 0;
  int num_q = 0;
  for (int i = 0; i < n; i++) {

    int temp = 0;
    for (int j = i + 1; j < n; j++) {
      if (p[i] > p[j]) {
        temp++;
      }
    }
    for (int j = 1; j < n - i; j++) {
      temp *= j;
    }
    num_p += temp;

    temp = 0;
    for (int j = i + 1; j < n; j++) {
      if (q[i] > q[j]) {
        temp++;
      }
    }
    for (int j = 1; j < n - i; j++) {
      temp *= j;
    }
    num_q += temp;
  }

  printf("%d\n", abs(num_p - num_q));

  return 0;
}

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let p: Vec<_> = s
        .by_ref()
        .take(n)
        .map(|a| a.parse::<i32>().unwrap() - 1)
        .collect();
    let q: Vec<_> = s
        .by_ref()
        .take(n)
        .map(|a| a.parse::<i32>().unwrap() - 1)
        .collect();
    let fact = |i: u32| {
        if i == 0 {
            1
        } else {
            (2..i + 1).product::<u32>()
        }
    };
    let f = |a: Vec<i32>| {
        let mut r: u32 = 0;
        let mut b: u32 = (1 << n) - 1;
        for a in a {
            b ^= 1 << a;
            r += (b & ((1 << a) - 1)).count_ones() * fact(b.count_ones());
        }
        r as i32
    };
    println!("{}", (f(p) - f(q)).abs());
}


Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do:   If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$;  if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$;  if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.

int solution() {
  long long int t;
  long long int k;
  long long int n;
  long long int a;
  long long int b;
  long long int m;
  long long int i;
  long long int x;
  long long int low;
  long long int high;
  long long int mid;
  long long int l;
  scanf("%lld", &t);
  for (m = 1; m <= t; m++) {
    scanf("%lld %lld %lld %lld", &k, &n, &a, &b);
    l = 0;
    if (k - n * b <= 0) {
      printf("-1\n");
      l++;
    } else {
      if (k - n * a > 0) {
        printf("%lld\n", n);
        l++;
      } else {
        x = k - n * a;
        low = 1;
        high = n;
        while (low <= high) {
          mid = (high + low) / 2;
          if (x + mid * (a - b) > 0) {
            if (x + (mid - 1) * (a - b) > 0) {
              high = mid - 1;
            } else {
              printf("%lld\n", n - mid);
              l++;
              break;
            }
          }
          if (x + mid * (a - b) == 0) {
            printf("%lld\n", n - mid - 1);
            l++;
            break;
          }
          if (x + mid * (a - b) < 0) {
            low = mid + 1;
          }
        }
      }
    }
    if (l == 0) {
      printf("0\n");
    }
  }
  return 0;
}

fn solution() -> io::Result<()> {
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input)?;

    let q: u32 = input.trim().parse().expect("read error");

    for _ in 1..q + 1 {
        let mut input = String::new();
        stdin.read_line(&mut input)?;
        let mut iter = input
            .split_whitespace()
            .map(|x| x.trim().parse::<u64>().expect("parse error"));
        let k = iter.next().unwrap();
        let n = iter.next().unwrap();
        let a = iter.next().unwrap();
        let b = iter.next().unwrap();

        if k > b * n {
            let mut inf = 0;
            let mut sup = n + 1;
            while inf < sup {
                let x = (inf + sup) / 2;
                if (a - b) * x < k - b * n {
                    inf = x + 1;
                } else {
                    sup = x;
                }
            }

            println!("{}", sup - 1);
        } else {
            println!("-1");
        }
    }

    Ok(())
}


Score : <var>400</var> points

Problem Statement

Joisino the magical girl has decided to turn every single digit that exists on this world into <var>1</var>.

Rewriting a digit <var>i</var> with <var>j</var> <var>(0≤i,j≤9)</var> costs <var>c_{i,j}</var> MP (Magic Points).

She is now standing before a wall. The wall is divided into <var>HW</var> squares in <var>H</var> rows and <var>W</var> columns, and at least one square contains a digit between <var>0</var> and <var>9</var> (inclusive).

You are given <var>A_{i,j}</var> that describes the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left, as follows:

If <var>A_{i,j}≠-1</var>, the square contains a digit <var>A_{i,j}</var>.

If <var>A_{i,j}=-1</var>, the square does not contain a digit.

Find the minimum total amount of MP required to turn every digit on this wall into <var>1</var> in the end.

Constraints

<var>1≤H,W≤200</var>

<var>1≤c_{i,j}≤10^3</var> <var>(i≠j)</var>

<var>c_{i,j}=0</var> <var>(i=j)</var>

<var>-1≤A_{i,j}≤9</var>

All input values are integers.

There is at least one digit on the wall.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>c_{0,0}</var> <var>...</var> <var>c_{0,9}</var>
<var>:</var>
<var>c_{9,0}</var> <var>...</var> <var>c_{9,9}</var>
<var>A_{1,1}</var> <var>...</var> <var>A_{1,W}</var>
<var>:</var>
<var>A_{H,1}</var> <var>...</var> <var>A_{H,W}</var>

Output

Print the minimum total amount of MP required to turn every digit on the wall into <var>1</var> in the end.

Sample Input 1

2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

Sample Output 1

12

To turn a single <var>8</var> into <var>1</var>, it is optimal to first turn <var>8</var> into <var>4</var>, then turn <var>4</var> into <var>9</var>, and finally turn <var>9</var> into <var>1</var>, costing <var>6</var> MP.

The wall contains two <var>8</var>s, so the minimum total MP required is <var>6×2=12</var>.

Sample Input 2

5 5
0 999 999 999 999 999 999 999 999 999
999 0 999 999 999 999 999 999 999 999
999 999 0 999 999 999 999 999 999 999
999 999 999 0 999 999 999 999 999 999
999 999 999 999 0 999 999 999 999 999
999 999 999 999 999 0 999 999 999 999
999 999 999 999 999 999 0 999 999 999
999 999 999 999 999 999 999 0 999 999
999 999 999 999 999 999 999 999 0 999
999 999 999 999 999 999 999 999 999 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Sample Output 2

0

Note that she may not need to change any digit.

Sample Input 3

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

Sample Output 3

47

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let h: usize = itr.next().unwrap().parse().unwrap();
    let w: usize = itr.next().unwrap().parse().unwrap();
    let mut dp: Vec<Vec<u64>> = (0..10)
        .map(|_| {
            (0..10)
                .map(|_| itr.next().unwrap().parse().unwrap())
                .collect()
        })
        .collect();
    for k in 0..10 {
        for i in 0..10 {
            for j in 0..10 {
                dp[i][j] = std::cmp::min(dp[i][j], dp[i][k] + dp[k][j]);
            }
        }
    }

    let mut ans: u64 = 0;
    for _ in 0..h * w {
        let a: isize = itr.next().unwrap().parse().unwrap();
        if a != -1 {
            ans += dp[a as usize][1];
        }
    }
    println!("{}", ans);
}


One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.

int solution(void) {
  int n = 0;
  int final = 0;
  int PVT_surity[3];

  scanf("%d", &n);
  while (n > 0) {
    for (int i = 0; i < 3; i++) {
      scanf("%d", &PVT_surity[i]);
    }
    if (PVT_surity[0] + PVT_surity[1] + PVT_surity[2] >= 2) {
      final++;
    }
    n--;
  }
  printf("%d", final);
  return 0;
}

fn solution() -> Result<(), Box<dyn std::error::Error>> {
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;

    let amount = input.trim().to_string().parse::<usize>()?;
    let mut result = 0;
    for _ in 0..amount {
        let mut vecs = String::new();
        io::stdin().read_line(&mut vecs)?;
        let mut correct = 0;
        for item in vecs.split_whitespace().map(|x| x.parse::<usize>().unwrap()) {
            if item == 1 {
                correct += 1;
            }
        }
        if correct >= 2 {
            result += 1;
        }
    }
    println!("{}", result);
    Ok(())
}


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

int solution(void) {
  long long prizes[5] = {0};
  long long pi[50];

  int n;
  scanf("%i", &n);

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

  int costs[5];
  for (i = 0; i < 5; i++) {
    scanf("%i", &costs[i]);
  }

  long long ps = 0;
  for (i = 0; i < n; i++) {
    ps += pi[i];

    for (j = 4; j >= 0; j--) {
      prizes[j] += ps / costs[j];
      ps %= costs[j];
    }
  }

  for (i = 0; i < 5; i++) {
    printf("%lld%c", prizes[i], i == 4 ? '\n' : ' ');
  }
  printf("%lld\n", ps);

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let _n = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
    let winnings: Vec<_> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(" ")
        .map(|s| s.parse::<u64>().unwrap())
        .collect();
    let mut costs: Vec<_> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(" ")
        .enumerate()
        .map(|(index, s)| (s.parse::<u64>().unwrap(), index))
        .collect();
    costs.sort_by(|a, b| b.0.cmp(&a.0));
    let mut current = 0;
    let mut solution = vec![0; 5];
    for amount in winnings.into_iter() {
        current += amount;
        for cost in costs.iter() {
            let how_many = current / cost.0;
            current %= cost.0;
            solution[cost.1] += how_many;
        }
    }
    for how_many in solution {
        print!("{} ", how_many);
    }
    println!();
    println!("{}", current);
}


Score : <var>200</var> points

Problem Statement

You are given nonnegative integers <var>a</var> and <var>b</var> (<var>a ≤ b</var>), and a positive integer <var>x</var>.
Among the integers between <var>a</var> and <var>b</var>, inclusive, how many are divisible by <var>x</var>?

Constraints

<var>0 ≤ a ≤ b ≤ 10^{18}</var>

<var>1 ≤ x ≤ 10^{18}</var>

Input

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

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

Output

Print the number of the integers between <var>a</var> and <var>b</var>, inclusive, that are divisible by <var>x</var>.

Sample Input 1

4 8 2

Sample Output 1

3

There are three integers between <var>4</var> and <var>8</var>, inclusive, that are divisible by <var>2</var>: <var>4</var>, <var>6</var> and <var>8</var>.

Sample Input 2

0 5 1

Sample Output 2

6

There are six integers between <var>0</var> and <var>5</var>, inclusive, that are divisible by <var>1</var>: <var>0</var>, <var>1</var>, <var>2</var>, <var>3</var>, <var>4</var> and <var>5</var>.

Sample Input 3

9 9 2

Sample Output 3

0

There are no integer between <var>9</var> and <var>9</var>, inclusive, that is divisible by <var>2</var>.

Sample Input 4

1 1000000000000000000 3

Sample Output 4

333333333333333333

Watch out for integer overflows.

int solution() {
  long long a;
  long long b;
  long long x;
  long long ans1;
  long long ans2;
  scanf("%lld%lld%lld", &a, &b, &x);
  ans1 = (a - 1) / x;
  ans2 = b / x;
  if (b < x) {
    if (a == 0) {
      puts("1");
    } else {
      puts("0");
    }
    return 0;
  }
  if (a == 0 && x != 1) {
    ans2++;
  }
  printf("%lld\n", ans2 - ans1);
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
    println!(
        "{}",
        v[1] / v[2] - v[0] / v[2] + (if v[0].is_multiple_of(v[2]) { 1 } else { 0 })
    );
}


You are given a string $$$s$$$. You have to determine whether it is possible to build the string $$$s$$$ out of strings aa, aaa, bb and/or bbb by concatenating them. You can use the strings aa, aaa, bb and/or bbb any number of times and in any order.For example:  aaaabbb can be built as aa $$$+$$$ aa $$$+$$$ bbb;  bbaaaaabbb can be built as bb $$$+$$$ aaa $$$+$$$ aa $$$+$$$ bbb;  aaaaaa can be built as aa $$$+$$$ aa $$$+$$$ aa;  abab cannot be built from aa, aaa, bb and/or bbb.

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).expect("Failed to read t");
    let mut t: usize = s.trim().parse().expect("t is not a number");
    while t != 0 {
        let mut s = String::new();
        io::stdin().read_line(&mut s).expect("Failed to read s");
        let s = s.trim().as_bytes();

        let l = s.len();
        let mut res = true;
        for i in 0..l {
            if (i == 0 || s[i] != s[i - 1]) && (i == l - 1 || s[i] != s[i + 1]) {
                res = false;
            }
        }
        if res {
            println!("YES")
        } else {
            println!("NO")
        };
        t -= 1;
    }
}