Score : <var>200</var> points

Problem Statement

<var>N</var> friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least <var>K</var> centimeters tall.

The <var>i</var>-th friend is <var>h_i</var> centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

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

<var> 1 \le K \le 500 </var>

<var> 1 \le h_i \le 500</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>h_1</var> <var>h_2</var> <var>\ldots</var> <var>h_N</var>

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5

int solution() {
  int i = 0;
  int n = 0;
  int k = 0;
  int h[10000000];
  int result = 0;

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

  while (i < n) {

    if (i < n - 1) {
      scanf("%d ", &h[i]);
    } else {
      scanf("%d", &h[i]);
    }
    if (h[i] >= 1 && h[i] <= 500) {
      if (h[i] >= k) {
        result++;
      } else {
      }
    }
    i++;
  }

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

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let mut iter = buf.split_whitespace();
    let n = match iter.next().unwrap().parse::<i32>() {
        Ok(m) => m,
        _ => panic!(""),
    };
    let k = match iter.next().unwrap().parse::<i32>() {
        Ok(m) => m,
        _ => panic!(""),
    };

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let mut iter = buf.split_whitespace();

    let mut cnt = 0;
    for _a in 0..n {
        let hi = match iter.next().unwrap().parse::<i32>() {
            Ok(m) => m,
            _ => panic!(""),
        };
        if hi >= k {
            cnt += 1;
        }
    }
    println!("{}", cnt);
}


Score : <var>500</var> points

Problem Statement

There are <var>N</var> integers, <var>A_1, A_2, ..., A_N</var>, written on a blackboard.

We will repeat the following operation <var>N-1</var> times so that we have only one integer on the blackboard.

Choose two integers <var>x</var> and <var>y</var> on the blackboard and erase these two integers. Then, write a new integer <var>x-y</var>.

Find the maximum possible value of the final integer on the blackboard and a sequence of operations that maximizes the final integer.

Constraints

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

<var>-10^4 \leq A_i \leq 10^4</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible value <var>M</var> of the final integer on the blackboard, and a sequence of operations <var>x_i, y_i</var> that maximizes the final integer, in the format below.

Here <var>x_i</var> and <var>y_i</var> represent the integers <var>x</var> and <var>y</var> chosen in the <var>i</var>-th operation, respectively.

If there are multiple sequences of operations that maximize the final integer, any of them will be accepted.

<var>M</var>
<var>x_1</var> <var>y_1</var>
<var>:</var>
<var>x_{N-1}</var> <var>y_{N-1}</var>

Sample Input 1

3
1 -1 2

Sample Output 1

4
-1 1
2 -2

If we choose <var>x = -1</var> and <var>y = 1</var> in the first operation, the set of integers written on the blackboard becomes <var>(-2, 2)</var>.

Then, if we choose <var>x = 2</var> and <var>y = -2</var> in the second operation, the set of integers written on the blackboard becomes <var>(4)</var>.

In this case, we have <var>4</var> as the final integer. We cannot end with a greater integer, so the answer is <var>4</var>.

Sample Input 2

3
1 1 1

Sample Output 2

1
1 1
1 0

int solution(void) {

  long n;
  scanf("%ld", &n);
  long a[n];
  for (long i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
  }
  long plus = 0;
  long minus = 0;
  long sum = 0;
  long abs;
  long min = -1;
  long min_i;
  for (long i = 0; i < n; i++) {
    if (a[i] >= 0) {
      plus++;
      abs = a[i];
    } else {
      minus++;
      abs = -a[i];
    }
    sum += abs;
    if (min == -1 || abs < min) {
      min = abs;
      min_i = i;
    }
  }
  if (plus == 0 || minus == 0) {
    sum -= min * 2;
  }
  printf("%ld\n", sum);
  if (plus == 0) {
    for (long i = 0; i < n; i++) {
      if (i == min_i) {
        continue;
      }
      printf("%ld %ld\n", a[min_i], a[i]);
      a[min_i] -= a[i];
    }
  } else if (minus == 0) {
    long other;
    for (long i = 0; i < n; i++) {
      if (i != min_i) {
        other = i;
        break;
      }
    }
    for (long i = 0; i < n; i++) {
      if (i != min_i && i != other) {
        printf("%ld %ld\n", a[min_i], a[i]);
        a[min_i] -= a[i];
      }
    }
    printf("%ld %ld\n", a[other], a[min_i]);
  } else {
    long p_1;
    long m_1;
    for (long i = 0; i < n; i++) {
      if (a[i] >= 0) {
        p_1 = i;
        break;
      }
    }
    for (long i = 0; i < n; i++) {
      if (a[i] < 0) {
        m_1 = i;
        break;
      }
    }
    for (long i = 0; i < n; i++) {
      if (i != p_1 && i != m_1) {
        if (a[i] >= 0) {
          printf("%ld %ld\n", a[m_1], a[i]);
          a[m_1] -= a[i];
        } else {
          printf("%ld %ld\n", a[p_1], a[i]);
          a[p_1] -= a[i];
        }
      }
    }
    printf("%ld %ld\n", a[p_1], a[m_1]);
  }

  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 {
        let v = get!();
        vs.push(v);
    }
    let mut op = vec![];
    vs.sort();

    for i in 1..n - 1 {
        if vs[i] < 0 {
            continue;
        }
        op.push((vs[0], vs[i]));
        vs[0] -= vs[i];
    }
    for i in 1..n - 1 {
        if vs[i] >= 0 {
            break;
        }
        op.push((vs[n - 1], vs[i]));
        vs[n - 1] -= vs[i];
    }
    op.push((vs[n - 1], vs[0]));
    vs[n - 1] -= vs[0];

    println!("{}", vs[n - 1]);
    for &(u, v) in op.iter() {
        println!("{} {}", u, v);
    }
}


Nastia has received an array of $$$n$$$ positive integers as a gift.She calls such an array $$$a$$$ good that for all $$$i$$$ ($$$2 \le i \le n$$$) takes place $$$gcd(a_{i - 1}, a_{i}) = 1$$$, where $$$gcd(u, v)$$$ denotes the greatest common divisor (GCD) of integers $$$u$$$ and $$$v$$$.You can perform the operation: select two different indices $$$i, j$$$ ($$$1 \le i, j \le n$$$, $$$i \neq j$$$) and two integers $$$x, y$$$ ($$$1 \le x, y \le 2 \cdot 10^9$$$) so that $$$\min{(a_i, a_j)} = \min{(x, y)}$$$. Then change $$$a_i$$$ to $$$x$$$ and $$$a_j$$$ to $$$y$$$.The girl asks you to make the array good using at most $$$n$$$ operations.It can be proven that this is always possible.

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

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

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

    let t = lines.next().unwrap().parse::<usize>().unwrap();

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

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

        let (i, x) = it.enumerate().min_by_key(|(_, x)| *x).unwrap();

        let k = if i > 0 { n } else { n - 1 };
        writeln!(&mut output, "{}", k).unwrap();
        if i > 0 {
            writeln!(&mut output, "{} {} {} {}", 1, i + 1, x, x).unwrap();
        }

        for i in 1..n {
            let y = if i % 2 == 0 { x } else { x + 1 };
            writeln!(&mut output, "{} {} {} {}", 1, i + 1, x, y).unwrap();
        }
    }
}


BMI

肥満は多くの成人病の原因として挙げられています。過去においては、一部の例外を除けば、高校生には無縁なものでした。しかし、過度の受験勉強等のために運動不足となり、あるいはストレスによる過食症となることが、非現実的なこととはいえなくなっています。高校生にとっても十分関心を持たねばならない問題になるかもしれません。

そこで、あなたは、保健室の先生の助手となって、生徒のデータから肥満の疑いのある生徒を探し出すプログラムを作成することになりました。

方法は BMI (Body Mass Index) という数値を算出する方法です。BMIは次の式で与えられます。

BMI = 22 が標準的で、25 以上だと肥満の疑いがあります。

各々の生徒の体重、身長の情報から BMI を算出し、25 以上の生徒の学籍番号を出力するプログラムを作成してください。

入力

入力は以下の形式で与えられます。

<var>s1</var>,<var>w1</var>,<var>h1</var>
<var>s2</var>,<var>w2</var>,<var>h2</var>
...
...

<var>si</var> (1 ≤ <var>si</var> ≤ 2,000)、<var>wi</var> (1 ≤ <var>wi</var> ≤ 200)、<var>hi</var> (1.0 ≤ <var>hi</var> ≤ 2.0) はそれぞれ、<var>i</var> 番目の生徒の学籍番号（整数）、体重（実数）、身長（実数）を表します。

生徒の数は 50 を超えません。

出力

BMI が 25 以上の生徒の学籍番号を、入力された順番にそれぞれ１行に出力します。

Sample Input

1001,50.0,1.60
1002,60.0,1.70
1003,70.0,1.80
1004,80.0,1.70
1005,90.0,1.60

Output for the Sample Input

1004
1005

int solution(void) {
  int num[50];
  int c = 0;
  double h[50];
  double w[50];

  while (scanf("%d,%lf,%lf", &num[c], &w[c], &h[c]) != EOF) {
    if ((w[c] / (h[c] * h[c])) >= 25) {
      printf("%d\n", num[c]);
    }
    c++;
  }

  return 0;
}

fn solution() {
    loop {
        let mut input = String::new();
        match std::io::stdin().read_line(&mut input).unwrap() {
            0 => break,
            _ => {
                let v: Vec<&str> = input.trim().split(',').collect();
                let (w, h): (f64, f64) = (v[1].parse().unwrap(), v[2].parse().unwrap());
                if w / (h * h) >= 25.0 {
                    println!("{}", v[0])
                }
            }
        };
    }
}


You are given three arrays $$$a$$$, $$$b$$$ and $$$c$$$. Initially, array $$$a$$$ consists of $$$n$$$ elements, arrays $$$b$$$ and $$$c$$$ are empty.You are performing the following algorithm that consists of two steps:   Step $$$1$$$: while $$$a$$$ is not empty, you take the last element from $$$a$$$ and move it in the middle of array $$$b$$$. If $$$b$$$ currently has odd length, you can choose: place the element from $$$a$$$ to the left or to the right of the middle element of $$$b$$$. As a result, $$$a$$$ becomes empty and $$$b$$$ consists of $$$n$$$ elements.  Step $$$2$$$: while $$$b$$$ is not empty, you take the middle element from $$$b$$$ and move it to the end of array $$$c$$$. If $$$b$$$ currently has even length, you can choose which of two middle elements to take. As a result, $$$b$$$ becomes empty and $$$c$$$ now consists of $$$n$$$ elements.  Refer to the Note section for examples.Can you make array $$$c$$$ sorted in non-decreasing order?

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

  while (cases--) {
    int arrLen;
    scanf("%d", &arrLen);

    int array[arrLen];
    for (int index = 0; index < arrLen; index++) {
      scanf("%d ", array + index);
    }

    if (arrLen % 2 == 0) {
      for (int index = 0; index < arrLen; index += 2) {
        if (array[index] > array[index + 1]) {
          int backup = array[index];
          array[index] = array[index + 1];
          array[index + 1] = backup;
        }
      }
    } else {
      for (int index = 1; index < arrLen; index += 2) {
        if (array[index] > array[index + 1]) {
          int backup = array[index];
          array[index] = array[index + 1];
          array[index + 1] = backup;
        }
      }
    }

    bool result = true;
    for (int index = 0; index < arrLen - 1; index++) {
      if (array[index] > array[index + 1]) {
        result = false;
        break;
      }
    }
    if (result) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).ok();
    let mut output = String::new();
    let mut input = input.split_ascii_whitespace().flat_map(str::parse);
    let t = input.next().unwrap();
    for _ in 0..t {
        let n = input.next().unwrap();
        let a: Vec<_> = input.by_ref().take(n).map(|x| x as u32).collect();
        let mut is_sorted = true;
        let mut max = 1_000_000;
        for chunk in a.rchunks(2) {
            match *chunk {
                [a] => {
                    if a > max {
                        is_sorted = false;
                        break;
                    } else {
                        max = a;
                    }
                }
                [a, b] => {
                    if a > b {
                        if a > max {
                            is_sorted = false;
                            break;
                        }
                        max = b;
                    } else {
                        if b > max {
                            is_sorted = false;
                            break;
                        }
                        max = a;
                    }
                }
                _ => {}
            }
        }
        if is_sorted {
            output.push_str("YES\n");
        } else {
            output.push_str("NO\n");
        }
    }
    print!("{output}");
}


Factorial

Write a program which reads an integer <var>n</var> and prints the factorial of <var>n</var>. You can assume that <var>n</var> ≤ 20.

Input

An integer <var>n</var> (1 ≤ <var>n</var> ≤ 20) in a line.

Output

Print the factorial of <var>n</var> in a line.

Sample Input

5

Output for the Sample Input

120

int solution(void) {
  long long int f = 1;
  int a = 0;
  scanf("%d", &a);
  while (a) {
    f *= a;
    a--;
  }
  printf("%lld\n", f);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<u64>().unwrap();
    let mut ans = 1;
    for i in 2..n + 1 {
        ans *= i;
    }
    println!("{}", ans);
}


Score : <var>300</var> points

Problem Statement

A railroad running from west to east in Atcoder Kingdom is now complete.

There are <var>N</var> stations on the railroad, numbered <var>1</var> through <var>N</var> from west to east.

Tomorrow, the opening ceremony of the railroad will take place.

On this railroad, for each integer <var>i</var> such that <var>1≤i≤N-1</var>, there will be trains that run from Station <var>i</var> to Station <var>i+1</var> in <var>C_i</var> seconds. No other trains will be operated.

The first train from Station <var>i</var> to Station <var>i+1</var> will depart Station <var>i</var> <var>S_i</var> seconds after the ceremony begins. Thereafter, there will be a train that departs Station <var>i</var> every <var>F_i</var> seconds.

Here, it is guaranteed that <var>F_i</var> divides <var>S_i</var>.

That is, for each Time <var>t</var> satisfying <var>S_i≤t</var> and <var>t％F_i=0</var>, there will be a train that departs Station <var>i</var> <var>t</var> seconds after the ceremony begins and arrives at Station <var>i+1</var> <var>t+C_i</var> seconds after the ceremony begins, where <var>A％B</var> denotes <var>A</var> modulo <var>B</var>, and there will be no other trains.

For each <var>i</var>, find the earliest possible time we can reach Station <var>N</var> if we are at Station <var>i</var> when the ceremony begins, ignoring the time needed to change trains.

Constraints

<var>1≤N≤500</var>

<var>1≤C_i≤100</var>

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

<var>1≤F_i≤10</var>

<var>S_i％F_i=0</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>C_1</var> <var>S_1</var> <var>F_1</var>
<var>:</var>
<var>C_{N-1}</var> <var>S_{N-1}</var> <var>F_{N-1}</var>

Output

Print <var>N</var> lines. Assuming that we are at Station <var>i</var> <var>(1≤i≤N)</var> when the ceremony begins, if the earliest possible time we can reach Station <var>N</var> is <var>x</var> seconds after the ceremony begins, the <var>i</var>-th line should contain <var>x</var>.

Sample Input 1

3
6 5 1
1 10 1

Sample Output 1

12
11
0

We will travel from Station <var>1</var> as follows:

<var>5</var> seconds after the beginning: take the train to Station <var>2</var>.

<var>11</var> seconds: arrive at Station <var>2</var>.

<var>11</var> seconds: take the train to Station <var>3</var>.

<var>12</var> seconds: arrive at Station <var>3</var>.

We will travel from Station <var>2</var> as follows:

<var>10</var> seconds: take the train to Station <var>3</var>.

<var>11</var> seconds: arrive at Station <var>3</var>.

Note that we should print <var>0</var> for Station <var>3</var>.

Sample Input 2

4
12 24 6
52 16 4
99 2 2

Sample Output 2

187
167
101
0

Sample Input 3

4
12 13 1
44 17 17
66 4096 64

Sample Output 3

4162
4162
4162
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() - 1;
    let mut t = Vec::new();
    for _ in 0..n {
        let c = it.next().unwrap().parse::<i64>().unwrap();
        let s = it.next().unwrap().parse::<i64>().unwrap();
        let f = it.next().unwrap().parse::<i64>().unwrap();
        t.push((c, s, f));
    }
    for i in 0..n {
        let mut cur = 0;
        for j in i..n {
            cur = std::cmp::max(t[j].1, cur + t[j].2 - 1) / t[j].2 * t[j].2 + t[j].0;
        }
        println!("{}", cur);
    }
    println!("0");
}


Sum of Numbers

  Write a program which reads an integer and prints sum of its digits.

Input

  The input consists of multiple datasets. For each dataset, an integer <var>x</var> is given in a line. The number of digits in <var>x</var> does not exceed 1000.

The input ends with a line including single zero. Your program should not process for this terminal symbol.

Output

  For each dataset, print the sum of digits in <var>x</var>.

Sample Input

123
55
1000
0

Sample Output

6
10
1

int solution(void) {
  char str[1001] = {0};
  int i = 0;
  int sum = 0;

  while (1) {
    scanf("%c", &str[i]);

    if (str[i] == '\n') {
      if (i == 1 && str[0] == '0') {
        break;
      }
      printf("%d\n", sum);
      sum = 0;
      i = 0;

    } else {
      sum += str[i] - 0x30;
      i++;
    }
  }

  return 0;
}

fn solution() {
    loop {
        let mut b = String::new();
        let s = std::io::stdin();
        s.read_line(&mut b).unwrap();
        if b.trim() == "0" {
            break;
        }
        println!(
            "{}",
            b.trim()
                .chars()
                .map(|c| c.to_digit(10).unwrap())
                .sum::<u32>()
        );
    }
}


You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?

int solution() {
  int t;
  scanf("%d", &t);
  long long output[t];
  for (int i = 0; i < t; i++) {
    long long n;
    long long k;
    scanf("%lld %lld", &n, &k);
    long long mult = k;
    while (mult / n == 0) {
      if (n % k) {
        mult = (n / k) * k + k;
      } else {
        mult = (n / k) * k;
      }
    }
    if (mult % n == 0) {
      output[i] = mult / n;
    } else {
      output[i] = mult / n + 1;
    }
  }
  for (int k = 0; k < t; k++) {
    printf("%lld\n", output[k]);
  }
}

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

    input.read_line(&mut buf).unwrap();
    let t = buf.trim().parse().unwrap();

    for _ in 0..t {
        buf.clear();
        input.read_line(&mut buf).unwrap();
        let mut words = buf.trim().split_ascii_whitespace();
        let n: usize = words.next().unwrap().parse().unwrap();
        let k: usize = words.next().unwrap().parse().unwrap();

        let mut target = (n / k) * k;
        if target < n {
            target += k;
        }

        let ans = if target.is_multiple_of(n) {
            target / n
        } else {
            target / n + 1
        };

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


Score : <var>400</var> points

Problem Statement

We have a sequence of length <var>N</var>, <var>a = (a_1, a_2, ..., a_N)</var>.
Each <var>a_i</var> is a positive integer.

Snuke's objective is to permute the element in <var>a</var> so that the following condition is satisfied:

For each <var>1 ≤ i ≤ N - 1</var>, the product of <var>a_i</var> and <var>a_{i + 1}</var> is a multiple of <var>4</var>.

Determine whether Snuke can achieve his objective.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

If Snuke can achieve his objective, print Yes; otherwise, print No.

Sample Input 1

3
1 10 100

Sample Output 1

Yes

One solution is <var>(1, 100, 10)</var>.

Sample Input 2

4
1 2 3 4

Sample Output 2

No

It is impossible to permute <var>a</var> so that the condition is satisfied.

Sample Input 3

3
1 4 1

Sample Output 3

Yes

The condition is already satisfied initially.

Sample Input 4

2
1 1

Sample Output 4

No

Sample Input 5

6
2 7 1 8 2 8

Sample Output 5

Yes

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

    let mut x: isize = 0;
    let mut y: isize = 0;
    let mut z: isize = 0;

    for i in &a {
        if *i % 4 == 0 {
            x += 1;
        } else if *i % 2 == 0 {
            y += 1;
        } else {
            z += 1;
        }
    }

    if y == 0 {
        z -= 1;
    }
    println!("{}", if z <= x { "Yes" } else { "No" });
}


Score : <var>300</var> points

Problem Statement

Snuke has decided to play with a six-sided die. Each of its six sides shows an integer <var>1</var> through <var>6</var>, and two numbers on opposite sides always add up to <var>7</var>.

Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation:

Operation: Rotate the die <var>90°</var> toward one of the following directions: left, right, front (the die will come closer) and back (the die will go farther). Then, obtain <var>y</var> points where <var>y</var> is the number written in the side facing upward.

For example, let us consider the situation where the side showing <var>1</var> faces upward, the near side shows <var>5</var> and the right side shows <var>4</var>, as illustrated in the figure.
If the die is rotated toward the right as shown in the figure, the side showing <var>3</var> will face upward.
Besides, the side showing <var>4</var> will face upward if the die is rotated toward the left, the side showing <var>2</var> will face upward if the die is rotated toward the front, and the side showing <var>5</var> will face upward if the die is rotated toward the back.

Find the minimum number of operation Snuke needs to perform in order to score at least <var>x</var> points in total.

Constraints

<var>1 ≦ x ≦ 10^{15}</var>

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

Input

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

<var>x</var>

Output

Print the answer.

Sample Input 1

7

Sample Output 1

2

Sample Input 2

149696127901

Sample Output 2

27217477801

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

    let x: u64 = s.trim().parse().unwrap();

    let r = x / 11;
    let m = x % 11;

    println!(
        "{}",
        if m == 0 {
            r * 2
        } else if m > 6 {
            r * 2 + 2
        } else {
            r * 2 + 1
        }
    );
}


A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

int solution() {
  int n_case = 0;
  scanf("%d", &n_case);
  long long w = 0;
  long long h = 0;
  long long w_up[2 * 100000];
  long long k = 0;
  long long min = 0;
  long long max = 0;
  long long a[4];
  long long final = 0;
  for (int ii = 0; ii < n_case; ++ii) {
    scanf("%lld", &w);
    scanf("%lld", &h);
    scanf("%lld", &k);
    int i = 0;
    for (i = 0; i < k; i++) {
      scanf("%lld", &w_up[i]);
    }

    min = w_up[0];
    max = w_up[k - 1];
    a[0] = (max - min) * h;

    for (i = 0; i < k; i++) {
      w_up[i] = 0;
    }

    scanf("%lld", &k);
    for (i = 0; i < k; i++) {
      scanf("%lld", &w_up[i]);
    }

    min = w_up[0];
    max = w_up[k - 1];
    a[1] = (max - min) * h;

    for (i = 0; i < k; i++) {
      w_up[i] = 0;
    }

    scanf("%lld", &k);
    for (i = 0; i < k; i++) {
      scanf("%lld", &w_up[i]);
    }

    min = w_up[0];
    max = w_up[k - 1];
    a[2] = (max - min) * w;

    for (i = 0; i < k; i++) {
      w_up[i] = 0;
    }

    scanf("%lld", &k);
    for (i = 0; i < k; i++) {
      scanf("%lld", &w_up[i]);
    }

    min = w_up[0];
    max = w_up[k - 1];
    a[3] = (max - min) * w;

    final = a[0];
    for (i = 1; i < 4; ++i) {
      if (a[i] > final) {
        final = a[i];
      }
    }
    printf("%lld\n", final);
  }
}

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

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

    for _i in 0..n {
        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }
        let p: Vec<&str> = buf.trim().split(" ").collect();

        let w: u128 = p[0].parse().unwrap();
        let h: u128 = p[1].parse().unwrap();

        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }
        let line1: Vec<u128> = buf
            .trim()
            .split(" ")
            .skip(1)
            .map(|s| s.parse::<u128>().unwrap())
            .collect();

        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }
        let line2: Vec<u128> = buf
            .trim()
            .split(" ")
            .skip(1)
            .map(|s| s.parse::<u128>().unwrap())
            .collect();

        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }
        let col1: Vec<u128> = buf
            .trim()
            .split(" ")
            .skip(1)
            .map(|s| s.parse::<u128>().unwrap())
            .collect();

        let mut buf = String::new();
        let r = stdin.read_line(&mut buf);
        match r {
            Ok(_) => {}
            _ => panic!("could not read from stdin"),
        }
        let col2: Vec<u128> = buf
            .trim()
            .split(" ")
            .skip(1)
            .map(|s| s.parse::<u128>().unwrap())
            .collect();

        let a1 = std::cmp::max(
            line1[line1.len() - 1] - line1[0],
            line2[line2.len() - 1] - line2[0],
        ) * h;
        let a2 = std::cmp::max(
            col1[col1.len() - 1] - col1[0],
            col2[col2.len() - 1] - col2[0],
        ) * w;

        println!("{}", std::cmp::max(a1, a2));
    }
}


David was given a red checkered rectangle of size $$$n \times m$$$. But he doesn't like it. So David cuts the original or any other rectangle piece obtained during the cutting into two new pieces along the grid lines. He can do this operation as many times as he wants.As a result, he will get a set of rectangles. Rectangles $$$1 \times 1$$$ are forbidden.David also knows how to paint the cells blue. He wants each rectangle from the resulting set of pieces to be colored such that any pair of adjacent cells by side (from the same piece) have different colors.What is the minimum number of cells David will have to paint?

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 [n, m] = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<u32>().unwrap())
            .collect::<Vec<_>>()[..]
        {
            writeln!(o, "{}", (n * m - 1) / 3 + 1).ok();
        }
    }
}


Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.

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

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

    let n: i32 = buf.trim().parse::<i32>().unwrap();

    let mut edges: Vec<Vec<i32>> = Vec::new();
    for _idx in 0..n {
        let mut buf = String::new();
        stdin.read_line(&mut buf);

        let edge: Vec<i32> = buf
            .split_whitespace()
            .map(|x| x.trim().parse::<i32>().unwrap())
            .collect();

        edges.push(edge);
    }

    let mut nodeToEdgeIndices: HashMap<i32, Vec<i32>> = HashMap::new();

    for edgeIdx in 0..edges.len() {
        for node in edges.get(edgeIdx).unwrap() {
            nodeToEdgeIndices
                .entry(*node)
                .or_default()
                .push(edgeIdx as i32);
        }
    }

    let mut centerNode = -1i32;
    for (node, edgeIndices) in nodeToEdgeIndices.iter() {
        if edgeIndices.len() > 2 {
            if centerNode >= 0 {
                println!("No");
                return;
            }
            centerNode = *node;
        }
    }
    if centerNode < 0 {
        centerNode = *nodeToEdgeIndices.keys().next().unwrap();
    }

    println!("Yes");

    let centerEdges: Vec<i32> = nodeToEdgeIndices.get(&centerNode).unwrap().to_vec();
    println!("{}", centerEdges.len());
    for edgeIdx in centerEdges {
        let mut endNode = centerNode;
        let mut endEdgeIdx = edgeIdx;
        loop {
            let edge = edges.get(endEdgeIdx as usize).unwrap();
            if endNode == edge[0] {
                endNode = edge[1];
            } else {
                endNode = edge[0];
            }

            let edgeIndices = nodeToEdgeIndices.get(&endNode).unwrap();
            if edgeIndices.len() < 2 {
                break;
            }
            if endEdgeIdx == edgeIndices[0] {
                endEdgeIdx = edgeIndices[1];
            } else {
                endEdgeIdx = edgeIndices[0];
            }
        }
        println!("{} {}", centerNode, endNode);
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $$$a$$$ to make it a good array. Recall that the prefix of the array $$$a=[a_1, a_2, \dots, a_n]$$$ is a subarray consisting several first elements: the prefix of the array $$$a$$$ of length $$$k$$$ is the array $$$[a_1, a_2, \dots, a_k]$$$ ($$$0 \le k \le n$$$).The array $$$b$$$ of length $$$m$$$ is called good, if you can obtain a non-decreasing array $$$c$$$ ($$$c_1 \le c_2 \le \dots \le c_{m}$$$) from it, repeating the following operation $$$m$$$ times (initially, $$$c$$$ is empty):  select either the first or the last element of $$$b$$$, remove it from $$$b$$$, and append it to the end of the array $$$c$$$. For example, if we do $$$4$$$ operations: take $$$b_1$$$, then $$$b_{m}$$$, then $$$b_{m-1}$$$ and at last $$$b_2$$$, then $$$b$$$ becomes $$$[b_3, b_4, \dots, b_{m-3}]$$$ and $$$c =[b_1, b_{m}, b_{m-1}, b_2]$$$.Consider the following example: $$$b = [1, 2, 3, 4, 4, 2, 1]$$$. This array is good because we can obtain non-decreasing array $$$c$$$ from it by the following sequence of operations:  take the first element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2, 1]$$$, $$$c = [1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2]$$$, $$$c = [1, 1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4]$$$, $$$c = [1, 1, 2]$$$;  take the first element of $$$b$$$, so $$$b = [3, 4, 4]$$$, $$$c = [1, 1, 2, 2]$$$;  take the first element of $$$b$$$, so $$$b = [4, 4]$$$, $$$c = [1, 1, 2, 2, 3]$$$;  take the last element of $$$b$$$, so $$$b = [4]$$$, $$$c = [1, 1, 2, 2, 3, 4]$$$;  take the only element of $$$b$$$, so $$$b = []$$$, $$$c = [1, 1, 2, 2, 3, 4, 4]$$$ — $$$c$$$ is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of $$$a$$$ to delete (erase), to make $$$a$$$ to be a good array. Note that the required length can be $$$0$$$.You have to answer $$$t$$$ independent test cases.

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

    'outer: 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 a: Vec<usize> = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let iter = buf.split_whitespace();
            iter.map(|x| x.parse().unwrap()).collect()
        };

        let mut x = *a.last().unwrap();
        let mut b = true;
        for i in (0..n).rev() {
            if b && a[i] >= x {
                x = a[i];
            } else if a[i] <= x {
                x = a[i];
                b = false;
            } else {
                println!("{}", i + 1);
                continue 'outer;
            }
        }
        println!("0");
    }
}


Score : <var>400</var> points

Problem Statement

Given are integers <var>A</var>, <var>B</var>, and <var>N</var>.

Find the maximum possible value of <var>floor(Ax/B) - A × floor(x/B)</var> for a non-negative integer <var>x</var> not greater than <var>N</var>.

Here <var>floor(t)</var> denotes the greatest integer not greater than the real number <var>t</var>.

Constraints

<var>1 ≤ A ≤ 10^{6}</var>

<var>1 ≤ B ≤ 10^{12}</var>

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible value of <var>floor(Ax/B) - A × floor(x/B)</var> for a non-negative integer <var>x</var> not greater than <var>N</var>, as an integer.

Sample Input 1

5 7 4

Sample Output 1

2

When <var>x=3</var>, <var>floor(Ax/B)-A×floor(x/B) = floor(15/7) - 5×floor(3/7) = 2</var>. This is the maximum value possible.

Sample Input 2

11 10 9

Sample Output 2

9

int solution() {
  long int x = 0;
  double A;
  double B;
  double N;
  scanf("%lf %lf %lf", &A, &B, &N);
  if (N >= B - 1) {
    x = A * ((B - 1) / B);
    printf("%ld", x);
  } else {
    x = A * (N / B);
    printf("%ld", x);
  }

  return 0;
}

fn solution() {
    let mut line = String::new();
    std::io::stdin().read_to_string(&mut line);
    let mut iter = line.split_whitespace();
    let a: i64 = iter.next().unwrap().parse().unwrap();
    let b: i64 = iter.next().unwrap().parse().unwrap();
    let n: i64 = iter.next().unwrap().parse().unwrap();
    if b <= n {
        let x = b - 1;
        println!("{}", a * x / b - a * (x / b))
    } else {
        let x = n;
        println!("{}", a * x / b - a * (x / b))
    }
}


Score : <var>400</var> points

Problem Statement

We say that a odd number <var>N</var> is similar to 2017 when both <var>N</var> and <var>(N+1)/2</var> are prime.

You are given <var>Q</var> queries.

In the <var>i</var>-th query, given two odd numbers <var>l_i</var> and <var>r_i</var>, find the number of odd numbers <var>x</var> similar to 2017 such that <var>l_i ≤ x ≤ r_i</var>.

Constraints

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

<var>1≤l_i≤r_i≤10^5</var>

<var>l_i</var> and <var>r_i</var> are odd.

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>Q</var>
<var>l_1</var> <var>r_1</var>
<var>:</var>
<var>l_Q</var> <var>r_Q</var>

Output

Print <var>Q</var> lines. The <var>i</var>-th line <var>(1≤i≤Q)</var> should contain the response to the <var>i</var>-th query.

Sample Input 1

1
3 7

Sample Output 1

2

<var>3</var> is similar to 2017, since both <var>3</var> and <var>(3+1)/2=2</var> are prime.

<var>5</var> is similar to 2017, since both <var>5</var> and <var>(5+1)/2=3</var> are prime.

<var>7</var> is not similar to 2017, since <var>(7+1)/2=4</var> is not prime, although <var>7</var> is prime.

Thus, the response to the first query should be <var>2</var>.

Sample Input 2

4
13 13
7 11
7 11
2017 2017

Sample Output 2

1
0
0
1

Note that <var>2017</var> is also similar to 2017.

Sample Input 3

6
1 53
13 91
37 55
19 51
73 91
13 49

Sample Output 3

4
4
1
1
1
2

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

    let mut is_prime: Vec<bool> = vec![true; 100010];
    let mut cumsum: Vec<u64> = vec![0; 100010];
    is_prime[0] = false;
    is_prime[1] = false;
    for i in 2..100005 {
        if is_prime[i] {
            let mut j = i * 2;
            while j < 100005 {
                is_prime[j] = false;
                j += i;
            }
        }
    }
    for i in 1..100005 {
        if is_prime[i] && is_prime[(i + 1) >> 1] {
            cumsum[i] += 1;
        }
    }
    for i in 0..100005 {
        cumsum[i + 1] += cumsum[i];
    }

    for _ in 0..q {
        let l: usize = itr.next().unwrap().parse().unwrap();
        let r: usize = itr.next().unwrap().parse().unwrap();
        writeln!(out, "{}", cumsum[r] - cumsum[l - 1]).unwrap();
    }
    stdout().write_all(&out).unwrap();
}


Score : <var>100</var> points

Problem Statement

Takahashi wants to print a document with <var>N</var> pages double-sided, where two pages of data can be printed on one sheet of paper.

At least how many sheets of paper does he need?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer.

Sample Input 1

5

Sample Output 1

3

By printing the <var>1</var>-st, <var>2</var>-nd pages on the <var>1</var>-st sheet, <var>3</var>-rd and <var>4</var>-th pages on the <var>2</var>-nd sheet, and <var>5</var>-th page on the <var>3</var>-rd sheet, we can print all the data on <var>3</var> sheets of paper.

Sample Input 2

2

Sample Output 2

1

Sample Input 3

100

Sample Output 3

50

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("error");
    let n: i32 = match buf.trim().parse() {
        Ok(num) => num,
        Err(_) => panic!("error"),
    };
    println!("{}", n / 2 + n % 2);
}


Mishka got an integer array $$$a$$$ of length $$$n$$$ as a birthday present (what a surprise!).Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:  Replace each occurrence of $$$1$$$ in the array $$$a$$$ with $$$2$$$;  Replace each occurrence of $$$2$$$ in the array $$$a$$$ with $$$1$$$;  Replace each occurrence of $$$3$$$ in the array $$$a$$$ with $$$4$$$;  Replace each occurrence of $$$4$$$ in the array $$$a$$$ with $$$3$$$;  Replace each occurrence of $$$5$$$ in the array $$$a$$$ with $$$6$$$;  Replace each occurrence of $$$6$$$ in the array $$$a$$$ with $$$5$$$;  $$$\dots$$$  Replace each occurrence of $$$10^9 - 1$$$ in the array $$$a$$$ with $$$10^9$$$;  Replace each occurrence of $$$10^9$$$ in the array $$$a$$$ with $$$10^9 - 1$$$. Note that the dots in the middle of this algorithm mean that Mishka applies these replacements for each pair of adjacent integers ($$$2i - 1, 2i$$$) for each $$$i \in\{1, 2, \ldots, 5 \cdot 10^8\}$$$ as described above.For example, for the array $$$a = [1, 2, 4, 5, 10]$$$, the following sequence of arrays represents the algorithm: $$$[1, 2, 4, 5, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$1$$$ with $$$2$$$) $$$\rightarrow$$$ $$$[2, 2, 4, 5, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$2$$$ with $$$1$$$) $$$\rightarrow$$$ $$$[1, 1, 4, 5, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$3$$$ with $$$4$$$) $$$\rightarrow$$$ $$$[1, 1, 4, 5, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$4$$$ with $$$3$$$) $$$\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$5$$$ with $$$6$$$) $$$\rightarrow$$$ $$$[1, 1, 3, 6, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$6$$$ with $$$5$$$) $$$\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\rightarrow$$$ $$$\dots$$$ $$$\rightarrow$$$ $$$[1, 1, 3, 5, 10]$$$ $$$\rightarrow$$$ (replace all occurrences of $$$10$$$ with $$$9$$$) $$$\rightarrow$$$ $$$[1, 1, 3, 5, 9]$$$. The later steps of the algorithm do not change the array.Mishka is very lazy and he doesn't want to apply these changes by himself. But he is very interested in their result. Help him find it.

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

    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let nums: Vec<u32> = buf
        .split_whitespace()
        .map(|elem| elem.parse().unwrap())
        .collect();

    for num in nums {
        if num % 2 == 0 {
            print!("{} ", num - 1);
        } else {
            print!("{} ", num);
        }
    }
}


Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day — exactly $$$2$$$ problems, during the third day — exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?

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

    let contests = input
        .trim()
        .parse::<i32>()
        .expect("CONTESTS::parse to i32 failed");
    input.clear();
    std::io::stdin()
        .read_line(&mut input)
        .expect("INPUT::read line failed");

    let mut vec = vec![];
    let input = input.trim().split(' ');

    for i in input {
        vec.push(i.parse::<i32>().unwrap());
    }

    let mut max_days = 1;
    vec.sort();
    for i in 0..contests {
        if vec[i as usize] >= max_days {
            max_days += 1;
        }
    }

    println!("{}", max_days - 1);
}


Madoka finally found the administrator password for her computer. Her father is a well-known popularizer of mathematics, so the password is the answer to the following problem.Find the maximum decimal number without zeroes and with no equal digits in a row, such that the sum of its digits is $$$n$$$.Madoka is too tired of math to solve it herself, so help her to solve this problem!

int solution() {
  char result[1000] = {0};
  int t = 0;
  int n = 0;
  int bd = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    memset(result, 0, 1000);
    bd = 0;
    scanf("%d", &n);
    if (n == 1) {
      printf("1");
      printf("\n");
    } else if (n == 2) {
      printf("2");
      printf("\n");
    } else {
      if (n % 3 == 0) {
        for (int i2 = 0; i2 < (n / 3); i2++) {

          result[bd] = '2';
          bd++;
          result[bd] = '1';
          bd++;
        }
        printf("%s", result);
        printf("\n");

      } else {
        if (n % 3 == 2) {

          result[bd] = '2';
          bd++;
          for (int i3 = 0; i3 < (n / 3); i3++) {

            result[bd] = '1';
            bd++;
            result[bd] = '2';
            bd++;
          }
          printf("%s", result);
          printf("\n");
        } else {

          result[bd] = '1';
          bd++;
          for (int i4 = 0; i4 < (n / 3); i4++) {

            result[bd] = '2';
            bd++;
            result[bd] = '1';
            bd++;
          }
          printf("%s", result);
          printf("\n");
        }
      }
    }
  }
  return 0;
}

fn solution() {
    let mut events = String::new();
    io::stdin()
        .read_line(&mut events)
        .expect("Failed to read input");
    let events: i64 = events.trim().parse().expect("Invalid input");

    let mut count = 0;
    while count < events {
        let mut number = String::new();
        io::stdin()
            .read_line(&mut number)
            .expect("Failed to read input");
        let number: i64 = number.trim().parse().expect("Invald input");

        let mut maxdecimal = if number % 3 == 1 { vec![1] } else { vec![2] };

        while maxdecimal.iter().clone().sum::<i64>() < number {
            if maxdecimal.last().unwrap() == &1 {
                maxdecimal.push(2)
            } else {
                maxdecimal.push(1)
            }
        }

        println!(
            "{}",
            maxdecimal.iter().map(|i| i.to_string()).collect::<String>()
        );
        count += 1
    }
}


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

int solution() {
  long int n;
  scanf("%ld", &n);
  long int arrI[n];
  long int arrM[300000] = {0};
  int i;
  int s;
  int m;
  int b;
  for (i = 0; i < n; i++) {
    arrI[i] = 0;
  }
  int j;
  int k;
  s = 0;
  m = 0;
  b = 0;
  long long int sumS = 0;
  long long int sumB = 0;
  long long int x;
  for (i = 0; i < n; i++) {
    scanf("%lld", &x);
    if (x < 1) {
      sumS += x;
      s++;
    } else if (x > n) {
      sumB += x;
      b++;
    } else {
      if (arrI[x - 1] == 0) {
        arrI[x - 1]++;
      } else {
        arrM[x - 1]++;
        m++;
      }
    }
  }

  long long int moves = 0;
  long long int sumTemp = 0;
  i = 0;
  int c = 0;
  while (c < s) {
    if (arrI[i] == 0) {
      c++;
      sumTemp += i + 1;
      arrI[i] = 1;
    }
    i++;
  }
  c = 0;
  i = 0;
  moves += sumTemp - sumS;

  long long int arrN[m][2];
  int y = 0;
  for (i = 0; y < m && i < 300000; i++) {
    if (arrM[i] != 0) {
      arrN[y][0] = i;
      arrN[y][1] = arrM[i];
      y++;
    }
  }
  y = 0;
  for (i = 0; y < m && i < n; i++) {
    if (arrI[i] == 0) {
      if (arrN[y][1] > 0) {
        arrI[i] = 1;
        moves += abs(arrN[y][0] - i);
        arrN[y][1]--;
        if (arrN[y][1] == 0) {
          y++;
        }
      }
    }
  }

  sumS = 0;
  for (i = 0; i < n; i++) {
    if (arrI[i] == 0) {
      sumS += i + 1;
    }
  }
  moves += sumB - sumS;
  printf("%lld", moves);
  return 0;
}

fn solution() {
    let mut v: Vec<i32> = BufReader::new(io::stdin())
        .lines()
        .nth(1)
        .unwrap()
        .unwrap()
        .split_whitespace()
        .map(|s| s.parse::<i32>().unwrap())
        .collect();
    v.sort();
    let mut res = 0u64;
    for (i, itm) in v.iter().enumerate() {
        res += (i as i32 - itm + 1).unsigned_abs() as u64;
    }
    println!("{}", res);
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> people standing in a queue from west to east.

Given is a string <var>S</var> of length <var>N</var> representing the directions of the people.
The <var>i</var>-th person from the west is facing west if the <var>i</var>-th character of <var>S</var> is L, and east if that character of <var>S</var> is R.

A person is happy if the person in front of him/her is facing the same direction.
If no person is standing in front of a person, however, he/she is not happy.

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

Operation: Choose integers <var>l</var> and <var>r</var> such that <var>1 \leq l \leq r \leq N</var>, and rotate by <var>180</var> degrees the part of the queue: the <var>l</var>-th, <var>(l+1)</var>-th, <var>...</var>, <var>r</var>-th persons. That is, for each <var>i = 0, 1, ..., r-l</var>, the <var>(l + i)</var>-th person from the west will stand the <var>(r - i)</var>-th from the west after the operation, facing east if he/she is facing west now, and vice versa.

What is the maximum possible number of happy people you can have?

Constraints

<var>N</var> is an integer satisfying <var>1 \leq N \leq 10^5</var>.

<var>K</var> is an integer satisfying <var>1 \leq K \leq 10^5</var>.

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

Each character of <var>S</var> is L or R.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>S</var>

Output

Print the maximum possible number of happy people after at most <var>K</var> operations.

Sample Input 1

6 1
LRLRRL

Sample Output 1

3

If we choose <var>(l, r) = (2, 5)</var>, we have LLLRLL, where the <var>2</var>-nd, <var>3</var>-rd, and <var>6</var>-th persons from the west are happy.

Sample Input 2

13 3
LRRLRLRRLRLLR

Sample Output 2

9

Sample Input 3

10 1
LLLLLRRRRR

Sample Output 3

9

Sample Input 4

9 2
RRRLRLRLL

Sample Output 4

7

int solution(void) {

  int n;
  int k;
  char s[199999];
  int ans = 0;
  int tmp = 0;

  scanf("%d %d", &n, &k);
  scanf("%s", s);

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

    if (s[i] == 'L') {

      if (i >= 1) {

        if (s[i - 1] == 'L') {

          tmp += 1;
        }
      }

    } else {

      if (i < n) {

        if (s[i + 1] == 'R') {

          tmp += 1;
        }
      }
    }
  }

  tmp += k * 2;

  if (tmp > n - 1) {

    ans = n - 1;

  } else {

    ans = tmp;
  }

  printf("%d", ans);

  return 0;
}

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let k: usize = s.next().unwrap().parse().unwrap();
    let mut s: Vec<_> = s.next().unwrap().chars().collect();
    s.dedup();
    println!("{}", n - std::cmp::max(1, s.len().saturating_sub(2 * k)));
}


Score : <var>500</var> points

Problem Statement

Find the number of integers between <var>1</var> and <var>N</var> (inclusive) that contains exactly <var>K</var> non-zero digits when written in base ten.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>K</var>

Output

Print the count.

Sample Input 1

100
1

Sample Output 1

19

The following <var>19</var> integers satisfy the condition:

<var>1,2,3,4,5,6,7,8,9,10,20,30,40,50,60,70,80,90,100</var>

Sample Input 2

25
2

Sample Output 2

14

The following <var>14</var> integers satisfy the condition:

<var>11,12,13,14,15,16,17,18,19,21,22,23,24,25</var>

Sample Input 3

314159
2

Sample Output 3

937

Sample Input 4

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
3

Sample Output 4

117879300

fn solution() {
    input! {
        N: chars,
        K: usize,
    }
    let mut dp = [[[0; 2]; 4]; 101];
    dp[0][0][0] = 1;
    for (i, &c) in N.iter().enumerate() {
        let d = c as i32 - '0' as i32;
        for j in 0..(K + 1) {
            for k in 0..2 {
                for di in 0..10 {
                    let (mut ni, mut nj, mut nk) = (i, j, k);
                    ni += 1;
                    if di != 0 {
                        nj += 1;
                    }
                    if nj > K {
                        continue;
                    }
                    if k == 0 {
                        if di > d {
                            continue;
                        }
                        if di < d {
                            nk = 1;
                        }
                    }
                    dp[ni][nj][nk] += dp[i][j][k];
                }
            }
        }
    }
    println!("{}", dp[N.len()][K][1] + dp[N.len()][K][0]);
}


Score : <var>100</var> points

Problem Statement

In AtCoder City, there are three stations numbered <var>1</var>, <var>2</var>, and <var>3</var>.

Each of these stations is operated by one of the two railway companies, A and B. A string <var>S</var> of length <var>3</var> represents which company operates each station. If <var>S_i</var> is A, Company A operates Station <var>i</var>; if <var>S_i</var> is B, Company B operates Station <var>i</var>.

To improve the transportation condition, for each pair of a station operated by Company A and one operated by Company B, there will be a bus service connecting them.

Determine if there is a pair of stations that will be connected by a bus service.

Constraints

Each character of <var>S</var> is A or B.

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If there is a pair of stations that will be connected by a bus service, print Yes; otherwise, print No.

Sample Input 1

ABA

Sample Output 1

Yes

Company A operates Station <var>1</var> and <var>3</var>, while Company B operates Station <var>2</var>.

There will be a bus service between Station <var>1</var> and <var>2</var>, and between Station <var>2</var> and <var>3</var>, so print Yes.

Sample Input 2

BBA

Sample Output 2

Yes

Company B operates Station <var>1</var> and <var>2</var>, while Company A operates Station <var>3</var>.

There will be a bus service between Station <var>1</var> and <var>3</var>, and between Station <var>2</var> and <var>3</var>, so print Yes.

Sample Input 3

BBB

Sample Output 3

No

Company B operates all the stations. Thus, there will be no bus service, so print No.

fn solution() {
    let mut input = String::new();
    if io::stdin().read_line(&mut input).is_ok() {
        let s = input.trim();
        println!(
            "{}",
            if s == "AAA" || s == "BBB" {
                "No"
            } else {
                "Yes"
            }
        );
    }
}


Score: <var>300</var> points

Problem Statement

We have a canvas divided into a grid with <var>H</var> rows and <var>W</var> columns. The square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left is represented as <var>(i, j)</var>.

Initially, all the squares are white. square1001 wants to draw a picture with black paint. His specific objective is to make Square <var>(i, j)</var> black when <var>s_{i, j}=</var> #, and to make Square <var>(i, j)</var> white when <var>s_{i, j}=</var> ..

However, since he is not a good painter, he can only choose two squares that are horizontally or vertically adjacent and paint those squares black, for some number of times (possibly zero). He may choose squares that are already painted black, in which case the color of those squares remain black.

Determine if square1001 can achieve his objective.

Constraints

<var>H</var> is an integer between <var>1</var> and <var>50</var> (inclusive).

<var>W</var> is an integer between <var>1</var> and <var>50</var> (inclusive).

For every <var>(i, j)</var> <var>(1 \leq i \leq H, 1 \leq j \leq W)</var>, <var>s_{i, j}</var> is # or ..

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>s_{1, 1} s_{1, 2} s_{1, 3} ... s_{1, W}</var>
<var>s_{2, 1} s_{2, 2} s_{2, 3} ... s_{2, W}</var>
  <var>:</var>   <var>:</var>
<var>s_{H, 1} s_{H, 2} s_{H, 3} ... s_{H, W}</var>

Output

If square1001 can achieve his objective, print Yes; if he cannot, print No.

Sample Input 1

3 3
.#.
###
.#.

Sample Output 1

Yes

One possible way to achieve the objective is shown in the figure below. Here, the squares being painted are marked by stars.

Sample Input 2

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

Sample Output 2

No

square1001 cannot achieve his objective here.

Sample Input 3

11 11
...#####...
.##.....##.
#..##.##..#
#..##.##..#
#.........#
#...###...#
.#########.
.#.#.#.#.#.
##.#.#.#.##
..##.#.##..
.##..#..##.

Sample Output 3

Yes

int solution() {

  char canvas[52][52];
  int h = 0;
  int w = 0;
  int loop_h = 0;
  int loop_w = 0;
  int flag = 0;
  char strin[52];

  memset(canvas, 0x00, sizeof(canvas));

  scanf("%d%d", &h, &w);
  while ('\n' != getchar()) {
    ;
  }
  for (loop_h = 0; loop_h < h; loop_h++) {
    memset(strin, 0x00, sizeof(strin));
    fgets(strin, 52, stdin);

    for (loop_w = 0; loop_w < w; loop_w++) {
      canvas[loop_h + 1][loop_w + 1] = strin[loop_w];
    }
  }

  for (loop_h = 1; loop_h < h + 1; loop_h++) {
    for (loop_w = 1; loop_w < w + 1; loop_w++) {
      if ('#' == canvas[loop_h][loop_w]) {

        if (('#' != canvas[loop_h - 1][loop_w]) &&
            ('#' != canvas[loop_h + 1][loop_w]) &&
            ('#' != canvas[loop_h][loop_w - 1]) &&
            ('#' != canvas[loop_h][loop_w + 1])) {
          flag = 1;
          break;
        }
      }
    }
  }

  if (0 == flag) {
    printf("Yes");
  } else {
    printf("No");
  }

  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 y: usize = iter.next().unwrap().parse().unwrap();
    let x: usize = iter.next().unwrap().parse().unwrap();
    let squares: Vec<Vec<char>> = (0..y)
        .map(|_| {
            let str: String = iter.next().unwrap().parse().unwrap();
            str.chars().collect::<Vec<char>>()
        })
        .collect();

    let mut can_paint = true;
    'outer: for (i, line) in squares.iter().enumerate() {
        for (j, &square) in line.iter().enumerate() {
            if square == '#' {
                if i != 0 && squares[i - 1][j] == '#' {
                    continue;
                }

                if j != 0 && squares[i][j - 1] == '#' {
                    continue;
                }
                if j < x - 1 && squares[i][j + 1] == '#' {
                    continue;
                }

                if i < y - 1 && squares[i + 1][j] == '#' {
                    continue;
                }

                can_paint = false;
                break 'outer;
            }
        }
    }
    println!("{}", if can_paint { "Yes" } else { "No" });
}


Score : <var>300</var> points

Problem Statement

You are given an undirected unweighted graph with <var>N</var> vertices and <var>M</var> edges that contains neither self-loops nor double edges.

Here, a self-loop is an edge where <var>a_i = b_i (1≤i≤M)</var>, and double edges are two edges where <var>(a_i,b_i)=(a_j,b_j)</var> or <var>(a_i,b_i)=(b_j,a_j) (1≤i<j≤M)</var>.

How many different paths start from vertex <var>1</var> and visit all the vertices exactly once?

Here, the endpoints of a path are considered visited.

For example, let us assume that the following undirected graph shown in Figure 1 is given.

Figure 1: an example of an undirected graph

The following path shown in Figure 2 satisfies the condition.

Figure 2: an example of a path that satisfies the condition

However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices.

Figure 3: an example of a path that does not satisfy the condition

Neither the following path shown in Figure 4, because it does not start from vertex <var>1</var>.

Figure 4: another example of a path that does not satisfy the condition

Constraints

<var>2≦N≦8</var>

<var>0≦M≦N(N-1)/2</var>

<var>1≦a_i<b_i≦N</var>

The given graph contains neither self-loops nor double edges.

Input

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

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>a_2</var> <var>b_2</var>
<var>:</var>
<var>a_M</var> <var>b_M</var>

Output

Print the number of the different paths that start from vertex <var>1</var> and visit all the vertices exactly once.

Sample Input 1

3 3
1 2
1 3
2 3

Sample Output 1

2

The given graph is shown in the following figure:

The following two paths satisfy the condition:

Sample Input 2

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

Sample Output 2

1

This test case is the same as the one described in the problem statement.

fn solution() {
    let mut stdin = io::stdin();
    let mut lines = String::new();
    let _ = stdin.read_to_string(&mut lines);
    let vec = lines.lines().collect::<Vec<&str>>();
    let firstline = vec[0].split(' ').collect::<Vec<&str>>();
    let n: usize = firstline[0].trim().parse().unwrap();
    let m: usize = firstline[1].trim().parse().unwrap();
    let mut hens: Vec<(usize, usize)> = Vec::new();
    for i in 0..m {
        let thisline = vec[i + 1].split(' ').collect::<Vec<&str>>();
        let a: usize = thisline[0].trim().parse().unwrap();
        let b: usize = thisline[1].trim().parse().unwrap();
        hens.push((a - 1, b - 1));
    }
    let hens = hens;
    let mut dp: Vec<usize> = vec![0; n * (1 << n)];
    dp[n] = 1;
    for i in 2..(1 << n) {
        for j in 0..n {
            if (1 << j) & i == 0 {
                continue;
            }
            for &(a, b) in &hens {
                let tail = if a == j {
                    b
                } else if b == j {
                    a
                } else {
                    n
                };
                if tail == n {
                    continue;
                }
                dp[i * n + j] += dp[(i ^ (1 << j)) * n + tail];
            }
        }
    }
    let mut fin = 0;
    for i in 0..n {
        fin += dp[((1 << n) - 1) * n + i];
    }
    println!("{}", fin);
}


There are $$$n$$$ workers and $$$m$$$ tasks. The workers are numbered from $$$1$$$ to $$$n$$$. Each task $$$i$$$ has a value $$$a_i$$$ — the index of worker who is proficient in this task.Every task should have a worker assigned to it. If a worker is proficient in the task, they complete it in $$$1$$$ hour. Otherwise, it takes them $$$2$$$ hours.The workers work in parallel, independently of each other. Each worker can only work on one task at once.Assign the workers to all tasks in such a way that the tasks are completed as early as possible. The work starts at time $$$0$$$. What's the minimum time all tasks can be completed by?

int solution() {
  int testcases;
  int n;
  int m;
  long long int extra;
  long long int need;
  int low;
  int high;
  int mid;
  scanf("%d", &testcases);
  int a[200500];
  int temp;
  while (testcases--) {
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
      a[i] = 0;
    }
    for (int i = 0; i < m; i++) {
      scanf("%d", &temp);
      ++a[temp - 1];
    }
    low = 0;
    high = m + 1;
    while (low < high) {
      mid = (low + high) / 2;
      need = 0;
      extra = 0;
      for (int i = 0; i < n; i++) {
        if (a[i] <= mid) {
          extra += (mid - a[i]) / 2;
        } else {
          need += a[i] - mid;
        }
      }
      if (need <= extra) {
        high = mid;
      }

      else {
        low = mid + 1;
      }
    }
    printf("%d\n", low);
  }
  return 0;
}

fn solution() {
    input! {
        name = reader,
        tests: usize
    }
    for _ in 0..tests {
        input! {
            use reader,
            n: usize,
            m: usize,
            a: [usize1; m]
        }
        let mut cnt = vec![0i64; n];
        for a in a {
            cnt[a] += 1;
        }
        let mut ok = *cnt.iter().max().unwrap();
        let mut ng = 0;
        while ng + 1 < ok {
            let mid = (ng + ok) / 2;
            let mut over = 0;
            let mut under = 0;
            for &c in cnt.iter() {
                if c >= mid {
                    over += c - mid;
                } else {
                    under += (mid - c) / 2;
                }
            }
            if over <= under {
                ok = mid;
            } else {
                ng = mid;
            }
        }
        println!("{}", ok);
    }
}


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).Let $$$p$$$ be any permutation of length $$$n$$$. We define the fingerprint $$$F(p)$$$ of $$$p$$$ as the sorted array of sums of adjacent elements in $$$p$$$. More formally,$$$$$$F(p)=\mathrm{sort}([p_1+p_2,p_2+p_3,\ldots,p_{n-1}+p_n]).$$$$$$For example, if $$$n=4$$$ and $$$p=[1,4,2,3],$$$ then the fingerprint is given by $$$F(p)=\mathrm{sort}([1+4,4+2,2+3])=\mathrm{sort}([5,6,5])=[5,5,6]$$$.You are given a permutation $$$p$$$ of length $$$n$$$. Your task is to find a different permutation $$$p'$$$ with the same fingerprint. Two permutations $$$p$$$ and $$$p'$$$ are considered different if there is some index $$$i$$$ such that $$$p_i \ne p'_i$$$.

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

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

    for _i in 0..t {
        io::stdin().read_line(&mut input).unwrap();
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        q = input
            .split_whitespace()
            .rev()
            .map(|num| num.parse().unwrap())
            .collect();
        println!("{}", q.join(" "));
        input.clear();
    }
}


There are $$$n$$$ boxers, the weight of the $$$i$$$-th boxer is $$$a_i$$$. Each of them can change the weight by no more than $$$1$$$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).Write a program that for given current values $$$a_i$$$ will find the maximum possible number of boxers in a team.It is possible that after some change the weight of some boxer is $$$150001$$$ (but no more).

fn solution() {
    let mut v: Vec<i32> = BufReader::new(io::stdin())
        .lines()
        .nth(1)
        .unwrap()
        .unwrap()
        .split_whitespace()
        .map(|s| s.parse::<i32>().unwrap())
        .collect();
    v.sort();
    let mut max = 0u32;
    let mut cnt = 0u32;
    for mut w in v {
        let diff = w - max as i32;
        match diff {
            0 => w += 1,
            1 => (),
            v if v > 1 => w -= 1,
            _ => continue,
        }
        max = w as u32;
        cnt += 1;
    }
    println!("{}", cnt)
}


The Squareland national forest is divided into equal $$$1 \times 1$$$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $$$(x, y)$$$ of its south-west corner.Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $$$A, B, C$$$ in the forest. Initially, all plots in the forest (including the plots $$$A, B, C$$$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $$$A, B, C$$$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.    For example, $$$A=(0,0)$$$, $$$B=(1,1)$$$, $$$C=(2,2)$$$. The minimal number of plots to be cleared is $$$5$$$. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.

int solution(int argc, char const *argv[]) {
  int x1;
  int x2;
  int x3;
  int y1;
  int y2;
  int y3;
  scanf("%d%d", &x1, &y1);
  scanf("%d%d", &x2, &y2);
  scanf("%d%d", &x3, &y3);
  int minx = 2000;
  int miny = 2000;
  int maxx = -1;
  int maxy = -1;
  if (x1 < minx) {
    minx = x1;
  }
  if (x2 < minx) {
    minx = x2;
  }
  if (x3 < minx) {
    minx = x3;
  }
  if (x1 > maxx) {
    maxx = x1;
  }
  if (x2 > maxx) {
    maxx = x2;
  }
  if (x3 > maxx) {
    maxx = x3;
  }

  if (y1 < miny) {
    miny = y1;
  }
  if (y2 < miny) {
    miny = y2;
  }
  if (y3 < miny) {
    miny = y3;
  }
  if (y1 > maxy) {
    maxy = y1;
  }
  if (y2 > maxy) {
    maxy = y2;
  }
  if (y3 > maxy) {
    maxy = y3;
  }
  int ans = maxy + maxx - miny - minx + 1;
  printf("%d", ans);

  int midx;
  int midy;
  if ((x1 <= x2 && x1 >= x3) || (x1 >= x2 && x1 <= x3)) {
    midx = x1;
  }
  if ((x2 <= x1 && x2 >= x3) || (x2 >= x1 && x2 <= x3)) {
    midx = x2;
  }
  if ((x3 <= x2 && x3 >= x1) || (x3 >= x2 && x3 <= x1)) {
    midx = x3;
  }
  if ((y1 <= y2 && y1 >= y3) || (y1 >= y2 && y1 <= y3)) {
    midy = y1;
  }
  if ((y2 <= y1 && y2 >= y3) || (y2 >= y1 && y2 <= y3)) {
    midy = y2;
  }
  if ((y3 <= y2 && y3 >= y1) || (y3 >= y2 && y3 <= y1)) {
    midy = y3;
  }

  for (int i = miny; i <= maxy; ++i) {
    printf("\n%d %d", midx, i);
  }
  int y;
  if (minx == x1) {
    y = y1;
  }
  if (minx == x2) {
    y = y2;
  }
  if (minx == x3) {
    y = y3;
  }

  for (int i = minx; i < midx; ++i) {
    printf("\n%d %d", i, y);
  }
  if (maxx == x1) {
    y = y1;
  }
  if (maxx == x2) {
    y = y2;
  }
  if (maxx == x3) {
    y = y3;
  }

  for (int i = maxx; i > midx; --i) {
    printf("\n%d %d", i, y);
  }

  return 0;
}

fn solution() {
    let mut visited = vec![vec![0; 1005]; 1005];
    let mut v = Vec::new();
    for _ in 0..3 {
        let mut s = String::new();
        stdin().read_line(&mut s).ok();
        let mut iter = s.split_whitespace();
        let t: (usize, usize) = (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        );
        v.push(t);
    }
    v.sort();
    let mut x = v[0].0;
    let mut y = v[0].1;
    while x < v[1].0 {
        visited[x][y] = 1;
        x += 1;
    }
    let mut dy = if v[1].1 > y { 1 } else { -1i32 };
    while y != v[1].1 {
        visited[x][y] = 1;
        y = (y as i32 + dy) as usize;
    }
    dy = if v[2].1 > y { 1 } else { -1 };
    while y != v[2].1 {
        visited[x][y] = 1;
        y = (y as i32 + dy) as usize;
    }
    while x < v[2].0 {
        visited[x][y] = 1;
        x += 1;
    }
    visited[x][y] = 1;
    let mut tot = 0;
    for i in 0..visited.len() {
        for j in 0..visited.len() {
            if visited[i][j] == 1 {
                tot += 1;
            }
        }
    }
    println!("{}", tot);
    for i in 0..visited.len() {
        for j in 0..visited.len() {
            if visited[i][j] == 1 {
                println!("{} {}", i, j);
            }
        }
    }
}


Madoka is a very strange girl, and therefore she suddenly wondered how many pairs of integers $$$(a, b)$$$ exist, where $$$1 \leq a, b \leq n$$$, for which $$$\frac{\operatorname{lcm}(a, b)}{\operatorname{gcd}(a, b)} \leq 3$$$.In this problem, $$$\operatorname{gcd}(a, b)$$$ denotes the greatest common divisor of the numbers $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(a, b)$$$ denotes the smallest common multiple of the numbers $$$a$$$ and $$$b$$$.

int solution() {

  int licz;
  scanf("%d", &licz);

  int wczyt[licz];

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

  for (i = 0; i < licz; i++) {
    printf("%d\n", wczyt[i] + ((wczyt[i] / 2) * 2) + ((wczyt[i] / 3) * 2));
  }

  return 0;
}

fn solution() {
    let std_in = stdin();
    let mut input = Scanner::new(std_in.lock());

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

    let t: usize = input.token();
    for _ in 0..t {
        let n: usize = input.token();
        let result = n + 2 * (n / 2 + n / 3);
        writeln!(output, "{}", result).unwrap();
    }
}


Arkady is playing Battleship. The rules of this game aren't really important.There is a field of $$$n \times n$$$ cells. There should be exactly one $$$k$$$-decker on the field, i. e. a ship that is $$$k$$$ cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if it is definitely empty or can contain a part of the ship.Consider all possible locations of the ship. Find such a cell that belongs to the maximum possible number of different locations of the ship.

fn solution() {
    use std::io;
    use std::io::prelude::*;

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

    let mut it = input.split_whitespace();
    let n: usize = it.next().unwrap().parse().unwrap();
    let k: usize = it.next().unwrap().parse().unwrap();

    let mut field = Vec::with_capacity(n * n);

    for _ in 0..n {
        for c in it.next().unwrap().chars() {
            match c {
                '#' => field.push(Cell::Empty),
                '.' => field.push(Cell::Unknown),
                _ => panic!("Invalid input"),
            }
        }
    }

    let check_h = |p| {
        (p..).take(k).all(|p| match field[p] {
            Cell::Empty => false,
            Cell::Unknown => true,
        })
    };

    let check_v = |mut p| {
        for _ in 0..k {
            match field[p] {
                Cell::Empty => return false,
                Cell::Unknown => (),
            }
            p += n;
        }
        true
    };

    let _ans = 0;

    let mut pl = vec![0; n * n];

    for y in 0..n {
        for x in 0..n {
            let p = y * n + x;
            if x + k <= n && check_h(p) {
                for i in 0..k {
                    pl[p + i] += 1;
                }
            }
            if y + k <= n && check_v(p) {
                for j in 0..k {
                    pl[p + n * j] += 1;
                }
            }
        }
    }

    let max_val = *pl.iter().max().unwrap();
    for y in 0..n {
        for x in 0..n {
            if pl[y * n + x] == max_val {
                println!("{} {}", y + 1, x + 1);
                return;
            }
        }
    }
}


Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.

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

    std::io::stdin().read_line(&mut inp).unwrap();
    let t: i32 = inp.trim().parse().unwrap();

    for _ in 0..t {
        inp = String::new();
        std::io::stdin().read_line(&mut inp).unwrap();

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

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

        l1 = l1.replace("G", "B");
        l2 = l2.replace("G", "B");

        if l1 == l2 {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>100</var> points

Problem Statement

You are parking at a parking lot. You can choose from the following two fee plans:

Plan <var>1</var>: The fee will be <var>A×T</var> yen (the currency of Japan) when you park for <var>T</var> hours.

Plan <var>2</var>: The fee will be <var>B</var> yen, regardless of the duration.

Find the minimum fee when you park for <var>N</var> hours.

Constraints

<var>1≤N≤20</var>

<var>1≤A≤100</var>

<var>1≤B≤2000</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

When the minimum fee is <var>x</var> yen, print the value of <var>x</var>.

Sample Input 1

7 17 120

Sample Output 1

119

If you choose Plan <var>1</var>, the fee will be <var>7×17=119</var> yen.

If you choose Plan <var>2</var>, the fee will be <var>120</var> yen.

Thus, the minimum fee is <var>119</var> yen.

Sample Input 2

5 20 100

Sample Output 2

100

The fee might be the same in the two plans.

Sample Input 3

6 18 100

Sample Output 3

100

int solution(void) {
  int a = 0;
  int b = 0;
  int n = 0;
  scanf("%d %d %d", &n, &a, &b);
  if (a * n <= b) {
    printf("%d\n", a * n);
  } else {
    printf("%d\n", b);
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let input: Vec<i32> = buf.split_whitespace().map(|c| c.parse().unwrap()).collect();
    let n = input[0];
    let a = input[1];
    let b = input[2];

    println!("{}", std::cmp::min(n * a, b));
}


You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.

int solution() {
  int len = 0;
  int num = 0;
  scanf("%d %d", &len, &num);
  int arr[1000] = {0};
  int count = 0;
  int stop = 0;
  for (int i = 0; i < num; i++) {
    scanf("%d", &arr[i]);
  }
  int platform[1000] = {0};
  for (int i = 0; i < num; i++) {
    for (int j = 1; j < len + 1; j++) {
      if (arr[i] == j) {
        platform[j - 1]++;
        break;
      }
    }
  }
  for (int i = 0; i < num; i++) {
    for (int j = 0; j < len; j++) {
      platform[j]--;
    }
    for (int k = 0; k < len; k++) {
      if (platform[k] < 0) {
        stop = 1;
        break;
      }
    }
    if (stop == 1) {
      break;
    }
    count++;
  }
  printf("%d\n", count);

  return 0;
}

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

    io::stdin().read_line(&mut input);
    let iter = input.split_whitespace().map(|x| x.parse::<u32>().unwrap());
    let mut counter = vec![0; squares];
    for number in iter {
        counter[number as usize - 1] += 1;
    }

    let mut min = 100000;
    for &number in counter.iter() {
        if number < min {
            min = number;
        }
    }

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


Score : <var>100</var> points

Problem Statement

There is always an integer in Takahashi's mind.

Initially, the integer in Takahashi's mind is <var>0</var>. Takahashi is now going to eat four symbols, each of which is + or -. When he eats +, the integer in his mind increases by <var>1</var>; when he eats -, the integer in his mind decreases by <var>1</var>.

The symbols Takahashi is going to eat are given to you as a string <var>S</var>. The <var>i</var>-th character in <var>S</var> is the <var>i</var>-th symbol for him to eat.

Find the integer in Takahashi's mind after he eats all the symbols.

Constraints

The length of <var>S</var> is <var>4</var>.

Each character in <var>S</var> is + or -.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the integer in Takahashi's mind after he eats all the symbols.

Sample Input 1

+-++

Sample Output 1

2

Initially, the integer in Takahashi's mind is <var>0</var>.

The first integer for him to eat is +. After eating it, the integer in his mind becomes <var>1</var>.

The second integer to eat is -. After eating it, the integer in his mind becomes <var>0</var>.

The third integer to eat is +. After eating it, the integer in his mind becomes <var>1</var>.

The fourth integer to eat is +. After eating it, the integer in his mind becomes <var>2</var>.

Thus, the integer in Takahashi's mind after he eats all the symbols is <var>2</var>.

Sample Input 2

-+--

Sample Output 2

-2

Sample Input 3

----

Sample Output 3

-4

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

    let mut cnt: isize = 0;
    for c in buf.chars() {
        if c == '+' {
            cnt += 1;
        } else if c == '-' {
            cnt -= 1;
        }
    }

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


Score : <var>200</var> points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with <var>A</var> sockets, into <var>B</var> or more empty sockets.

One power strip with <var>A</var> sockets can extend one empty socket into <var>A</var> empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

<var>2 \leq A \leq 20</var>

<var>1 \leq B \leq 20</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

<var>3</var> power strips, each with <var>4</var> sockets, extend the socket into <var>10</var> empty sockets.

Sample Input 2

8 9

Sample Output 2

2

<var>2</var> power strips, each with <var>8</var> sockets, extend the socket into <var>15</var> empty sockets.

Sample Input 3

8 8

Sample Output 3

1

int solution(void) {
  int mouth = 0;
  int want = 0;
  int ans = 0;
  int ima = 1;
  int flag = 0;

  scanf("%d", &mouth);
  scanf("%d", &want);

  while (flag == 0) {
    if (ima < want) {
      ima = ima - 1;
      ima = ima + mouth;
      ans++;
    } else {
      flag = 1;
    }
  }

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

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    let v: Vec<i32> = s
        .split_whitespace()
        .map(|n| n.parse().ok().unwrap())
        .collect();
    let a = v[0];
    let b = v[1];
    let _s = a - 1;
    let _t = b - 1;
    let mut r: i32 = 0;
    let mut o: i32 = 1;
    while o < b {
        o += a - 1;
        r += 1;
    }
    println!("{}", r);
}


				Max Score: <var>350</var> Points

Problem Statement

					There are <var>N</var> buildings along the line. The <var>i</var>-th building from the left is colored in color <var>i</var>, and its height is currently <var>a_i</var> meters.

					Chokudai is a mayor of the city, and he loves colorful thigs. And now he wants to see at least <var>K</var> buildings from the left.

					You can increase height of buildings, but it costs <var>1</var> yens to increase <var>1</var> meters. It means you cannot make building that height is not integer.

					You cannot decrease height of buildings.

					Calculate the minimum cost of satisfying Chokudai's objective.

					Note: "Building <var>i</var> can see from the left" means there are no <var>j</var> exists that (height of building <var>j</var>) ≥ (height of building <var>i</var>) and <var>j < i</var>.

Input Format

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

Output Format

						Print the minimum cost in one line. In the end put a line break.

Constraints

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

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

Scoring

						Subtask 1 [<var>120</var> points]

<var>N = K</var>

						Subtask 2 [<var>90</var> points]

<var>N ≤ 5</var>

<var>a_i ≤ 7</var>

						Subtask 3 [<var>140</var> points]

There are no additional constraints.

Sample Input 1

5 5
3949 3774 3598 3469 3424

Sample Output 1

1541

					The optimal solution is (height of buildings from the left) <var>= [3949, 3950, 3951, 3952, 3953]</var>.

Sample Input 2

5 3
7 4 2 6 4

Sample Output 2

7

					The optimal solution is (height of buildings from the left) <var>= [7, 8, 2, 9, 4]</var>.

int solution(void) {
  int n;
  int k;
  scanf("%d%d", &n, &k);
  int a[15];
  int i;
  int j;
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  long long int ans = 999999999999999;
  int bit;
  int a_temp[15];
  int can_see = 0;
  int maxh = 0;
  long long int cost;
  for (bit = 0; bit < (1 << n); ++bit) {
    cost = 0;
    can_see = 0;
    for (i = 0; i < n; i++) {
      a_temp[i] = a[i];
    }
    for (i = 0; i < n; i++) {
      if (bit & (1 << i)) {
        can_see++;

        maxh = 0;
        for (j = 0; j <= i - 1; j++) {
          maxh = maxh > a_temp[j] ? maxh : a_temp[j];
        }

        if (a_temp[i] < maxh + 1) {
          cost += maxh + 1 - a_temp[i];
          a_temp[i] = maxh + 1;
        }
      }
    }
    if (can_see >= k) {
      ans = ans < cost ? ans : cost;
    }
  }
  printf("%lld\n", ans);
  return 0;
}

fn solution() {
    input! {
    n: usize,
    k: usize,
    a: [usize; n]
    }
    let mut ans = usize::max_value();
    for i in 0..1 << n {
        let i: usize = i;
        let q = i.count_ones() as usize;
        if q < k {
            continue;
        }
        let mut c = 0;
        let mut h = a[0];
        for j in 1..n {
            if 1 << j & i > 0 && h >= a[j] {
                c += h - a[j] + 1;
                h += 1;
            } else if h < a[j] {
                h = a[j];
            }
        }
        ans = min(c, ans);
    }
    println!("{}", ans);
}


Score : <var>200</var> points

Problem Statement

We have a grid of <var>H</var> rows and <var>W</var> columns. Initially, there is a stone in the top left cell. Shik is trying to move the stone to the bottom right cell. In each step, he can move the stone one cell to its left, up, right, or down (if such cell exists). It is possible that the stone visits a cell multiple times (including the bottom right and the top left cell).

You are given a matrix of characters <var>a_{ij}</var> (<var>1 \leq i \leq H</var>, <var>1 \leq j \leq W</var>). After Shik completes all moving actions, <var>a_{ij}</var> is # if the stone had ever located at the <var>i</var>-th row and the <var>j</var>-th column during the process of moving. Otherwise, <var>a_{ij}</var> is .. Please determine whether it is possible that Shik only uses right and down moves in all steps.

Constraints

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

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

There exists a valid sequence of moves for Shik to generate the map <var>a</var>.

Input

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

<var>H</var> <var>W</var>
<var>a_{11}a_{12}</var><var>...</var><var>a_{1W}</var>
<var>:</var>
<var>a_{H1}a_{H2}</var><var>...</var><var>a_{HW}</var>

Output

If it is possible that Shik only uses right and down moves, print Possible. Otherwise, print Impossible.

Sample Input 1

4 5
##...
.##..
..##.
...##

Sample Output 1

Possible

The matrix can be generated by a <var>7</var>-move sequence: right, down, right, down, right, down, and right.

Sample Input 2

5 3
###
..#
###
#..
###

Sample Output 2

Impossible

Sample Input 3

4 5
##...
.###.
.###.
...##

Sample Output 3

Impossible

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

    let hw: Vec<_> = s.trim().split(' ').map(|x| x.parse().unwrap()).collect();

    let mut xs = vec![vec![false; hw[1]]; hw[0]];

    let mut res = true;

    'outer: for i in 0..hw[0] {
        let mut s = String::new();
        io::stdin().read_line(&mut s).ok();
        if !res {
            continue;
        }

        let cs: Vec<_> = s.trim().chars().collect();

        for j in 0..hw[1] {
            if cs[j] == '.' {
                continue;
            }

            if i == j && i == 0 {
                xs[i][j] = true;
                continue;
            }

            let f1 = if i == 0 { false } else { xs[i - 1][j] };

            let f2 = if j == 0 { false } else { xs[i][j - 1] };

            res = f1 != f2;
            xs[i][j] = res;

            if !res {
                break 'outer;
            }
        }
    }

    if res {
        'outer2: for i in 0..hw[0] {
            for j in 0..hw[1] {
                if i == hw[0] - 1 && j == hw[1] - 1 {
                    break 'outer2;
                }

                if !xs[i][j] {
                    continue;
                }

                let f1 = if i == hw[0] - 1 { false } else { xs[i + 1][j] };

                let f2 = if j == hw[1] - 1 { false } else { xs[i][j + 1] };

                res = f1 != f2;
                if !res {
                    break 'outer2;
                }
            }
        }
    }

    println!("{}", if res { "Possible" } else { "Impossible" });
}


Score : <var>300</var> points

Problem Statement

Find <var>\displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}</var>.

Here <var>\gcd(a,b,c)</var> denotes the greatest common divisor of <var>a</var>, <var>b</var>, and <var>c</var>.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print the value of <var>\displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}</var>.

Sample Input 1

2

Sample Output 1

9

<var>\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)</var>
<var>+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)</var>
<var>=1+1+1+1+1+1+1+2=9</var>

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

Sample Input 2

200

Sample Output 2

10813692

int solution(void) {
  int k;
  long long int ans = 0;
  int min = 200;
  scanf("%d", &k);

  for (int i = 1; i <= k; i++) {
    for (int j = 1; j <= k; j++) {
      for (int l = 1; l <= k; l++) {
        min = fmin(i, j);
        min = fmin(min, l);
        for (int m = min; m > 0; m--) {
          if (i % m == 0 && j % m == 0 && l % m == 0) {
            ans += m;
            break;
          }
        }
      }
    }
  }
  printf("%lld\n", ans);
  return 0;
}


Polycarp got an array of integers $$$a[1 \dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\dots=a_n$$$)?

int solution() {
  int n = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    int a = 0;
    scanf("%d", &a);
    int max = 0;
    int min = 1000000000;
    for (int j = 0; j < a; j++) {
      int temp = 0;
      scanf("%d", &temp);
      if (temp > max) {
        max = temp;
      }
      if (temp < min) {
        min = temp;
      }
    }
    printf("%d\n", max - min);
  }
  return 0;
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(2)
        .step_by(2)
        .flatten()
        .for_each(|s| {
            let (max, min) = s
                .split_ascii_whitespace()
                .flat_map(str::parse::<usize>)
                .fold((0usize, usize::MAX), |(max, min), c| {
                    (max.max(c), min.min(c))
                });
            let ans = max.wrapping_sub(min);
            writeln!(buf, "{ans}").ok();
        });
}


You are given a permutation $$$a_1, a_2, \ldots, a_n$$$ of size $$$n$$$, where each integer from $$$1$$$ to $$$n$$$ appears exactly once.You can do the following operation any number of times (possibly, zero):  Choose any three indices $$$i, j, k$$$ ($$$1 \le i < j < k \le n$$$).  If $$$a_i > a_k$$$, replace $$$a_i$$$ with $$$a_i + a_j$$$. Otherwise, swap $$$a_j$$$ and $$$a_k$$$. Determine whether you can make the array $$$a$$$ sorted in non-descending order.

int solution() {

  int t = 0;
  int a = 0;
  int b[100] = {0};

  scanf("%d", &t);

  while (t != 0) {

    scanf("%d", &a);

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

    if (b[0] == 1) {
      printf("\nYes\n");
    } else {
      printf("\nNo\n");
    }

    t--;
  }

  return 0;
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(2)
        .step_by(2)
        .flatten()
        .for_each(|s| {
            writeln!(buf, "{}", if s.starts_with("1 ") { "Yes" } else { "No" }).unwrap_or_default();
        });
}


Score : <var>500</var> points

Problem Statement

There are <var>K</var> items placed on a grid of squares with <var>R</var> rows and <var>C</var> columns. Let <var>(i, j)</var> denote the square at the <var>i</var>-th row (<var>1 \leq i \leq R</var>) and the <var>j</var>-th column (<var>1 \leq j \leq C</var>). The <var>i</var>-th item is at <var>(r_i, c_i)</var> and has the value <var>v_i</var>.

Takahashi will begin at <var>(1, 1)</var>, the start, and get to <var>(R, C)</var>, the goal. When he is at <var>(i, j)</var>, he can move to <var>(i + 1, j)</var> or <var>(i, j + 1)</var> (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

<var>1 \leq R, C \leq 3000</var>

<var>1 \leq K \leq \min(2 \times 10^5, R \times C)</var>

<var>1 \leq r_i \leq R</var>

<var>1 \leq c_i \leq C</var>

<var>(r_i, c_i) \neq (r_j, c_j) (i \neq j)</var>

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>R</var> <var>C</var> <var>K</var>
<var>r_1</var> <var>c_1</var> <var>v_1</var>
<var>r_2</var> <var>c_2</var> <var>v_2</var>
<var>:</var>
<var>r_K</var> <var>c_K</var> <var>v_K</var>

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

Visit <var>(1, 1)</var>, <var>(1, 2)</var>, and <var>(2, 2)</var>, in this order. In this case, the total value of the items he can pick up is <var>3 + 5 = 8</var>.

Visit <var>(1, 1)</var>, <var>(2, 1)</var>, and <var>(2, 2)</var>, in this order. In this case, the total value of the items he can pick up is <var>3 + 4 = 7</var>.

Thus, the maximum possible sum of the values of items he picks up is <var>8</var>.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the <var>1</var>-st row. The optimal choices are as follows:

Visit <var>(1, 1)</var> <var>(1, 2)</var>, <var>(1, 3)</var>, <var>(1, 4)</var>, <var>(2, 4)</var>, and <var>(2, 5)</var>, in this order, and pick up all items except the one on <var>(1, 2)</var>. Then, the total value of the items he picks up will be <var>3 + 4 + 2 + 20 = 29</var>.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142

fn solution() {
    let mut buf = String::new();
    std::io::stdin()
        .read_to_string(&mut buf)
        .expect("fail to read");
    let mut iter = buf.split_whitespace();

    let h: usize = iter.next().unwrap().parse().unwrap();
    let w: usize = iter.next().unwrap().parse().unwrap();
    let k: usize = iter.next().unwrap().parse().unwrap();

    let mut dp = vec![vec![vec![0_i64; 4]; w + 1]; h + 1];
    let mut map = vec![vec![None; w + 1]; h + 1];

    for _i in 0..k {
        let r: usize = iter.next().unwrap().parse().unwrap();
        let c: usize = iter.next().unwrap().parse().unwrap();
        let v: i64 = iter.next().unwrap().parse().unwrap();
        map[r][c] = Some(v);
    }
    let map = map;

    for y in 1..=h {
        for x in 1..=w {
            if let Some(v) = map[y][x] {
                dp[y][x][1] = max(
                    dp[y][x][1],
                    max(*dp[y - 1][x].iter().max().unwrap() + v, dp[y][x - 1][0] + v),
                );
                dp[y][x][2] = max(dp[y][x][2], dp[y][x - 1][1] + v);
                dp[y][x][3] = max(dp[y][x][3], dp[y][x - 1][2] + v);
            }

            dp[y][x][0] = max(*dp[y - 1][x].iter().max().unwrap(), dp[y][x - 1][0]);
            dp[y][x][1] = max(dp[y][x][1], dp[y][x - 1][1]);
            dp[y][x][2] = max(dp[y][x][2], dp[y][x - 1][2]);
            dp[y][x][3] = max(dp[y][x][3], dp[y][x - 1][3]);
        }
    }
    println!("{}", *dp[h][w].iter().max().unwrap());
}