You are given one integer number $$$n$$$. Find three distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$ and $$$a \cdot b \cdot c = n$$$ or say that it is impossible to do it.If there are several answers, you can print any.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; ++i) {
    int n = 0;
    int temp = 0;
    int done = 1;
    scanf("%d", &n);
    for (int j = 2; j < sqrt(n) && done; ++j) {
      if (n % j == 0) {
        temp = n / j;
        for (int k = j; k < sqrt(temp) && done; ++k) {
          if (temp % k == 0 && k != j && temp / k != j) {
            printf("YES\n%d %d %d\n", j, temp / k, k);
            done = 0;
          }
        }
      }
    }
    if (done) {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut queries: i8 = line.trim().parse().unwrap();
    while queries > 0 {
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut number: i32 = line.trim().parse().unwrap();
        let mut first: i32 = 2;
        loop {
            let mut second: i32 = number / first;
            if first >= second {
                println!("NO");
                break;
            }
            if number % first == 0 {
                number = second;
                second = first;
                loop {
                    second += 1;
                    let third: i32 = number / second;
                    if second >= third {
                        println!("NO");
                        break;
                    }
                    if number % second == 0 {
                        println!("YES\n{} {} {}", first, second, third);
                        break;
                    }
                }
                break;
            }
            first += 1;
        }
        queries -= 1;
    }
}


There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.

int solution()

{
  int a = 0;
  int b = 0;
  int c = 0;
  int n;

  scanf("%d", &n);

  int arr[n];
  int i;

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

    if (arr[i] == 1) {
      a++;

    } else if (arr[i] == 2) {
      b++;
    } else {
      c++;
    }
  }

  if (a >= b && a >= c) {
    printf("%d\n", b + c);

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

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

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

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let nums: Vec<&str> = buf.split_whitespace().collect();

    let (mut one, mut two, mut three) = (0, 0, 0);

    for num in nums {
        match num {
            "1" => one += 1,
            "2" => two += 1,
            "3" => three += 1,
            _ => unreachable!(),
        }
    }

    let mut digits = [&one, &two, &three];
    digits.sort_unstable();
    println!("{}", digits[0] + digits[1]);
}


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s$$$.For some non-empty substring$$$^\dagger$$$ $$$t$$$ of string $$$s$$$ containing $$$x$$$ characters 0 and $$$y$$$ characters 1, define its cost as:  $$$x \cdot y$$$, if $$$x > 0$$$ and $$$y > 0$$$;  $$$x^2$$$, if $$$x > 0$$$ and $$$y = 0$$$;  $$$y^2$$$, if $$$x = 0$$$ and $$$y > 0$$$. Given a binary string $$$s$$$ of length $$$n$$$, find the maximum cost across all its non-empty substrings.$$$^\dagger$$$ A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

int solution() {
  int t;
  scanf("%d", &t);
  for (int tt = 0; tt < t; tt++) {
    int n;
    scanf("\n%d\n", &n);
    char arr[n];
    long long int n1 = 0;
    long long int n0 = 0;
    long long int maxx;
    for (int i = 0; i < n; i++) {
      scanf("%c", &arr[i]);
      if (arr[i] == '0') {
        n0++;
      }
      if (arr[i] == '1') {
        n1++;
      }
    }
    if (n0 == 0) {
      maxx = n1 * n1;
      printf("%lld\n", maxx);
      continue;
    }
    if (n1 == 0) {
      maxx = n0 * n0;
      printf("%lld\n", maxx);
      continue;
    }

    maxx = n1 * n0;
    long long int tmp = 0;
    char prev = '!';
    for (int i = 0; i < n; i++) {
      if ((prev == '!') || (prev == arr[i])) {
        tmp++;
      } else {
        tmp = 1;
      }
      prev = arr[i];
      if ((tmp * tmp) > maxx) {
        maxx = tmp * tmp;
      }
    }
    printf("%lld\n", maxx);
  }
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(2)
        .step_by(2)
        .flatten()
        .for_each(|s| {
            let t = s.as_bytes();
            let zeroes = t.iter().fold(
                0usize,
                |acc, &x| if x == b'0' { acc.wrapping_add(1) } else { acc },
            );
            let ones = t.len().wrapping_sub(zeroes);
            let mut ans = 1usize.max(zeroes.wrapping_mul(ones));
            t.windows(2).fold(1usize, |a, c| {
                let b: usize = match c {
                    &[d, e] if d == e => a.wrapping_add(1),
                    _ => 1,
                };
                ans = ans.max(b.wrapping_mul(b));
                b
            });
            writeln!(buf, "{ans}").unwrap_or_default();
        });
}


Slastyona and her loyal dog Pushok are playing a meaningless game that is indeed very interesting.The game consists of multiple rounds. Its rules are very simple: in each round, a natural number k is chosen. Then, the one who says (or barks) it faster than the other wins the round. After that, the winner's score is multiplied by k2, and the loser's score is multiplied by k. In the beginning of the game, both Slastyona and Pushok have scores equal to one.Unfortunately, Slastyona had lost her notepad where the history of all n games was recorded. She managed to recall the final results for each games, though, but all of her memories of them are vague. Help Slastyona verify their correctness, or, to put it another way, for each given pair of scores determine whether it was possible for a game to finish with such result or not.

int solution() {
  int n;
  long long t;
  long long a;
  long long b;
  scanf("%d", &n);
  while (n--) {
    scanf("%lld%lld", &a, &b);
    t = a * b;
    t = round(pow(t, 1.0 / 3));
    if (t * t * t != a * b) {
      printf("No\n");
    } else {
      if (a % t == 0 && b % t == 0) {
        printf("Yes\n");
      } else {
        printf("No\n");
      }
    }
  }

  return 0;
}

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

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

    let n = input.trim().parse::<u32>().unwrap();

    let mut ress = Vec::with_capacity(n as usize);

    for _i in 0..n {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace().map(|x| x.parse::<u32>().unwrap());
        ress.push((it.next().unwrap(), it.next().unwrap()));
    }

    for (a, b) in ress {
        let c: f64 = a as f64 * b as f64;
        let d = c.cbrt();
        if c == d.round().powi(3) && a % d.round() as u32 == 0 && b % d.round() as u32 == 0 {
            println!("yes");
        } else {
            println!("no");
        }
    }
}


Score : <var>100</var> points

Problem Statement

How many ways are there to choose two distinct positive integers totaling <var>N</var>, disregarding the order?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer.

Sample Input 1

4

Sample Output 1

1

There is only one way to choose two distinct integers totaling <var>4</var>: to choose <var>1</var> and <var>3</var>. (Choosing <var>3</var> and <var>1</var> is not considered different from this.)

Sample Input 2

999999

Sample Output 2

499999

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

  int cnt = 0;
  for (int i = 1; i < n - i; i++) {
    cnt++;
  }
  printf("%d", cnt);
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let n: i64 = s.trim().parse().ok().unwrap();
    println!("{}", (n - 1) / 2);
}


One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let n: i32 = s.trim().parse().unwrap();
    if n % 2 == 0 {
        println!("{} {}", 4, n - 4);
    } else {
        println!("{} {}", 9, n - 9);
    }
}


Rectangle

Write a program which calculates the area and perimeter of a given rectangle.

Input

  The length <var>a</var> and breadth <var>b</var> of the rectangle are given in a line separated by a single space.

Output

Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.

Constraints

 1 ≤ <var>a</var>, <var>b</var> ≤ 100

Sample Input 1

3 5

Sample Output 1

15 16

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

    let mut line = String::new();

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

    let n: u32 = vec[0].parse().unwrap_or(0);
    let m: u32 = vec[1].parse().unwrap_or(0);

    println!("{} {}", n * m, 2 * (n + m));
}


Score : <var>100</var> points

Problem Statement

Iroha loves Haiku. Haiku is a short form of Japanese poetry. A Haiku consists of three phrases with <var>5</var>, <var>7</var> and <var>5</var> syllables, in this order.

To create a Haiku, Iroha has come up with three different phrases. These phrases have <var>A</var>, <var>B</var> and <var>C</var> syllables, respectively. Determine whether she can construct a Haiku by using each of the phrases once, in some order.

Constraints

<var>1≦A,B,C≦10</var>

Input

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

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

Output

If it is possible to construct a Haiku by using each of the phrases once, print YES (case-sensitive). Otherwise, print NO.

Sample Input 1

5 5 7

Sample Output 1

YES

Using three phrases of length <var>5</var>, <var>5</var> and <var>7</var>, it is possible to construct a Haiku.

Sample Input 2

7 7 5

Sample Output 2

NO

fn solution() {
    let mut line = String::new();
    drop(std::io::stdin().read_to_string(&mut line));
    let line: Vec<_> = line.split_whitespace().collect();
    let mut line: Vec<_> = line.iter().filter_map(|x| i32::from_str(x).ok()).collect();
    line.sort();
    let line = line;
    print!("{}", if line == [5, 5, 7] { "YES" } else { "NO" });
}


Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,  - 2, 1, 3,  - 4. Suppose the mother suggested subarrays (1,  - 2), (3,  - 4), (1, 3), (1,  - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:   the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,  the second flower adds ( - 2)·1 =  - 2, because he is in one of chosen subarrays,  the third flower adds 1·2 = 2, because he is in two of chosen subarrays,  the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,  the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays. Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.

int solution() {
  int i = 0;
  int j = 0;
  int n = 0;
  int m = 0;
  int l = 0;
  int r = 0;
  int max = 0;
  int beauty = 0;
  int a[150] = {0};
  scanf("%d %d", &n, &m);
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }

  for (i = 0; i < m; i++) {
    scanf("%d %d", &l, &r);
    l--;
    beauty = 0;

    for (j = l; j < r; j++) {
      beauty += a[j];
    }
    if (max + beauty > max) {
      max += beauty;
    }
  }

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

  return 0;
}

fn solution() {
    let mut input_line = String::new();
    stdin().read_line(&mut input_line).unwrap();
    let mut input_iter = input_line
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());

    let flower_count = input_iter.next().unwrap();
    let subarray_count = input_iter.next().unwrap();

    let mut sum_range = [0; 101];
    let mut input_line = String::new();
    stdin().read_line(&mut input_line).unwrap();
    let mut input_iter = input_line
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap());

    for i in 1..(flower_count + 1) {
        sum_range[i] = sum_range[i - 1] + input_iter.next().unwrap();
    }

    let mut result = 0;

    for _ in 1..(subarray_count + 1) {
        let mut input_line = String::new();
        stdin().read_line(&mut input_line).unwrap();
        let mut input_iter = input_line
            .split_whitespace()
            .map(|x| x.parse::<usize>().unwrap());
        let left = input_iter.next().unwrap();
        let right = input_iter.next().unwrap();
        let happiness = sum_range[right] - sum_range[left - 1];
        if happiness > 0 {
            result += happiness;
        }
    }

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


This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury picked an integer $$$x$$$ not less than $$$0$$$ and not greater than $$$2^{14} - 1$$$. You have to guess this integer.To do so, you may ask no more than $$$2$$$ queries. Each query should consist of $$$100$$$ integer numbers $$$a_1$$$, $$$a_2$$$, ..., $$$a_{100}$$$ (each integer should be not less than $$$0$$$ and not greater than $$$2^{14} - 1$$$). In response to your query, the jury will pick one integer $$$i$$$ ($$$1 \le i \le 100$$$) and tell you the value of $$$a_i \oplus x$$$ (the bitwise XOR of $$$a_i$$$ and $$$x$$$). There is an additional constraint on the queries: all $$$200$$$ integers you use in the queries should be distinct.It is guaranteed that the value of $$$x$$$ is fixed beforehand in each test, but the choice of $$$i$$$ in every query may depend on the integers you send.

int solution(void) {
  unsigned int top;
  unsigned int bot;

  printf("? ");
  for (unsigned int x = 1; x <= 100; ++x) {
    printf("%u ", x);
  }
  printf("\n");
  fflush(stdout);

  scanf("%u", &top);

  printf("? ");
  for (unsigned int x = 1; x <= 100; ++x) {
    printf("%u ", x << 7);
  }
  printf("\n");
  fflush(stdout);

  scanf("%u", &bot);

  printf("! %u", (top & 0b11111110000000) | (bot & 0b00000001111111));

  return 0;
}

fn solution() {
    print!("?");
    for i in 1..101 {
        print!(" {}", i);
    }
    println!();
    print!("?");
    for i in 1..101 {
        print!(" {}", i << 7);
    }
    println!();
    stdout().flush().unwrap();

    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let rear = buf.trim().parse::<i32>().unwrap();

    buf.clear();
    std::io::stdin().read_line(&mut buf).unwrap();
    let front = buf.trim().parse::<i32>().unwrap();

    println!("! {}", (rear & !((1 << 7) - 1)) | (front & ((1 << 7) - 1)));
}


Score: <var>400</var> points

Problem Statement

In Takahashi Kingdom, there is a east-west railroad and <var>N</var> cities along it, numbered <var>1</var>, <var>2</var>, <var>3</var>, ..., <var>N</var> from west to east.
A company called AtCoder Express possesses <var>M</var> trains, and the train <var>i</var> runs from City <var>L_i</var> to City <var>R_i</var> (it is possible that <var>L_i = R_i</var>).
Takahashi the king is interested in the following <var>Q</var> matters:

The number of the trains that runs strictly within the section from City <var>p_i</var> to City <var>q_i</var>, that is, the number of trains <var>j</var> such that <var>p_i \leq L_j</var> and <var>R_j \leq q_i</var>.

Although he is genius, this is too much data to process by himself. Find the answer for each of these <var>Q</var> queries to help him.

Constraints

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

<var>M</var> is an integer between <var>1</var> and <var>200 \ 000</var> (inclusive).

<var>Q</var> is an integer between <var>1</var> and <var>100 \ 000</var> (inclusive).

<var>1 \leq L_i \leq R_i \leq N</var> <var>(1 \leq i \leq M)</var>

<var>1 \leq p_i \leq q_i \leq N</var> <var>(1 \leq i \leq Q)</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>Q</var>
<var>L_1</var> <var>R_1</var>
<var>L_2</var> <var>R_2</var>
<var>:</var>
<var>L_M</var> <var>R_M</var>
<var>p_1</var> <var>q_1</var>
<var>p_2</var> <var>q_2</var>
<var>:</var>
<var>p_Q</var> <var>q_Q</var>

Output

Print <var>Q</var> lines. The <var>i</var>-th line should contain the number of the trains that runs strictly within the section from City <var>p_i</var> to City <var>q_i</var>.

Sample Input 1

2 3 1
1 1
1 2
2 2
1 2

Sample Output 1

3

As all the trains runs within the section from City <var>1</var> to City <var>2</var>, the answer to the only query is <var>3</var>.

Sample Input 2

10 3 2
1 5
2 8
7 10
1 7
3 10

Sample Output 2

1
1

The first query is on the section from City <var>1</var> to <var>7</var>. There is only one train that runs strictly within that section: Train <var>1</var>.
The second query is on the section from City <var>3</var> to <var>10</var>. There is only one train that runs strictly within that section: Train <var>3</var>.

Sample Input 3

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

Sample Output 3

7
9
10
6
8
9
6
7
8
10

int solution(void) {

  long n;
  long m;
  long q;
  scanf("%ld %ld %ld", &n, &m, &q);
  long l[m];
  long r[m];
  for (long i = 0; i < m; i++) {
    scanf("%ld %ld", &l[i], &r[i]);
  }
  long sp[q];
  long sq[q];
  for (long i = 0; i < q; i++) {
    scanf("%ld %ld", &sp[i], &sq[i]);
  }
  long train[n + 1][n + 1];
  for (long i = 0; i <= n; i++) {
    for (long j = 0; j <= n; j++) {
      train[i][j] = 0;
    }
  }
  for (long i = 0; i < m; i++) {
    train[l[i]][r[i]]++;
  }
  long sum[n + 1][n + 1];
  for (long i = 1; i <= n; i++) {
    sum[i][i - 1] = 0;
    for (long j = i; j <= n; j++) {
      sum[i][j] = sum[i][j - 1] + train[i][j];
    }
  }
  long ans;
  for (long i = 0; i < q; i++) {
    ans = 0;
    for (int j = sp[i]; j <= sq[i]; j++) {
      ans += sum[j][sq[i]] - sum[j][j - 1];
    }
    printf("%ld\n", ans);
  }

  return 0;
}

fn solution() {
    input! {
        N: usize,
        M: usize,
        Q: usize,
        train: [(usize, usize); M],
        part: [(usize, usize); Q],
    }

    let mut count_map = vec![vec![0; N + 1]; N + 1];
    for t in train.iter() {
        count_map[t.0][t.1] += 1;
    }

    let mut cml_sum = vec![vec![0; N + 1]; N + 1];
    let mut colum_sum = vec![0; N + 1];
    for i in 0..N + 1 {
        colum_sum[0] += count_map[i][0];
        cml_sum[i][0] = colum_sum[0];
        for j in 1..N + 1 {
            colum_sum[j] += count_map[i][j];
            cml_sum[i][j] = cml_sum[i][j - 1] + colum_sum[j];
        }
    }

    for q in part.iter() {
        let count = cml_sum[q.0 - 1][q.0 - 1] + cml_sum[q.1][q.1]
            - cml_sum[q.0 - 1][q.1]
            - cml_sum[q.1][q.0 - 1];
        println!("{}", count);
    }
}


void solution(int *arr, int size) {
  for (int i = 1; i < size; i++) {
    int j = i - 1;
    int key = arr[i];

    while (j >= 0 && key < arr[j]) {
      arr[j + 1] = arr[j];
      j = j - 1;
    }

    arr[j + 1] = key;
  }
}

fn solution<T: Ord + Copy>(arr: &mut [T]) {
    for i in 1..arr.len() {
        let mut j = i;
        let cur = arr[i];

        while j > 0 && cur < arr[j - 1] {
            arr[j] = arr[j - 1];
            j -= 1;
        }

        arr[j] = cur;
    }
}


双六 (Sugoroku)

 問題文

JOI 君はおじさんの家で双六を見つけた．双六は直線状に並んだ <var>N+2</var> 個のマスからなり，<var>1</var> 番目のマスはスタート，<var>N+2</var> 番目のマスはゴールである．その他の各マスには <var>0</var> または <var>1</var> が書かれていて，各 <var>i</var> (<var>1≦i≦N</var>) について，<var>i+1</var> 番目のマスに書かれた数字は <var>A_i</var> である．

双六では，最初にスタートのマスにコマを置き，サイコロを振って，出た目の数だけコマを進めることを繰り返す．ただし，<var>1</var> の書かれたマスに止まった場合は，ゲームオーバーである．ゲームオーバーにならずにゴールのマスに止まるか，ゴールのマスを通り過ぎたら，ゲームクリアである．

JOI 君は双六を遊ぶためのサイコロをおもちゃ屋さんに買いに行くことにした．おもちゃ屋さんには <var>N+1</var> 個のサイコロが売っている．<var>j</var> 番目 (<var>1≦j≦N+1</var>) のサイコロは <var>j</var> 個の面を持ち，<var>1,2,...,j</var> が <var>1</var> つずつ書かれている．

JOI 君はゲームクリアできるようなサイコロのうち，最も面の数が少ないサイコロを <var>1</var> 個買うことにした．JOI 君はどのサイコロを買えばよいだろうか．

 制約

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

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

入力・出力

入力

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

<var>N</var>

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

出力

JOI 君が購入すべきサイコロの面の数を答えよ．

入出力例

入力例 1

5
0 1 0 0 0

出力例 1

2

双六は <var>7</var> マスからなり，<var>3</var> マス目のみに <var>1</var> が書かれている．面の数が <var>2</var> 個のサイコロを使った場合，例えば出た目が <var>1,2,1,1,1</var> となったときにゲームクリアすることができる．これが最小なので <var>2</var> を出力する．

入力例 2

5
1 1 1 1 1

出力例 2

6

双六は <var>7</var> マスからなり，スタートとゴール以外のマス全てに <var>1</var> が書かれている．このとき，面の数が <var>6</var> 個のサイコロが必要である．これが最小なので <var>6</var> を出力する．

入力例 3

7
0 0 1 0 1 1 0

出力例 3

3

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

int solution() {
  int N;
  int L[105];
  int point = 0;
  int max = 1;
  int tag = 0;
  int n = 1;
  scanf("%d", &N);
  for (int i = 0; i < N; ++i) {
    scanf("%d", L + i);
  }
  while (point < N) {
    if (tag == 0 && L[point]) {
      tag = 1;
    }
    if (tag && !L[point]) {
      tag = 0;
      if (n > max) {
        max = n;
      }
      n = 1;
    }
    if (tag && point == N - 1) {
      ++n;
      if (n > max) {
        max = n;
      }
    }
    if (tag) {
      ++n;
    }
    ++point;
  }

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

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

    iter.next();
    println!(
        "{}",
        iter.next()
            .unwrap()
            .unwrap()
            .split(' ')
            .scan(0, |acc, s| {
                *acc = if s == "1" { *acc + 1 } else { 0 };
                Some(*acc)
            })
            .max()
            .unwrap()
            + 1
    );
}


Areas on the Cross-Section Diagram

  Your task is to simulate a flood damage.

  For a given cross-section diagram, reports areas of flooded sections.

  Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides.
For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.

Input

  A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".

output

  Report the areas of floods in the following format:

$A$

$k$ $L_1$ $L_2$ ... $L_k$

  In the first line, print the total area $A$ of created floods.

  In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.

Constraints

$1 \leq$ length of the string $\leq 20,000$

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\

Sample Output 2

35
5 4 2 1 19 9

int solution() {
  int c;
  int x;
  int i;
  int sum = 0;
  int putop = 0;
  int xtop = 0;
  int xstack[20000];
  int lefts[20000];
  int vols[20000];

  for (x = 0; (c = getchar()) != '\n'; x++) {
    if (c == '\\') {
      xstack[xtop++] = x;
    } else if (c == '/') {
      if (xtop == 0) {
        continue;
      }
      int last_x = xstack[--xtop];
      int new_vol = x - last_x;
      while (putop > 0 && last_x < lefts[putop - 1]) {
        new_vol += vols[--putop];
      }
      lefts[putop] = x;
      vols[putop] = new_vol;
      putop++;
    }
  }
  for (i = 0; i < putop; i++) {
    sum += vols[i];
  }

  printf("%d\n%d", sum, putop);

  for (i = 0; i < putop; i++) {
    printf(" %d", vols[i]);
  }
  puts("");
}

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

    let C = buf_it.next().unwrap().chars().collect::<Vec<_>>();
    let N = C.len();

    let mut H = vec![0isize];
    for &c in &C {
        let h = H[H.len() - 1];
        match c {
            '/' => {
                H.push(h + 1);
            }
            '_' => {
                H.push(h);
            }
            '\\' => {
                H.push(h - 1);
            }
            _ => {}
        }
    }
    let mut L = H.clone();
    let mut R = H.clone();
    for i in 0..N {
        L[i + 1] = max(L[i], L[i + 1]);
        R[N - i - 1] = max(R[N - i - 1], R[N - i]);
    }
    let W = L
        .iter()
        .zip(R.iter())
        .map(|(a, b)| *min(a, b))
        .collect::<Vec<_>>();
    let mut ans = Vec::new();
    let mut tmp = 0;
    for i in 0..N + 1 {
        let h = H[i];
        let w = W[i];
        if w - h <= 0 && tmp > 0 {
            ans.push(tmp);
            tmp = 0;
        } else if w - h > 0 {
            tmp += w - h;
        }
    }
    println!("{}", ans.iter().sum::<isize>());
    if ans.is_empty() {
        println!("0");
    } else {
        println!(
            "{} {}",
            ans.len(),
            ans.iter()
                .map(|a| format!("{}", a))
                .collect::<Vec<_>>()
                .join(" ")
        );
    }
}


There are $$$n$$$ pillars aligned in a row and numbered from $$$1$$$ to $$$n$$$.Initially each pillar contains exactly one disk. The $$$i$$$-th pillar contains a disk having radius $$$a_i$$$.You can move these disks from one pillar to another. You can take a disk from pillar $$$i$$$ and place it on top of pillar $$$j$$$ if all these conditions are met:  there is no other pillar between pillars $$$i$$$ and $$$j$$$. Formally, it means that $$$|i - j| = 1$$$;  pillar $$$i$$$ contains exactly one disk;  either pillar $$$j$$$ contains no disks, or the topmost disk on pillar $$$j$$$ has radius strictly greater than the radius of the disk you move. When you place a disk on a pillar that already has some disks on it, you put the new disk on top of previously placed disks, so the new disk will be used to check the third condition if you try to place another disk on the same pillar.You may take any disk and place it on other pillar any number of times, provided that every time you do it, all three aforementioned conditions are met. Now you wonder, is it possible to place all $$$n$$$ disks on the same pillar simultaneously?

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

fn solution() {
    let mut s: String = String::new();
    s.clear();
    let _: i32 = {
        io::stdin().read_line(&mut s).ok();
        s.trim().parse().unwrap()
    };
    s.clear();
    let a: Vec<i32> = {
        io::stdin().read_line(&mut s).ok();
        s.split_whitespace().map(|s| s.parse().unwrap()).collect()
    };
    let mut last = 0i32;
    let mut up = true;
    let mut good_flag = true;
    for el in a {
        if up {
            if el < last {
                up = false;
            }
        } else {
            if el > last {
                good_flag = false;
                break;
            }
        }
        last = el;
    }

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


You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().

int solution() {
  char a[1000002];
  char b[1000002];
  fgets(a, 1000002, stdin);
  fgets(b, 1000002, stdin);
  char *aa = a;
  char *bb = b;
  while (*aa == '0') {
    ++aa;
  }
  while (*bb == '0') {
    ++bb;
  }
  int la = strlen(aa);
  int lb = strlen(bb);
  if (la != lb) {
    printf("%s\n", la > lb ? ">" : "<");
  } else {
    int cmp = memcmp(aa, bb, la);
    printf("%s\n", cmp > 0 ? ">" : (cmp < 0 ? "<" : "="));
  }
}

fn solution() {
    let mut a = String::with_capacity(1000_002);
    let mut b = String::with_capacity(1000_002);
    stdin().read_line(&mut a).unwrap();
    stdin().read_line(&mut b).unwrap();
    let mut ar1: [u8; 1000_001] = [0; 1000_001];
    let mut ar2: [u8; 1000_001] = [0; 1000_001];
    let (mut i, mut j) = (0, 0);
    for c in a.trim_end().chars() {
        if i == 0 && c == '0' {
            continue;
        }
        ar1[i] = c as u8;
        i += 1;
    }
    for c in b.trim_end().chars() {
        if j == 0 && c == '0' {
            continue;
        }
        ar2[j] = c as u8;
        j += 1;
    }
    if i > j {
        println!(">");
        return;
    } else if i < j {
        println!("<");
        return;
    }
    for k in 0..i {
        if ar1[k] > ar2[k] {
            println!(">");
            return;
        } else if ar1[k] < ar2[k] {
            println!("<");
            return;
        }
    }
    println!("=");
}


Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.It is known that in a match between two players, the one whose skill is greater will win. The skill of the $$$i$$$-th player is equal to $$$s_i$$$ and all skill levels are pairwise different (i. e. there are no two identical values in the array $$$s$$$).The tournament is called fair if the two players with the highest skills meet in the finals.Determine whether the given tournament is fair.

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(1) {
        if let [mut s1, mut s2, mut s3, mut s4] = l
            .unwrap()
            .split_whitespace()
            .map(|w| w.parse::<u32>().unwrap())
            .collect::<Vec<_>>()[..]
        {
            if s1 > s2 {
                swap(&mut s1, &mut s2)
            };
            if s3 > s4 {
                swap(&mut s3, &mut s4)
            };
            writeln!(o, "{}", if s2 < s3 || s4 < s1 { "NO" } else { "YES" }).ok();
        }
    }
}


Shopping

You are now in a bookshop with your friend Alice to buy a book, "The Winning Strategy for the Programming Koshien Contest,” just released today. As you definitely want to buy it, you are planning to borrow some money from Alice in case the amount you have falls short of the price. If the amount you receive from Alice still fails to meet the price, you have to abandon buying the book this time.

  Write a program to calculate the minimum amount of money you need to borrow from Alice given the following three items of data: the money you and Alice have now and the price of the book.

Input

  The input is given in the following format.

<var>m</var> <var>f</var> <var>b</var>

A line containing the three amounts of money is given: the amount you have with you now <var>m</var> (0 ≤ <var>m</var> ≤ 10000), the money Alice has now <var>f</var> (0 ≤ <var>f</var> ≤ 10000) and the price of the book <var>b</var> (100 ≤ <var>b</var> ≤ 20000).

Output

Output a line suggesting the minimum amount of money you need to borrow from Alice. Output "NA" if all the money Alice has with him now is not a sufficient amount for you to buy the book.

Sample Input 1

1000 3000 3000

Sample Output 1

2000

Sample Input 2

5000 3000 4500

Sample Output 2

0

Sample Input 3

500 1000 2000

Sample Output 3

NA

int solution() {

  int money;
  int friend;
  int price;

  scanf("%d %d %d", &money, &friend, &price);

  if (money - price >= 0) {
    printf("0\n");
  }
  if ((money - price) < 0 && friend >= -1 * (money - price)) {
    printf("%d\n", -1 * (money - price));
  }
  if (money - price < 0 && friend < -1 * (money - price)) {
    printf("NA\n");
  }

  return 0;
}

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

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

    if a >= c {
        println!("{}", 0);
    } else if a + b < c {
        println!("NA");
    } else {
        println!("{}", c - a);
    }
}


Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners.The valid sizes of T-shirts are either "M" or from $$$0$$$ to $$$3$$$ "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not.There are $$$n$$$ winners to the cup for both the previous year and the current year. Ksenia has a list with the T-shirt sizes printed for the last year cup and is yet to send the new list to the printing office. Organizers want to distribute the prizes as soon as possible, so now Ksenia is required not to write the whole list from the scratch but just make some changes to the list of the previous year. In one second she can choose arbitrary position in any word and replace its character with some uppercase Latin letter. Ksenia can't remove or add letters in any of the words.What is the minimal number of seconds Ksenia is required to spend to change the last year list to the current one?The lists are unordered. That means, two lists are considered equal if and only if the number of occurrences of any string is the same in both lists.

int solution() {
  int n;
  scanf("%d", &n);
  char a[n][100];
  char b[n][100];
  int strlen1[n];
  int strlen2[n];
  for (int i = 0; i < n; i++) {
    scanf("%s", a[i]);
    strlen1[i] = strlen(a[i]);
  }

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

  int f = 0;
  int visited[100];
  for (int i = 0; i < 100; i++) {
    visited[i] = 0;
  }

  int count = 0;

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if (strlen1[i] == strlen2[j] && visited[j] != 1) {
        if (strcmp(a[i], b[j]) == 0) {
          visited[j] = 1;
          count++;
          break;
        }
      }
    }
  }

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

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!();
    use std::collections::HashMap;
    let mut xs = HashMap::new();
    for _ in 0..n {
        let s = get!(String);
        let c = match xs.get(&s) {
            Some(&c) => c + 1,
            None => 1,
        };
        xs.insert(s, c);
    }
    let mut ans = 0;
    for _ in 0..n {
        let s = get!(String);
        let &c = xs.get(&s).unwrap_or(&0);
        if c == 0 {
            ans += 1;
        } else {
            xs.insert(s, c - 1);
        }
    }
    println!("{}", ans);
}


Score : <var>500</var> points

Problem Statement

You are given a sequence <var>(P_1,P_2,...,P_N)</var> which is a permutation of the integers from <var>1</var> through <var>N</var>.
You would like to sort this sequence in ascending order by repeating the following operation:

Choose an element in the sequence and move it to the beginning or the end of the sequence.

Find the minimum number of operations required.
It can be proved that it is actually possible to sort the sequence using this operation.

Constraints

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

<var>(P_1,P_2,...,P_N)</var> is a permutation of  <var>(1,2,...,N)</var>.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>P_1</var>
<var>:</var>
<var>P_N</var>

Output

Print the minimum number of operations required.

Sample Input 1

4
1
3
2
4

Sample Output 1

2

For example, the sequence can be sorted in ascending order as follows:

Move <var>2</var> to the beginning. The sequence is now <var>(2,1,3,4)</var>.

Move <var>1</var> to the beginning. The sequence is now <var>(1,2,3,4)</var>.

Sample Input 2

6
3
2
5
1
4
6

Sample Output 2

4

Sample Input 3

8
6
3
1
2
7
4
8
5

Sample Output 3

5

int solution(void) {

  int n;
  scanf("%d", &n);
  int p[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &p[i]);
  }
  int q[n + 1];
  for (int i = 0; i < n; i++) {
    q[p[i]] = i;
  }
  int count = 1;
  int max = 1;
  for (int i = 2; i <= n; i++) {
    if (q[i] > q[i - 1]) {
      count++;
    } else {
      count = 1;
    }
    if (count > max) {
      max = count;
    }
  }
  printf("%d\n", n - max);

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let a = (0..n)
        .map(|_| it.next().unwrap().parse::<usize>().unwrap())
        .collect::<Vec<_>>();
    let mut b = vec![0; n];
    for i in 0..n {
        b[a[i] - 1] = i;
    }
    let mut res = 0;
    let mut cnt = 0;
    let mut pos = 0;
    for &t in &b {
        cnt = if t >= pos { cnt + 1 } else { 1 };
        res = std::cmp::max(res, cnt);
        pos = t;
    }
    println!("{}", n - res);
}


Score : <var>300</var> points

Problem Statement

Snuke loves "paper cutting": he cuts out characters from a newspaper headline and rearranges them to form another string.

He will receive a headline which contains one of the strings <var>S_1,...,S_n</var> tomorrow.
He is excited and already thinking of what string he will create.
Since he does not know the string on the headline yet, he is interested in strings that can be created regardless of which string the headline contains.

Find the longest string that can be created regardless of which string among <var>S_1,...,S_n</var> the headline contains.
If there are multiple such strings, find the lexicographically smallest one among them.

Constraints

<var>1 \leq n \leq 50</var>

<var>1 \leq |S_i| \leq 50</var> for every <var>i = 1, ..., n</var>.

<var>S_i</var> consists of lowercase English letters (a - z) for every <var>i = 1, ..., n</var>.

Input

Input is given from Standard Input in the following format:

<var>n</var>
<var>S_1</var>
<var>...</var>
<var>S_n</var>

Output

Print the lexicographically smallest string among the longest strings that satisfy the condition.
If the answer is an empty string, print an empty line.

Sample Input 1

3
cbaa
daacc
acacac

Sample Output 1

aac

The strings that can be created from each of cbaa, daacc and acacac, are aa, aac, aca, caa and so forth.
Among them, aac, aca and caa are the longest, and the lexicographically smallest of these three is aac.

Sample Input 2

3
a
aa
b

Sample Output 2

The answer is an empty string.

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

    let mut h: HashMap<char, usize> = HashMap::new();
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let c: Vec<char> = s.trim().chars().collect();
    for e in &c {
        let x = match h.get(e) {
            Some(x) => *x,
            None => 0,
        };
        h.insert(*e, x + 1);
    }

    for _ in 1..n {
        let mut m: HashMap<char, usize> = HashMap::new();
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let c: Vec<char> = s.trim().chars().collect();
        for e in &c {
            let x = match m.get(e) {
                Some(x) => *x,
                None => 0,
            };
            m.insert(*e, x + 1);
        }
        for (k, v) in h.iter_mut() {
            let x = match m.get(k) {
                Some(x) => *x,
                None => 0,
            };
            *v = std::cmp::min(x, *v);
        }
    }
    let mut v: Vec<char> = h.keys().copied().collect();
    v.sort();
    for k in &v {
        let x = match h.get(k) {
            Some(x) => *x,
            None => 0,
        };
        print!("{}", std::iter::repeat_n(*k, x).collect::<String>());
    }
    println!();
}


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

int solution(void) {
  int n;
  int maxindex = 0;
  int minindex = 0;
  int swaps = 0;
  scanf("%d", &n);
  int soldiers[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &soldiers[i]);
  }
  int max = 0;
  int min = 101;
  if (n >= 2 && n <= 100) {
    for (int i = 0; i < n; i++) {
      if (soldiers[i] >= 1 && soldiers[i] <= 100) {
        if (soldiers[i] > max) {
          max = soldiers[i];
          maxindex = i;
        }
        if (soldiers[i] <= min) {
          min = soldiers[i];
          minindex = i;
        }
      }
    }
    if (maxindex >= minindex) {
      swaps = (maxindex - 1) + (n - minindex) - 1;
    } else {
      swaps = (maxindex - 1) + (n - minindex);
    }

    printf("%d", swaps);
  }
  return 0;
}

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

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

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

    let mut line = String::new();

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

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

    let mut maxima = -1;
    let mut minima = 101;

    for item in &words {
        if *item > maxima {
            maxima = *item;
        }
        if *item < minima {
            minima = *item;
        }
    }

    let mut answer = 0;

    for (idx, item) in words.clone().into_iter().enumerate() {
        if item == maxima {
            answer += idx;
            break;
        }
    }

    for (idx, item) in words.clone().into_iter().rev().enumerate() {
        if item == minima {
            answer += idx;
            break;
        }
    }

    if answer >= n {
        answer -= 1;
    }

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


Score: <var>300</var> points

Problem Statement

Find the minimum prime number greater than or equal to <var>X</var>.

Notes

A prime number is an integer greater than <var>1</var> that cannot be evenly divided by any positive integer except <var>1</var> and itself.

For example, <var>2</var>, <var>3</var>, and <var>5</var> are prime numbers, while <var>4</var> and <var>6</var> are not.

Constraints

<var> 2 \le X \le 10^5 </var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

Print the minimum prime number greater than or equal to <var>X</var>.

Sample Input 1

20

Sample Output 1

23

The minimum prime number greater than or equal to <var>20</var> is <var>23</var>.

Sample Input 2

2

Sample Output 2

2

<var>X</var> itself can be a prime number.

Sample Input 3

99992

Sample Output 3

100003

int solution(void) {

  int X = 0;

  int i = 2;
  int j = 0;

  scanf("%d", &X);

  for (j = 0; j < 1000000; j++) {
    while (X % i != 0) {
      i++;
    }
    if (X != i) {
      X++;
      i = 2;
    } else {
      break;
    }
  }

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

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let x = stdin.lock().lines().next().unwrap().unwrap();
    let x = x.parse::<i32>().unwrap();

    for i in x.. {
        if (2..).take_while(|d| d * d <= i).all(|d| i % d != 0) {
            println!("{}", i);
            return;
        }
    }
}


Score : <var>400</var> points

Problem Statement

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

Let us choose some number of positive common divisors of <var>A</var> and <var>B</var>.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer <var>d</var> is said to be a common divisor of integers <var>x</var> and <var>y</var> when <var>d</var> divides both <var>x</var> and <var>y</var>.

Definition of being coprime

Integers <var>x</var> and <var>y</var> are said to be coprime when <var>x</var> and <var>y</var> have no positive common divisors other than <var>1</var>.

Definition of dividing

An integer <var>x</var> is said to divide another integer <var>y</var> when there exists an integer <var>\alpha</var> such that <var>y = \alpha x</var>.

Constraints

All values in input are integers.

<var>1 \leq A, B \leq 10^{12}</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

<var>12</var> and <var>18</var> have the following positive common divisors: <var>1</var>, <var>2</var>, <var>3</var>, and <var>6</var>.

<var>1</var> and <var>2</var> are coprime, <var>2</var> and <var>3</var> are coprime, and <var>3</var> and <var>1</var> are coprime, so we can choose <var>1</var>, <var>2</var>, and <var>3</var>, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

<var>1</var> and <var>2019</var> have no positive common divisors other than <var>1</var>.

int solution(void) {
  long a;
  long b;
  scanf("%ld %ld", &a, &b);

  long gcd;
  long m = a;
  long d = b;
  while (d > 0) {
    long temp = d;
    d = m % d;
    m = temp;
  }
  gcd = m;

  if (gcd == 1) {
    printf("%d\n", 1);
    return 0;
  }

  long count = 0;
  for (long i = 2; i <= sqrt(gcd); i++) {
    if (gcd % i == 0) {
      count++;
      while (gcd % i == 0) {
        gcd /= i;
      }
    }
  }

  if (gcd > 1) {
    count++;
  }

  printf("%ld\n", count + 1);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let a = it.next().unwrap().parse::<u64>().unwrap();
    let b = it.next().unwrap().parse::<u64>().unwrap();
    let mut div: Vec<u64> = Vec::new();
    for i in 2..a {
        if i * i > a {
            break;
        }
        if a % i == 0 {
            if b % i == 0 {
                div.push(i)
            }
            if b % (a / i) == 0 {
                div.push(a / i)
            }
        }
    }
    if a > 1 && b % a == 0 {
        div.push(a);
    }
    div.sort();
    let mut res: Vec<u64> = Vec::new();
    for d in div {
        if res.iter().all(|x| d % x != 0) {
            res.push(d);
        }
    }
    println!("{}", res.len() + 1);
}


A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

int solution() {
  int a;
  int b;
  int c;
  int n;
  int note[100001];
  int count = 0;

  scanf("%d%d%d%d", &a, &b, &c, &n);
  for (a = 0; a < n; a++) {
    scanf("%d", &note[a]);
    if (note[a] < c && note[a] > b) {
      count++;
    }
  }
  printf("%d\n", count);

  return 0;
}

fn solution() {
    let (_, b, c): (usize, usize, usize) = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut abc = line.split_whitespace().map(|s| s.parse().unwrap());
        (
            abc.next().unwrap(),
            abc.next().unwrap(),
            abc.next().unwrap(),
        )
    };

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

    let mut line = String::new();
    let x_iter = {
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace().map(|s| s.parse::<usize>().unwrap())
    };

    println!("{}", x_iter.filter(|&x| x > b && x < c).count());
}


Score : <var>400</var> points

Problem Statement

A positive integer <var>X</var> is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of <var>X</var> (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most <var>1</var>.

For example, <var>1234</var>, <var>1</var>, and <var>334</var> are lunlun numbers, while none of <var>31415</var>, <var>119</var>, or <var>13579</var> is.

You are given a positive integer <var>K</var>. Find the <var>K</var>-th smallest lunlun number.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the <var>15</var> smallest lunlun numbers in ascending order:

<var>1</var>,
<var>2</var>,
<var>3</var>,
<var>4</var>,
<var>5</var>,
<var>6</var>,
<var>7</var>,
<var>8</var>,
<var>9</var>,
<var>10</var>,
<var>11</var>,
<var>12</var>,
<var>21</var>,
<var>22</var>,
<var>23</var>.

Thus, the answer is <var>23</var>.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

Note that the answer may not fit into the <var>32</var>-bit signed integer type.

int solution(void) {
  unsigned long long int X[100000] = {0};
  unsigned long long int K;
  unsigned long long int count = 0;
  int l = -1;
  scanf("%llu", &K);

  for (int i = 0; i < 9; i++) {
    X[i] = i + 1;
  }

  for (unsigned long long int j = 9; j < K; j++) {
    X[j] = X[count] * 10 + (X[count] % 10) + l;
    l++;

    if (X[count] % 10 == 0) {
      X[j]++;
      if (l == 1) {
        count++;
        l = -1;
      }
    }

    if (l == 1 && X[count] % 10 == 9) {
      l = -1;
      count++;
    }

    if (l == 2) {
      l = -1;
      count++;
    }
  }

  printf("%llu", X[K - 1]);

  return 0;
}

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

    let mut ans: Vec<i8> = Vec::new();
    for _ in 0..k {
        let mut i = 0;
        while i <= ans.len() {
            if i == ans.len() {
                ans.push(1);
                break;
            } else if ans[i] < 9 && (i + 1 == ans.len() || (ans[i] + 1 - ans[i + 1]).abs() <= 1) {
                ans[i] += 1;
                break;
            }
            i += 1;
        }
        for j in (0..i).rev() {
            ans[j] = max(0, ans[j + 1] - 1);
        }
    }

    let ans = ans
        .iter()
        .rev()
        .map(|x| x.to_string())
        .collect::<Vec<_>>()
        .join("");
    println!("{}", ans);
}


Score : <var>200</var> points

Problem Statement

Evi has <var>N</var> integers <var>a_1,a_2,..,a_N</var>. His objective is to have <var>N</var> equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer <var>x</var> into another integer <var>y</var> costs him <var>(x-y)^2</var> dollars. Even if <var>a_i=a_j (i≠j)</var>, he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

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

<var>-100≦a_i≦100</var>

Input

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

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

Output

Print the minimum total cost to achieve Evi's objective.

Sample Input 1

2
4 8

Sample Output 1

8

Transforming the both into <var>6</var>s will cost <var>(4-6)^2+(8-6)^2=8</var> dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

3

Transforming the all into <var>2</var>s will cost <var>(1-2)^2+(1-2)^2+(3-2)^2=3</var> dollars. Note that Evi has to pay <var>(1-2)^2</var> dollar separately for transforming each of the two <var>1</var>s.

Sample Input 3

3
4 2 5

Sample Output 3

5

Leaving the <var>4</var> as it is and transforming the <var>2</var> and the <var>5</var> into <var>4</var>s will achieve the total cost of <var>(2-4)^2+(5-4)^2=5</var> dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0

Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is <var>0</var>.

int solution(void) {
  int n;
  int sum = 0;
  int low = 99999999;
  int a[105];
  scanf("%d", &n);

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

  for (int j = -100; j <= 100; j++) {
    sum = 0;
    for (int k = 0; k < n; k++) {
      sum = sum + (a[k] - j) * (a[k] - j);
    }
    if (sum <= low) {
      low = sum;
    }
  }
  printf("%d\n", low);
}

fn solution() {
    input! {
        N: usize,
        a: [i64; N],
    }
    use std::cmp::min;
    let mut ans = 1 << 60;
    for x in -100..101 {
        let s = a.iter().map(|&y| (x - y) * (x - y)).sum::<i64>();
        ans = min(ans, s);
    }
    println!("{}", ans);
}


Score : <var>300</var> points

Problem Statement

Given are positive integers <var>N</var>, <var>M</var>, <var>Q</var>, and <var>Q</var> quadruples of integers ( <var>a_i</var> , <var>b_i</var> , <var>c_i</var> , <var>d_i</var> ).

Consider a sequence <var>A</var> satisfying the following conditions:

<var>A</var> is a sequence of <var>N</var> positive integers.

<var>1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M</var>.

Let us define a score of this sequence as follows:

The score is the sum of <var>d_i</var> over all indices <var>i</var> such that <var>A_{b_i} - A_{a_i} = c_i</var>. (If there is no such <var>i</var>, the score is <var>0</var>.)

Find the maximum possible score of <var>A</var>.

Constraints

All values in input are integers.

<var>2 ≤ N ≤ 10</var>

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

<var>1 \leq Q \leq 50</var>

<var>1 \leq a_i < b_i \leq N</var> ( <var>i = 1, 2, ..., Q</var> )

<var>0 \leq c_i \leq M - 1</var> ( <var>i = 1, 2, ..., Q</var> )

<var>(a_i, b_i, c_i) \neq (a_j, b_j, c_j)</var> (where <var>i \neq j</var>)

<var>1 \leq d_i \leq 10^5</var> ( <var>i = 1, 2, ..., Q</var> )

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>Q</var>
<var>a_1</var> <var>b_1</var> <var>c_1</var> <var>d_1</var>
<var>:</var>
<var>a_Q</var> <var>b_Q</var> <var>c_Q</var> <var>d_Q</var>

Output

Print the maximum possible score of <var>A</var>.

Sample Input 1

3 4 3
1 3 3 100
1 2 2 10
2 3 2 10

Sample Output 1

110

When <var>A = \{1, 3, 4\}</var>, its score is <var>110</var>. Under these conditions, no sequence has a score greater than <var>110</var>, so the answer is <var>110</var>.

Sample Input 2

4 6 10
2 4 1 86568
1 4 0 90629
2 3 0 90310
3 4 1 29211
3 4 3 78537
3 4 2 8580
1 2 1 96263
1 4 2 2156
1 2 0 94325
1 4 3 94328

Sample Output 2

357500

Sample Input 3

10 10 1
1 10 9 1

Sample Output 3

1

int solution(void) {

  int n;
  int m;
  int q;
  scanf("%d %d %d", &n, &m, &q);
  int a[q];
  int b[q];
  int c[q];
  long d[q];
  for (long i = 0; i < q; i++) {
    scanf("%d %d %d %ld", &a[i], &b[i], &c[i], &d[i]);
  }
  long max = 0;
  long score;
  int sequence[n];
  for (int i = 0; i < n; i++) {
    sequence[i] = 1;
  }
  while (1) {
    score = 0;
    for (int i = 0; i < q; i++) {
      if (sequence[b[i] - 1] - sequence[a[i] - 1] == c[i]) {
        score += d[i];
      }
    }
    if (score > max) {
      max = score;
    }
    if (sequence[1] == m) {
      break;
    }
    for (int i = n - 1; i > 0; i--) {
      if (sequence[i] < m) {
        sequence[i]++;
        for (int j = i + 1; j < n; j++) {
          sequence[j] = sequence[i];
        }
        break;
      }
    }
  }
  printf("%ld\n", max);

  return 0;
}

fn solution() {
    input! {
        n: usize,
        m: usize,
        q: usize,
        v: [(usize1, usize1, usize, usize); q]
    }
    let mut ar = vec![0; n];
    let mut ans = 0;
    while ar[0] < m {
        let mut t = 0;
        for &(a, b, c, d) in &v {
            if ar[b] - ar[a] == c {
                t += d;
            }
        }
        ans = max(ans, t);
        ar[n - 1] += 1;
        let mut i = n - 1;
        while i > 0 {
            if ar[i] == m {
                i -= 1;
                ar[i] += 1;
            } else {
                break;
            }
        }
        while i < n - 1 {
            ar[i + 1] = ar[i];
            i += 1;
        }
    }
    println!("{}", ans);
}


Enumeration of Subsets II

  You are given a set $T$, which is a subset of $U$. The set $U$ consists of $0, 1, ... n-1$.

  Print all sets, each of which is a subset of $U$ and includes $T$ as a subset.

  Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elements.

Input

  The input is given in the following format.

$n$
$k \; b_0 \; b_1 \; ... \; b_{k-1}$

$k$ is the number of elements in $T$, and $b_i$ represents elements in $T$.

Output

  Print the subsets ordered by their decimal integers. Print a subset in the following format.

$d$: $e_0$ $e_1$ ...

  Print ':' after the integer value $d$, then print elements $e_i$ in the subset in ascending order. Separate two adjacency elements by a space character.

Constraints

$1 \leq n \leq 18$

$0 \leq k \leq n$

$0 \leq b_i < n$

Sample Input 1

4
2 0 2

Sample Output 1

5: 0 2
7: 0 1 2
13: 0 2 3
15: 0 1 2 3

int solution() {
  int n;
  int bit[19];
  int *t;
  int t_n;
  int x;
  int tmp;
  int size;
  int flag;
  int i;
  int j;
  int k;

  scanf("%d", &n);

  scanf("%d", &t_n);

  t = (int *)malloc(sizeof(int) * t_n);
  for (i = 0; i < t_n; i++) {
    scanf("%d", &t[i]);
  }

  for (i = 0; i < pow(2, n); i++) {
    x = i;
    j = k = 0;
    while ((tmp = x / 2) >= 1) {
      if (x % 2) {
        bit[k++] = j;
      }
      x = tmp;
      j++;
    }
    if (x) {
      bit[k] = j;
    }

    size = k;

    if (i > 0) {
      flag = 1;
      for (j = 0; j < t_n; j++) {
        for (k = 0; k <= size; k++) {
          if (t[j] == bit[k]) {
            break;
          }
        }
        if (k == size + 1) {
          flag = 0;
          break;
        }
      }

      if (flag) {
        printf("%d:", i);
        for (j = 0; j <= size; j++) {
          printf(" %d", bit[j]);
        }
        printf("\n");
      }
    } else if (i == 0 && t_n == 0) {
      printf("0:\n");
    }
  }

  return 0;
}

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

    let n: u32 = input.parse().unwrap();

    input.clear();
    stdin().read_line(&mut input);
    input.pop();

    let mut t = 0u32;
    let mut max = 0;
    for s in input.split(' ').skip(1) {
        let b = s.parse::<u32>().unwrap();
        t |= 1 << b;
        if max < b {
            max = b;
        }
    }

    let out = stdout();
    let mut out = BufWriter::new(out.lock());
    if t == 0 {
        writeln!(out, "0:");
    }

    for p in max..n {
        for d in (1 << p)..(2 << p) {
            if d & t == t {
                write!(out, "{}:", d);

                for e in 0..p + 1 {
                    if d & 1 << e != 0 {
                        write!(out, " {}", e);
                    }
                }
                writeln!(out);
            }
        }
    }
}


Score : <var>500</var> points

Problem Statement

"Teishi-zushi", a Japanese restaurant, is a plain restaurant with only one round counter. The outer circumference of the counter is <var>C</var> meters. Customers cannot go inside the counter.

Nakahashi entered Teishi-zushi, and he was guided to the counter. Now, there are <var>N</var> pieces of sushi (vinegared rice with seafood and so on) on the counter. The distance measured clockwise from the point where Nakahashi is standing to the point where the <var>i</var>-th sushi is placed, is <var>x_i</var> meters. Also, the <var>i</var>-th sushi has a nutritive value of <var>v_i</var> kilocalories.

Nakahashi can freely walk around the circumference of the counter. When he reach a point where a sushi is placed, he can eat that sushi and take in its nutrition (naturally, the sushi disappears). However, while walking, he consumes <var>1</var> kilocalories per meter.

Whenever he is satisfied, he can leave the restaurant from any place (he does not have to return to the initial place). On balance, at most how much nutrition can he take in before he leaves? That is, what is the maximum possible value of the total nutrition taken in minus the total energy consumed? Assume that there are no other customers, and no new sushi will be added to the counter. Also, since Nakahashi has plenty of nutrition in his body, assume that no matter how much he walks and consumes energy, he never dies from hunger.

Constraints

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

<var>2 ≤ C ≤ 10^{14}</var>

<var>1 ≤ x_1 < x_2 < ... < x_N < C</var>

<var>1 ≤ v_i ≤ 10^9</var>

All values in input are integers.

Subscores

<var>300</var> points will be awarded for passing the test set satisfying <var>N ≤ 100</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>C</var>
<var>x_1</var> <var>v_1</var>
<var>x_2</var> <var>v_2</var>
<var>:</var>
<var>x_N</var> <var>v_N</var>

Output

If Nakahashi can take in at most <var>c</var> kilocalories on balance before he leaves the restaurant, print <var>c</var>.

Sample Input 1

3 20
2 80
9 120
16 1

Sample Output 1

191

There are three sushi on the counter with a circumference of <var>20</var> meters. If he walks two meters clockwise from the initial place, he can eat a sushi of <var>80</var> kilocalories. If he walks seven more meters clockwise, he can eat a sushi of <var>120</var> kilocalories. If he leaves now, the total nutrition taken in is <var>200</var> kilocalories, and the total energy consumed is <var>9</var> kilocalories, thus he can take in <var>191</var> kilocalories on balance, which is the largest possible value.

Sample Input 2

3 20
2 80
9 1
16 120

Sample Output 2

192

The second and third sushi have been swapped. Again, if he walks two meters clockwise from the initial place, he can eat a sushi of <var>80</var> kilocalories. If he walks six more meters counterclockwise this time, he can eat a sushi of <var>120</var> kilocalories. If he leaves now, the total nutrition taken in is <var>200</var> kilocalories, and the total energy consumed is <var>8</var> kilocalories, thus he can take in <var>192</var> kilocalories on balance, which is the largest possible value.

Sample Input 3

1 100000000000000
50000000000000 1

Sample Output 3

0

Even though the only sushi is so far that it does not fit into a <var>32</var>-bit integer, its nutritive value is low, thus he should immediately leave without doing anything.

Sample Input 4

15 10000000000
400000000 1000000000
800000000 1000000000
1900000000 1000000000
2400000000 1000000000
2900000000 1000000000
3300000000 1000000000
3700000000 1000000000
3800000000 1000000000
4000000000 1000000000
4100000000 1000000000
5200000000 1000000000
6600000000 1000000000
8000000000 1000000000
9300000000 1000000000
9700000000 1000000000

Sample Output 4

6500000000

All these sample inputs above are included in the test set for the partial score.

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 c: i64 = itr.next().unwrap().parse().unwrap();
    let mut rx = vec![0i64; n];
    let mut rv = vec![0i64; n];
    for i in 0..n {
        rx[i] = itr.next().unwrap().parse().unwrap();
        rv[i] = itr.next().unwrap().parse().unwrap();
    }
    let mut lx = vec![0; n];
    let mut lv = rv.clone();
    let mut lmax = vec![0; n];
    let mut rmax = vec![0; n];
    lv.reverse();
    for i in 0..n {
        lx[i] = c - rx[n - 1 - i];
    }
    for i in 0..n - 1 {
        lv[i + 1] += lv[i];
        rv[i + 1] += rv[i];
        lmax[i + 1] = max(lmax[i], lv[i] - lx[i]);
        rmax[i + 1] = max(rmax[i], rv[i] - rx[i]);
    }

    let mut ans = 0i64;
    for i in 0..n {
        ans = max(ans, lv[i] - lx[i]);
        ans = max(ans, lv[i] - lx[i] * 2 + rmax[n - 1 - i]);
    }
    for i in 0..n {
        ans = max(ans, rv[i] - rx[i]);
        ans = max(ans, rv[i] - rx[i] * 2 + lmax[n - 1 - i]);
    }
    println!("{}", ans);
}


Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.In the beginning, uncle Bogdan wrote on a board a positive integer $$$x$$$ consisting of $$$n$$$ digits. After that, he wiped out $$$x$$$ and wrote integer $$$k$$$ instead, which was the concatenation of binary representations of digits $$$x$$$ consists of (without leading zeroes). For example, let $$$x = 729$$$, then $$$k = 111101001$$$ (since $$$7 = 111$$$, $$$2 = 10$$$, $$$9 = 1001$$$).After some time, uncle Bogdan understood that he doesn't know what to do with $$$k$$$ and asked Denis to help. Denis decided to wipe last $$$n$$$ digits of $$$k$$$ and named the new number as $$$r$$$.As a result, Denis proposed to find such integer $$$x$$$ of length $$$n$$$ that $$$r$$$ (as number) is maximum possible. If there are multiple valid $$$x$$$ then Denis is interested in the minimum one.All crew members, including captain Flint himself, easily solved the task. All, except cabin boy Kostya, who was too drunk to think straight. But what about you?Note: in this task, we compare integers ($$$x$$$ or $$$k$$$) as numbers (despite what representations they are written in), so $$$729 < 1999$$$ or $$$111 < 1000$$$.

int solution() {
  int n = 0;
  int k = 0;
  scanf("%d", &n);
  int rez[n];
  for (int i = 0; i < n; ++i) {
    scanf("%d", &k);
    rez[i] = k;
  }
  for (int i = 0; i < n; ++i) {
    int e = ((rez[i] - 1) / 4) + 1;
    for (int j = 0; j < rez[i] - e; ++j) {
      printf("9");
    }
    for (int j = 0; j < e; ++j) {
      printf("8");
    }
    printf("\n");
  }
  return 0;
}

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

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

        let k = (n - 1) / 4 + 1;
        for _ in 0..(n - k) {
            print!("9");
        }
        for _ in 0..k {
            print!("8");
        }
        println!();
    }
}


Score : <var>100</var> points

Problem Statement

There are <var>N</var> children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give <var>1</var> candy to the first child in the line, <var>2</var> candies to the second child, ..., <var>N</var> candies to the <var>N</var>-th child. How many candies will be necessary in total?

Constraints

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

Input

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

<var>N</var>

Output

Print the necessary number of candies in total.

Sample Input 1

3

Sample Output 1

6

The answer is <var>1+2+3=6</var>.

Sample Input 2

10

Sample Output 2

55

The sum of the integers from <var>1</var> to <var>10</var> is <var>55</var>.

Sample Input 3

1

Sample Output 3

1

Only one child. The answer is <var>1</var> in this case.

int solution() {
  int N = 0;
  scanf("%d", &N);
  printf("%d\n", (int)(0.5 * N * (N + 1)));
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let n: usize = s.trim().parse().unwrap();
    println!("{}", n * (n + 1) / 2);
}


Score : <var>400</var> points

Problem Statement

Kenkoooo is planning a trip in Republic of Snuke.
In this country, there are <var>n</var> cities and <var>m</var> trains running.
The cities are numbered <var>1</var> through <var>n</var>, and the <var>i</var>-th train connects City <var>u_i</var> and <var>v_i</var> bidirectionally.
Any city can be reached from any city by changing trains.

Two currencies are used in the country: yen and snuuk.
Any train fare can be paid by both yen and snuuk.
The fare of the <var>i</var>-th train is <var>a_i</var> yen if paid in yen, and <var>b_i</var> snuuk if paid in snuuk.

In a city with a money exchange office, you can change <var>1</var> yen into <var>1</var> snuuk.
However, when you do a money exchange, you have to change all your yen into snuuk.
That is, if Kenkoooo does a money exchange when he has <var>X</var> yen, he will then have <var>X</var> snuuk.
Currently, there is a money exchange office in every city, but the office in City <var>i</var> will shut down in <var>i</var> years and can never be used in and after that year.

Kenkoooo is planning to depart City <var>s</var> with <var>10^{15}</var> yen in his pocket and head for City <var>t</var>, and change his yen into snuuk in some city while traveling.
It is acceptable to do the exchange in City <var>s</var> or City <var>t</var>.

Kenkoooo would like to have as much snuuk as possible when he reaches City <var>t</var> by making the optimal choices for the route to travel and the city to do the exchange.
For each <var>i=0,...,n-1</var>, find the maximum amount of snuuk that Kenkoooo has when he reaches City <var>t</var> if he goes on a trip from City <var>s</var> to City <var>t</var> after <var>i</var> years.
You can assume that the trip finishes within the year.

Constraints

<var>2 \leq n \leq 10^5</var>

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

<var>1 \leq s,t \leq n</var>

<var>s \neq t</var>

<var>1 \leq u_i < v_i \leq n</var>

<var>1 \leq a_i,b_i \leq 10^9</var>

If <var>i\neq j</var>, then <var>u_i \neq u_j </var> or <var>v_i \neq v_j</var>.

Any city can be reached from any city by changing trains.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>n</var> <var>m</var> <var>s</var> <var>t</var>
<var>u_1</var> <var>v_1</var> <var>a_1</var> <var>b_1</var>
<var>:</var>
<var>u_m</var> <var>v_m</var> <var>a_m</var> <var>b_m</var>

Output

Print <var>n</var> lines.
In the <var>i</var>-th line, print the maximum amount of snuuk that Kenkoooo has when he reaches City <var>t</var> if he goes on a trip from City <var>s</var> to City <var>t</var> after <var>i-1</var> years.

Sample Input 1

4 3 2 3
1 4 1 100
1 2 1 10
1 3 20 1

Sample Output 1

999999999999998
999999999999989
999999999999979
999999999999897

After <var>0</var> years, it is optimal to do the exchange in City <var>1</var>.

After <var>1</var> years, it is optimal to do the exchange in City <var>2</var>.

Note that City <var>1</var> can still be visited even after the exchange office is closed.
Also note that, if it was allowed to keep <var>1</var> yen when do the exchange in City <var>2</var> and change the remaining yen into snuuk, we could reach City <var>3</var> with <var>999999999999998</var> snuuk, but this is NOT allowed.

After <var>2</var> years, it is optimal to do the exchange in City <var>3</var>.

After <var>3</var> years, it is optimal to do the exchange in City <var>4</var>.
Note that the same train can be used multiple times.

Sample Input 2

8 12 3 8
2 8 685087149 857180777
6 7 298270585 209942236
2 4 346080035 234079976
2 5 131857300 22507157
4 8 30723332 173476334
2 6 480845267 448565596
1 4 181424400 548830121
4 5 57429995 195056405
7 8 160277628 479932440
1 6 475692952 203530153
3 5 336869679 160714712
2 7 389775999 199123879

Sample Output 2

999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994
999999574976994

int solution(void) {
  long long n;
  long long p;
  long long s;
  long long t;
  long long count;
  scanf("%lld%lld%lld%lld", &n, &p, &s, &t);
  bool visited[n + 1];

  long long mm = 0;
  long long head[(3 * p) + 1];
  long long next[(3 * p) + 1];
  long long to[(3 * p) + 1];
  long long leny[(3 * p) + 1];
  long long lens[(3 * p) + 1];
  for (int i = 0; i <= n; i++) {
    head[i] = -1;
  }
  for (long long i = 0; i < p; i++) {
    long long u;
    long long v;
    long long a;
    long long b;
    scanf("%lld%lld%lld%lld", &u, &v, &a, &b);
    next[mm] = head[u];
    head[u] = mm;
    to[mm] = v;
    leny[mm] = a;
    lens[mm] = b;
    mm++;
    next[mm] = head[v];
    head[v] = mm;
    to[mm] = u;
    leny[mm] = a;
    lens[mm] = b;
    mm++;
  }

  long long countans = 0;
  count = 0;
  queue_t q[n * 50];
  queue_t tmpq;
  long long d[n + 1];
  for (long long i = 0; i <= n; i++) {
    visited[i] = false;
    d[i] = 1e17;
    q[i].q = d[i];
    q[i].i = i;
    count++;
  }
  d[s] = 0;
  q[0].q = -1e17;
  q[count].q = d[s];
  q[count].i = s;
  for (long long i = count; i > 0; i = i / 2) {
    if (i / 2 != 0 && q[i].q <= q[i / 2].q) {
      tmpq = q[i];
      q[i] = q[i / 2];
      q[i / 2] = tmpq;
    } else {
      break;
    }
  }
  for (long long i = 0; i <= n; i++) {
    long long now = q[1].i;
    if (visited[now] == false) {
      visited[now] = true;
      countans++;
    }

    q[1] = q[count];
    long long bf = 1;
    while (1) {
      if (bf * 2 > count) {
        break;
      }
      if (q[bf * 2].q <= q[(bf * 2) + 1].q) {
        if (q[bf].q > q[bf * 2].q) {
          tmpq = q[bf];
          q[bf] = q[bf * 2];
          q[bf * 2] = tmpq;
          bf = bf * 2;
        } else {
          break;
        }
      } else {
        if (q[bf].q > q[(bf * 2) + 1].q) {
          tmpq = q[bf];
          q[bf] = q[(bf * 2) + 1];
          q[(bf * 2) + 1] = tmpq;
          bf = bf * 2 + 1;
        } else {
          break;
        }
      }
    }
    count--;
    long long tmp;
    for (long long e = head[now]; e != -1; e = next[e]) {
      tmp = d[now] + leny[e];
      if (d[to[e]] > tmp) {
        d[to[e]] = tmp;
        count++;
        q[count].q = tmp;
        q[count].i = to[e];
        for (long long af = count; af > 0; af = af / 2) {
          if (af / 2 != 0 && q[af].q <= q[af / 2].q) {
            tmpq = q[af];
            q[af] = q[af / 2];
            q[af / 2] = tmpq;
          } else {
            break;
          }
        }
      }
    }
    if (countans == n) {
      break;
    }
  }

  countans = 0;
  count = 0;
  queue_t q2[n * 50];
  long long f[n + 1];
  for (long long i = 0; i <= n; i++) {
    visited[i] = false;
    f[i] = 1e17;
    q2[i].q = f[i];
    q2[i].i = i;
    count++;
  }
  f[t] = 0;
  q2[0].q = -1e17;
  q2[count].q = f[t];
  q2[count].i = t;
  for (long long i = count; i > 0; i = i / 2) {
    if (i / 2 != 0 && q2[i].q <= q2[i / 2].q) {
      tmpq = q2[i];
      q2[i] = q2[i / 2];
      q2[i / 2] = tmpq;
    } else {
      break;
    }
  }
  for (long long i = 0; i <= n; i++) {
    int now = q2[1].i;

    if (visited[now] == false) {
      visited[now] = true;
      countans++;
    }

    q2[1] = q2[count];
    long long bf = 1;
    while (1) {
      if (bf * 2 >= count) {
        break;
      }
      if (q2[bf * 2].q <= q2[(bf * 2) + 1].q) {
        if (q2[bf].q > q2[bf * 2].q) {
          tmpq = q2[bf];
          q2[bf] = q2[bf * 2];
          q2[bf * 2] = tmpq;
          bf = bf * 2;
        } else {
          break;
        }
      } else {
        if (q2[bf].q > q2[(bf * 2) + 1].q) {
          tmpq = q2[bf];
          q2[bf] = q2[(bf * 2) + 1];
          q2[(bf * 2) + 1] = tmpq;
          bf = bf * 2 + 1;
        } else {
          break;
        }
      }
    }
    count--;
    long long tmp;
    for (long long e = head[now]; e != -1; e = next[e]) {
      tmp = f[now] + lens[e];
      if (f[to[e]] > tmp) {
        f[to[e]] = tmp;
        count++;
        q2[count].q = tmp;
        q2[count].i = to[e];
        for (long long af = count; af > 0; af = af / 2) {
          if (af / 2 != 0 && q2[af].q <= q2[af / 2].q) {
            tmpq = q2[af];
            q2[af] = q2[af / 2];
            q2[af / 2] = tmpq;
          } else {
            break;
          }
        }
      }
    }
    if (countans == n) {
      break;
    }
  }

  long long ans[n + 1];
  ans[0] = 0;
  for (int i = 1; i <= n; i++) {
    ans[i] = d[i] + f[i];
  }
  for (int i = n; i > 1; i--) {
    if (ans[i] < ans[i - 1]) {
      ans[i - 1] = ans[i];
    }
  }
  for (int i = 1; i <= n; i++) {
    printf("%lld\n", 1000000000000000 - ans[i]);
  }

  return 0;
}

fn solution() {
    let mut nmst = String::new();
    std::io::stdin().read_line(&mut nmst).unwrap();
    let nmst: Vec<usize> = nmst
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let n = nmst[0];
    let m = nmst[1];
    let s = nmst[2] - 1;
    let t = nmst[3] - 1;
    let mut g: Vec<Vec<(usize, usize, usize)>> = vec![vec![]; n];
    for _ in 0..m {
        let mut uvab = String::new();
        std::io::stdin().read_line(&mut uvab).unwrap();
        let uvab: Vec<usize> = uvab
            .split_whitespace()
            .map(|x| x.parse().unwrap())
            .collect();
        let u = uvab[0] - 1;
        let v = uvab[1] - 1;
        let a = uvab[2];
        let b = uvab[3];
        g[u].push((v, a, b));
        g[v].push((u, a, b));
    }
    let f = 1e15 as usize;
    let mut e = vec![f; n];
    let mut q = std::collections::BinaryHeap::new();
    q.push((f, n, t));
    while let Some((y, c, v)) = q.pop() {
        if e[v] <= f - y {
            continue;
        }
        e[v] = f - y;
        for &(u, _, b) in &g[v] {
            if e[u] >= f - (y - b) {
                q.push((y - b, c, u));
            }
        }
    }
    let mut d = vec![0; n];
    q.push((f, n, s));
    let mut r = vec![];
    r.reserve(n);
    while let Some((y, c, v)) = q.pop() {
        if c == n {
            if d[v] >= y {
                continue;
            }
            d[v] = y;
            if r.len() <= v {
                q.push((y - e[v], v, t));
            }
            for &(u, a, _) in &g[v] {
                if d[u] < y - a {
                    q.push((y - a, c, u));
                }
            }
        } else {
            if r.len() <= c {
                r.resize(c + 1, y);
            }
        }
    }
    for y in r {
        println!("{}", y);
    }
}


Score : <var>500</var> points

Problem Statement

Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph <var>G</var>.
<var>G</var> consists of <var>N</var> vertices numbered <var>1</var> to <var>N</var>, and <var>M</var> edges. The <var>i</var>-th edge points from Vertex <var>u_i</var> to Vertex <var>v_i</var>.

First, Ken stands on Vertex <var>S</var>. He wants to reach Vertex <var>T</var> by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.

Determine if he can reach Vertex <var>T</var> by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex <var>T</var>. Note that visiting Vertex <var>T</var> in the middle of a ken-ken-pa does not count as reaching Vertex <var>T</var> by repeating ken-ken-pa.

Constraints

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

<var>0 \leq M \leq \min(10^5, N (N-1))</var>

<var>1 \leq u_i, v_i \leq N(1 \leq i \leq M)</var>

<var>u_i \neq v_i (1 \leq i \leq M)</var>

If <var>i \neq j</var>, <var>(u_i, v_i) \neq (u_j, v_j)</var>.

<var>1 \leq S, T \leq N</var>

<var>S \neq T</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>u_1</var> <var>v_1</var>
<var>:</var>
<var>u_M</var> <var>v_M</var>
<var>S</var> <var>T</var>

Output

If Ken cannot reach Vertex <var>T</var> from Vertex <var>S</var> by repeating ken-ken-pa, print <var>-1</var>.
If he can, print the minimum number of ken-ken-pa needed to reach vertex <var>T</var>.

Sample Input 1

4 4
1 2
2 3
3 4
4 1
1 3

Sample Output 1

2

Ken can reach Vertex <var>3</var> from Vertex <var>1</var> in two ken-ken-pa, as follows: <var>1 \rightarrow 2 \rightarrow 3 \rightarrow 4</var> in the first ken-ken-pa, then <var>4 \rightarrow 1 \rightarrow 2 \rightarrow 3</var> in the second ken-ken-pa. This is the minimum number of ken-ken-pa needed.

Sample Input 2

3 3
1 2
2 3
3 1
1 2

Sample Output 2

-1

Any number of ken-ken-pa will bring Ken back to Vertex <var>1</var>, so he cannot reach Vertex <var>2</var>, though he can pass through it in the middle of a ken-ken-pa.

Sample Input 3

2 0
1 2

Sample Output 3

-1

Vertex <var>S</var> and Vertex <var>T</var> may be disconnected.

Sample Input 4

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

Sample Output 4

2

int solution() {
  int i;
  int u;
  int w;
  int N;
  int M;
  int S;
  int T;
  scanf("%d %d", &N, &M);
  list **adj = (list **)malloc(sizeof(list *) * (N + 1) * 3);
  list *d = (list *)malloc(sizeof(list) * M * 3);
  for (i = 1; i <= N * 3; i++) {
    adj[i] = NULL;
  }
  for (i = 0; i < M; i++) {
    scanf("%d %d", &u, &w);
    d[i * 3].v = w + N;
    d[i * 3].next = adj[u];
    adj[u] = &(d[i * 3]);
    d[(i * 3) + 1].v = w + N * 2;
    d[(i * 3) + 1].next = adj[u + N];
    adj[u + N] = &(d[(i * 3) + 1]);
    d[(i * 3) + 2].v = w;
    d[(i * 3) + 2].next = adj[u + (N * 2)];
    adj[u + (N * 2)] = &(d[(i * 3) + 2]);
  }
  scanf("%d %d", &S, &T);

  int dist[300001] = {};
  int q[300001];
  int head;
  int tail;
  list *p;
  dist[S] = 1;
  q[0] = S;
  for (head = 0, tail = 1; head < tail; head++) {
    u = q[head];
    for (p = adj[u]; p != NULL; p = p->next) {
      if (dist[p->v] == 0) {
        dist[p->v] = dist[u] + 1;
        q[tail++] = p->v;
      }
    }
  }

  printf("%d\n", ((dist[T] + 2) / 3) - 1);
  fflush(stdout);
  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 m: usize = itr.next().unwrap().parse().unwrap();
    let mut g = vec![Vec::new(); n];
    for _ in 0..m {
        let u = itr.next().unwrap().parse::<usize>().unwrap() - 1;
        let v = itr.next().unwrap().parse::<usize>().unwrap() - 1;
        g[u].push(v);
    }
    let s: usize = itr.next().unwrap().parse::<usize>().unwrap() - 1;
    let t: usize = itr.next().unwrap().parse::<usize>().unwrap() - 1;

    let mut dp = vec![vec![1 << 30; 5]; n + 1];
    dp[s][0] = 0;

    let mut q = std::collections::VecDeque::new();
    q.push_back((s, 0));
    while let Some((v, p)) = q.pop_front() {
        for &nv in g[v].iter() {
            if dp[nv][(p + 1) % 3] == (1 << 30) {
                dp[nv][(p + 1) % 3] = min(dp[nv][(p + 1) % 3], dp[v][p] + 1);
                q.push_back((nv, (p + 1) % 3));
            }
        }
    }

    if dp[t][0] == 1 << 30 {
        println!("-1")
    } else {
        println!("{}", dp[t][0] / 3);
    }
}


Score : <var>400</var> points

Problem Statement

Mr. Takahashi has a string <var>s</var> consisting of lowercase English letters.
He repeats the following operation on <var>s</var> exactly <var>K</var> times.

Choose an arbitrary letter on <var>s</var> and change that letter to the next alphabet. Note that the next letter of z is a.

For example, if you perform an operation for the second letter on aaz, aaz becomes abz.
If you then perform an operation for the third letter on abz, abz becomes aba.

Mr. Takahashi wants to have the lexicographically smallest string after performing exactly <var>K</var> operations on <var>s</var>.
Find the such string.

Constraints

<var>1≤|s|≤10^5</var>

All letters in <var>s</var> are lowercase English letters.

<var>1≤K≤10^9</var>

Input

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

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

Output

Print the lexicographically smallest string after performing exactly <var>K</var> operations on <var>s</var>.

Sample Input 1

xyz
4

Sample Output 1

aya

For example, you can perform the following operations: xyz, yyz, zyz, ayz, aya.

Sample Input 2

a
25

Sample Output 2

z

You have to perform exactly <var>K</var> operations.

Sample Input 3

codefestival
100

Sample Output 3

aaaafeaaivap

int solution() {
  static char S[100005];
  static char *p;
  static int K;
  static int res;
  static int t;
  fgets(S, 100005, stdin);
  scanf("%d", &K);
  p = S;
  while (*(p + 2)) {
    if (*p - 'a') {
      t = '{' - *p;
      if (K >= t) {
        K -= t;
        res += t;
        *p = 'a';
      }
    }
    ++p;
  }
  *p = (*p - 'a' + K) % 26 + 'a';
  *++p ^= 10;
  puts(S);
}

fn solution() {
    input! {
        s: chars,
        mut k: u64,
    }
    let mut ans = "".to_string();
    for i in 0..s.len() - 1 {
        let acc = (s[i] as u8 - b'a') as u64;
        if k / (26u64 - acc) > 0 && acc != 0 {
            ans += &'a'.to_string();
            k -= 26 - acc;
        } else {
            ans += &((acc as u8 + b'a') as char).to_string();
        }
    }
    k %= 26;
    let acc = ((s[s.len() - 1] as u8 - b'a') + k as u8) % 26;
    ans += &((acc + b'a') as char).to_string();

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


You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?

int solution() {
  int n;
  int a[2000];
  scanf("%d", &n);
  for (int i = 0; i < 2 * n; ++i) {
    scanf("%d", &a[i]);
  }
  int sumA = 0;
  int sumB = 0;
  for (int i = 0; i < n; ++i) {
    sumA += a[i];
  }
  for (int i = n; i < 2 * n; ++i) {
    sumB += a[i];
  }
  if (sumA == sumB) {
    for (int i = 0; i < n; ++i) {
      for (int j = n; j < 2 * n; ++j) {
        if (a[i] != a[j]) {
          int temp = a[i];
          a[i] = a[j];
          a[j] = temp;
          for (int k = 0; k < 2 * n; ++k) {
            printf("%d ", a[k]);
          }
          return 0;
        }
      }
    }
    puts("-1");
  } else {
    for (int i = 0; i < 2 * n; ++i) {
      printf("%d ", a[i]);
    }
  }
  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 mut vs = vec![];
    for _ in 0..n * 2 {
        vs.push(get!());
    }
    vs.sort();
    let sum1: i64 = vs[0..n].iter().sum();
    let sum2: i64 = vs[n..n * 2].iter().sum();
    if sum1 == sum2 {
        println!("-1");
    } else {
        for i in 0..vs.len() {
            if i > 0 {
                print!(" ");
            }
            print!("{}", vs[i]);
        }
        println!();
    }
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these.

Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from the top rank down. Participants who are not students cannot pass the Qualification contests.

A Japanese student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than <var>A+B</var>.

An overseas student passes the Qualification contests if the number of the participants who have already definitively passed is currently fewer than <var>A+B</var> and the student ranks <var>B</var>-th or above among all overseas students.

A string <var>S</var> is assigned indicating attributes of all participants. If the <var>i</var>-th character of string <var>S</var> is a, this means the participant ranked <var>i</var>-th in the Qualification contests is a Japanese student; b means the participant ranked <var>i</var>-th is an overseas student; and c means the participant ranked <var>i</var>-th is neither of these.

Write a program that outputs for all the participants in descending rank either Yes if they passed the Qualification contests or No if they did not pass.

Constraints

<var>1≦N,A,B≦100000</var>

<var>A+B≦N</var>

<var>S</var> is <var>N</var> characters long.

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

Input

Inputs are provided from Standard Input in the following form.

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

Output

Output <var>N</var> lines. On the <var>i</var>-th line, output Yes if the <var>i</var>-th participant passed the Qualification contests or No if that participant did not pass.

Sample Input 1

10 2 3
abccabaabb

Sample Output 1

Yes
Yes
No
No
Yes
Yes
Yes
No
No
No

The first, second, fifth, sixth, and seventh participants pass the Qualification contests.

Sample Input 2

12 5 2
cabbabaacaba

Sample Output 2

No
Yes
Yes
Yes
Yes
No
Yes
Yes
No
Yes
No
No

The sixth participant is third among overseas students and thus does not pass the Qualification contests.

Sample Input 3

5 2 2
ccccc

Sample Output 3

No
No
No
No
No

int solution() {
  int N;
  int B;
  int A;
  scanf("%d%d%d", &N, &A, &B);
  char S[N];
  scanf("%s", S);

  int counta = 0;
  int countb = 1;

  for (int i = 0; i < N; i++) {
    if (S[i] == 'a' && A + B > counta) {

      counta++;
      printf("Yes\n");

    } else if (S[i] == 'b' && A + B > counta && countb <= B) {

      countb++;
      counta++;
      printf("Yes\n");

    }

    else {
      printf("No\n");
    }
  }
  return 0;
}

fn solution() {
    let (_N, A, B): (usize, usize, usize) = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };
    let S: Vec<char> = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().chars().collect()
    };

    let mut c = 0;
    let mut d = 0;
    for &s in &S {
        if s == 'a' && c < A + B {
            c += 1;
            println!("Yes");
        } else if s == 'b' && c < A + B && d < B {
            c += 1;
            d += 1;
            println!("Yes")
        } else {
            println!("No")
        }
    }
}


You are given a sequence $$$a_1, a_2, \dots, a_n$$$ consisting of $$$n$$$ pairwise distinct positive integers.Find $$$\left\lfloor \frac n 2 \right\rfloor$$$ different pairs of integers $$$x$$$ and $$$y$$$ such that:   $$$x \neq y$$$;  $$$x$$$ and $$$y$$$ appear in $$$a$$$;  $$$x~mod~y$$$ doesn't appear in $$$a$$$. Note that some $$$x$$$ or $$$y$$$ can belong to multiple pairs.$$$\lfloor x \rfloor$$$ denotes the floor function — the largest integer less than or equal to $$$x$$$. $$$x~mod~y$$$ denotes the remainder from dividing $$$x$$$ by $$$y$$$.If there are multiple solutions, print any of them. It can be shown that at least one solution always exists.

int solution() {
  int t = 1;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int a[n];
    int min = 10000000;
    int p = -1;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      if (a[i] < min) {
        min = a[i];
        p = i;
      }
    }
    int x = 0;
    for (int i = 0; i < n / 2; i++) {
      if (x == p) {
        x++;
      }
      printf("%d %d\n", a[x], a[p]);
      x++;
    }
  }
  return 0;
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let mut v = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<u32>().unwrap())
            .collect::<Vec<_>>();
        v.sort_unstable();
        for j in 1..=v.len() / 2 {
            writeln!(o, "{} {}", v[j], v[0]).ok();
        }
    }
}


Spreadsheet

  Your task is to perform a simple table calculation.

  Write a program which reads the number of rows <var>r</var>, columns <var>c</var> and a table of <var>r</var> × <var>c</var> elements, and prints a new table, which includes the total sum for each row and column.

Input

  In the first line, two integers <var>r</var> and <var>c</var> are given. Next, the table is given by <var>r</var> lines, each of which consists of <var>c</var> integers separated by space characters.

Output

  Print the new table of (<var>r</var>+1) × (<var>c</var>+1) elements. Put a single space character between adjacent elements. For each row, print the sum of it's elements in the last column. For each column, print the sum of it's elements in the last row. Print the total sum of the elements at the bottom right corner of the table.

Constraints

 1 ≤ <var>r</var>, <var>c</var> ≤ 100

 0 ≤ an element of the table ≤ 100

Sample Input

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

Sample Output

1 1 3 4 5 14
2 2 2 4 5 15
3 3 0 1 1 8
2 3 4 4 6 19
8 9 9 13 17 56

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

    let mut ite1 = buf.split_whitespace().map(|x| x.parse::<usize>().unwrap());

    let _r = ite1.next().unwrap();
    let c = ite1.next().unwrap();

    let sums = &mut vec![0; c + 1];

    for line in stdin.lock().lines() {
        let line = line.unwrap();

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

        for i in 0..c {
            sums[i] += vec[i];
            print!("{} ", vec[i]);
        }

        let sum = vec.iter().sum::<i32>();
        sums[c] += sum;
        println!("{}", sum);
    }

    println!(
        "{}",
        sums.iter()
            .map(|x| x.to_string())
            .collect::<Vec<_>>()
            .join(" ")
    );
}