Score: <var>200</var> points

Problem Statement

We have a string <var>S</var> consisting of lowercase English letters.

If the length of <var>S</var> is at most <var>K</var>, print <var>S</var> without change.

If the length of <var>S</var> exceeds <var>K</var>, extract the first <var>K</var> characters in <var>S</var>, append ... to the end of them, and print the result.

Constraints

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

<var>S</var> is a string consisting of lowercase English letters.

The length of <var>S</var> is between <var>1</var> and <var>100</var> (inclusive).

Input

Input is given from Standard Input in the following format:

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

Output

Print a string as stated in Problem Statement.

Sample Input 1

7
nikoandsolstice

Sample Output 1

nikoand...

nikoandsolstice has a length of <var>15</var>, which exceeds <var>K=7</var>.

We should extract the first <var>7</var> characters in this string, append ... to the end of them, and print the result nikoand....

Sample Input 2

40
ferelibenterhominesidquodvoluntcredunt

Sample Output 2

ferelibenterhominesidquodvoluntcredunt

The famous quote from Gaius Julius Caesar.

int solution(void) {
  int a = 0;
  scanf("%d", &a);
  char s[999] = "";
  scanf("%s", s);
  int y = strlen(s);

  if (y <= a) {
    printf("%s", s);
  } else {
    char t[999] = " ";
    strncpy(t, s, a);
    printf("%s", t);
    printf("...");
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let k: usize = s.trim().parse().unwrap();
    s.clear();
    stdin().read_line(&mut s).ok();
    s.pop();
    println!(
        "{}",
        if s.len() <= k {
            s
        } else {
            format!("{}...", &s[..k])
        }
    );
}


Score : <var>300</var> points

Problem Statement

Given is a sequence of integers <var>A_1, A_2, ..., A_N</var>.
If its elements are pairwise distinct, print YES; otherwise, print NO.

Constraints

<var>2 ≤ N ≤ 200000</var>

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If the elements of the sequence are pairwise distinct, print YES; otherwise, print NO.

Sample Input 1

5
2 6 1 4 5

Sample Output 1

YES

The elements are pairwise distinct.

Sample Input 2

6
4 1 3 1 6 2

Sample Output 2

NO

The second and fourth elements are identical.

Sample Input 3

2
10000000 10000000

Sample Output 3

NO

int solution(void) {
  static char A[1000000010];
  int N;
  int num;
  int ans;

  scanf("%d", &N);

  for (int i = 0; i < 1000000010; i++) {
    A[i] = 0;
  }

  for (int i = 0; i < N; i++) {
    scanf("%d", &num);
    A[num]++;
    if (A[num] > 1) {
      printf("NO");
      return 0;
    }
  }

  printf("YES");

  return 0;
}

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

    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    let line: HashSet<&str> = line.split_whitespace().collect();
    println!("{}", if n == line.len() { "YES" } else { "NO" });
}


Score : <var>200</var> points

Problem Statement

Snuke is having a barbeque party.

At the party, he will make <var>N</var> servings of Skewer Meal.

Example of a serving of Skewer Meal

He has a stock of <var>2N</var> skewers, all of which will be used in Skewer Meal. The length of the <var>i</var>-th skewer is <var>L_i</var>.
Also, he has an infinite supply of ingredients.

To make a serving of Skewer Meal, he picks <var>2</var> skewers and threads ingredients onto those skewers.
Let the length of the shorter skewer be <var>x</var>, then the serving can hold the maximum of <var>x</var> ingredients.

What is the maximum total number of ingredients that his <var>N</var> servings of Skewer Meal can hold, if he uses the skewers optimally?

Constraints

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

<var>1≦L_i≦100</var>

For each <var>i</var>, <var>L_i</var> is an integer.

Input

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

<var>N</var>
<var>L_1</var> <var>L_2</var> <var>...</var> <var>L_{2N}</var>

Output

Print the maximum total number of ingredients that Snuke's <var>N</var> servings of Skewer Meal can hold.

Sample Input 1

2
1 3 1 2

Sample Output 1

3

If he makes a serving using the first and third skewers, and another using the second and fourth skewers, each serving will hold <var>1</var> and <var>2</var> ingredients, for the total of <var>3</var>.

Sample Input 2

5
100 1 2 3 14 15 58 58 58 29

Sample Output 2

135

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

    let N = buf_it.next().unwrap().parse::<usize>().unwrap();
    let mut A = (0..2 * N)
        .map(|_| buf_it.next().unwrap().parse::<isize>().unwrap())
        .collect::<Vec<_>>();
    A.sort();
    println!("{}", (0..N).map(|i| A[i * 2]).sum::<isize>());
}


You are given a positive integer $$$n$$$. You have to find $$$4$$$ positive integers $$$a, b, c, d$$$ such that  $$$a + b + c + d = n$$$, and $$$\gcd(a, b) = \operatorname{lcm}(c, d)$$$.If there are several possible answers you can output any of them. It is possible to show that the answer always exists.In this problem $$$\gcd(a, b)$$$ denotes the greatest common divisor of $$$a$$$ and $$$b$$$, and $$$\operatorname{lcm}(c, d)$$$ denotes the least common multiple of $$$c$$$ and $$$d$$$.

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

fn solution() {
    let stdin = io::stdin();
    let lines = stdin.lock().lines().skip(1);
    let mut oup = io::BufWriter::new(io::stdout());
    for line in lines {
        let n = line.unwrap().parse::<u32>().unwrap();
        writeln!(oup, "{} 1 1 1", n - 3).unwrap();
    }
    oup.flush().ok();
}


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut lines = buf.lines();
    let (h, w, c) = {
        let mut tokens = lines.next().unwrap().split_whitespace();
        let h: i32 = tokens.next().unwrap().parse().unwrap();
        let w: i32 = tokens.next().unwrap().parse().unwrap();
        let c: char = tokens.next().unwrap().parse().unwrap();
        (h, w, c)
    };

    let room: Vec<Vec<char>> = lines.map(|l| l.chars().collect()).collect();

    let di: Vec<i32> = vec![0, 1, 0, -1];
    let dj: Vec<i32> = vec![1, 0, -1, 0];
    let mut set = HashSet::new();
    for i in 0..h {
        for j in 0..w {
            if room[i as usize][j as usize] == c {
                for k in 0..4 {
                    let ii = i + di[k];
                    let jj = j + dj[k];
                    if ii >= 0 && ii < h && jj >= 0 && jj < w {
                        set.insert(room[ii as usize][jj as usize]);
                    }
                }
            }
        }
    }
    set.remove(&c);
    set.remove(&'.');
    println!("{}", set.len());
}


All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — a coordinate on the Ox axis. No two cities are located at a single point.Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (because if they live in the same city, then it is easier to drop in).Strange but true, the cost of sending the letter is exactly equal to the distance between the sender's city and the recipient's city.For each city calculate two values mini and maxi, where mini is the minimum cost of sending a letter from the i-th city to some other city, and maxi is the the maximum cost of sending a letter from the i-th city to some other city

int solution() {
  int number = 0;
  int p = 0;
  scanf("%d", &number);
  int location[number];
  for (int i = 0; i < number; i++) {
    scanf("%d", &location[i]);
  }
  int max = location[number - 1] - location[0];
  int min = location[1] - location[0];
  printf("%d %d\n", min, max);
  int max1 = 0;
  int max2 = 0;
  int min1 = 0;
  int min2 = 0;
  for (int i = 1; i < number - 1; i++) {
    max1 = location[i] - location[0];
    max2 = location[number - 1] - location[i];
    min1 = location[i] - location[i - 1];
    min2 = location[i + 1] - location[i];
    max = max1;
    if (max1 < max2) {
      max = max2;
    }
    min = min1;
    if (min1 > min2) {
      min = min2;
    }
    printf("%d %d\n", min, max);
  }
  max = location[number - 1] - location[0];
  min = location[number - 1] - location[number - 2];
  printf("%d %d\n", min, max);
}

fn solution() {
    use std::io;
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let cities: Vec<i64> = buf
        .split_whitespace()
        .map(|str| str.trim().parse().unwrap())
        .collect();
    for (i, &city) in cities.iter().enumerate() {
        let max = std::cmp::max(
            (cities[0] - city).abs(),
            (cities[cities.len() - 1] - city).abs(),
        );
        let mut min = i64::max_value();
        if i != 0 {
            min = std::cmp::min(min, (cities[i - 1] - city).abs());
        }
        if i != cities.len() - 1 {
            min = std::cmp::min(min, (cities[i + 1] - city).abs());
        }
        println!("{} {}", min, max);
    }
}


A batch of $$$n$$$ goods ($$$n$$$ — an even number) is brought to the store, $$$i$$$-th of which has weight $$$a_i$$$. Before selling the goods, they must be packed into packages. After packing, the following will be done:   There will be $$$\frac{n}{2}$$$ packages, each package contains exactly two goods;  The weight of the package that contains goods with indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) is $$$a_i + a_j$$$. With this, the cost of a package of weight $$$x$$$ is always $$$\left \lfloor\frac{x}{k}\right\rfloor$$$ burles (rounded down), where $$$k$$$ — a fixed and given value.Pack the goods to the packages so that the revenue from their sale is maximized. In other words, make such $$$\frac{n}{2}$$$ pairs of given goods that the sum of the values $$$\left \lfloor\frac{x_i}{k} \right \rfloor$$$, where $$$x_i$$$ is the weight of the package number $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$), is maximal.For example, let $$$n = 6, k = 3$$$, weights of goods $$$a = [3, 2, 7, 1, 4, 8]$$$. Let's pack them into the following packages.   In the first package we will put the third and sixth goods. Its weight will be $$$a_3 + a_6 = 7 + 8 = 15$$$. The cost of the package will be $$$\left \lfloor\frac{15}{3}\right\rfloor = 5$$$ burles.  In the second package put the first and fifth goods, the weight is $$$a_1 + a_5 = 3 + 4 = 7$$$. The cost of the package is $$$\left \lfloor\frac{7}{3}\right\rfloor = 2$$$ burles.  In the third package put the second and fourth goods, the weight is $$$a_2 + a_4 = 2 + 1 = 3$$$. The cost of the package is $$$\left \lfloor\frac{3}{3}\right\rfloor = 1$$$ burle. With this packing, the total cost of all packs would be $$$5 + 2 + 1 = 8$$$ burles.

int solution() {
  int t;
  scanf("%d", &t);
  for (int T = 0; T < t; T++) {
    int n;
    int k;
    int x;
    scanf("%d%d", &n, &k);
    int *r = calloc(k, sizeof(int));
    long long tot = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &x);
      tot += (x / k);
      r[x % k]++;
    }

    x = k >> 1;
    for (int i = 1; i < x; i++) {
      if (r[i] < r[k - i]) {
        tot += r[i];
        r[k - i - 1] = r[k - i - 1] + r[k - i] - r[i];
      } else {
        tot += r[k - i];
      }
    }
    if (k > 1) {
      if (k & 1) {
        if (r[x] >= r[x + 1]) {
          tot += r[x + 1];
        } else {
          tot = tot + r[x] + ((r[x + 1] - r[x]) >> 1);
        }
      } else {
        tot += (r[x] >> 1);
      }
    }
    printf("%lld\n", tot);
    free(r);
  }
  return 0;
}

fn solution() {
    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut scan = Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());

    let t = scan.token::<usize>();

    for _ in 0..t {
        let n = scan.token::<usize>();
        let k = scan.token::<usize>();
        let mut A = vec![];
        let mut M = vec![];
        for __ in 0..n {
            let a = scan.token::<usize>();
            A.push(a);
            M.push(a % k);
        }

        M.sort();
        let mut Q = VecDeque::new();

        for i in 0..n {
            Q.push_back(M[i]);
        }

        let mut ans = 0;
        while !Q.is_empty() {
            let f = Q.pop_front().unwrap();
            let b = Q.pop_back().unwrap();
            if (f + b) >= k {
                ans += (f + b) / k;
            } else {
                Q.push_back(b);
                let f2 = Q.pop_front().unwrap();
                ans += (f + f2) / k;
            }
        }

        for i in 0..n {
            ans += (A[i] - (A[i] % k)) / k
        }

        writeln!(out, "{}", ans);
    }
}


Nick had received an awesome array of integers $$$a=[a_1, a_2, \dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \cdot a_2 \cdot \dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \cdot a_2 \cdot \dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.

fn solution() {
    let stdin = io::stdin();
    let mut it = stdin.lock().lines();
    let _input = it.next().unwrap().unwrap();
    let input = it.next().unwrap().unwrap();
    let a: Vec<i32> = input
        .split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect();
    let b: Vec<i32> = a
        .clone()
        .into_iter()
        .map(|i| if i >= 0 { -i - 1 } else { i })
        .collect();
    let len = a.len();

    if len.is_multiple_of(2) {
        for i in b.into_iter() {
            print!("{} ", if i >= 0 { -i - 1 } else { i });
        }
    } else {
        let min = b.clone().into_iter().min().unwrap();
        let mut changed = false;
        for i in b.into_iter() {
            if i == min && !changed {
                print!("{} ", -i - 1);
                changed = true;
            } else {
                print!("{} ", i);
            }
        }
    }
}


鉛筆 (Pencils)

問題文

JOI 君は鉛筆を <var>N</var> 本買うために近くの文房具店に行くことにした．

文房具店では鉛筆が一定の本数ずつのセットで売られている．セット <var>X</var> は <var>A</var> 本で <var>B</var> 円，セット <var>Y</var> は <var>C</var> 本で <var>D</var> 円である．

JOI 君はセット <var>X</var> かセット <var>Y</var> の一方を選び，選んだセットをいくつか購入する．両方のセットを購入することはできない．<var>N</var> 本以上の鉛筆を得るために必要な金額の最小値を求めよ．

制約

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

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

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

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

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

入力・出力

入力

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

<var>N</var> <var>A</var> <var>B</var> <var>C</var> <var>D</var>

出力

JOI 君が <var>N</var> 本以上の鉛筆を手に入れるのに必要な金額の最小値を出力せよ．

入出力例

入力例 1

10 3 100 5 180

出力例 1

360

JOI 君は10本の鉛筆を入手したい．セット <var>X</var> は3本で100円，セット <var>Y</var> は5本で180円である．この時，セット <var>X</var> を選んだ場合は，セットを4つ購入する必要があり400円必要である．セット <var>Y</var> を選んだ場合は，セットを2つ購入する必要があり360円必要である．したがって，必要な金額の最小値は400円と360円の小さい方で360円である．

入力例 2

6 2 200 3 300

出力例 2

600

このとき，セット <var>X</var> を選んだ場合もセット <var>Y</var> を選んだ場合も必要な金額は600円である．必要な金額の最小値は600円である．

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

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

    let (n, a, b, c, d) = (data[0], data[1], data[2], data[3], data[4]);

    let mut total = 0;
    let mut a_money = 0;
    while n > total {
        total += a;
        a_money += b;
    }
    let mut total = 0;
    let mut c_money = 0;
    while n > total {
        total += c;
        c_money += d;
    }
    let ans = if a_money < c_money { a_money } else { c_money };
    println!("{}", ans);
}


There are two infinite sources of water:  hot water of temperature $$$h$$$;  cold water of temperature $$$c$$$ ($$$c < h$$$). You perform the following procedure of alternating moves:  take one cup of the hot water and pour it into an infinitely deep barrel;  take one cup of the cold water and pour it into an infinitely deep barrel;  take one cup of the hot water $$$\dots$$$  and so on $$$\dots$$$ Note that you always start with the cup of hot water.The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.You want to achieve a temperature as close as possible to $$$t$$$. So if the temperature in the barrel is $$$t_b$$$, then the absolute difference of $$$t_b$$$ and $$$t$$$ ($$$|t_b - t|$$$) should be as small as possible.How many cups should you pour into the barrel, so that the temperature in it is as close as possible to $$$t$$$? If there are multiple answers with the minimum absolute difference, then print the smallest of them.

int solution() {
  int T;
  scanf("%d", &T);
  long long int h;
  long long int c;
  long long int t;
  long long int min;
  long long int mid;
  long long int max;
  for (; T > 0; T--) {
    scanf("%lld %lld %lld", &h, &c, &t);
    if (h <= t) {
      printf("1\n");
      continue;
    }
    if (h + c >= 2 * t) {
      printf("2\n");
      continue;
    }
    min = 0;
    max = 1000000009;
    while (max - min > 1) {
      mid = (max + min) / 2;
      if (c * mid + h * (mid + 1) < t * (2 * mid + 1)) {
        max = mid;
      } else {
        min = mid;
      }
    }
    if ((c * min + h * (min + 1)) * (2 * max + 1) -
            t * (2 * min + 1) * (2 * max + 1) <=
        t * (2 * min + 1) * (2 * max + 1) -
            (c * max + h * (max + 1)) * (2 * min + 1)) {
      printf("%lld\n", (2 * min) + 1);
    } else {
      printf("%lld\n", (2 * max) + 1);
    }
  }
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut out = Vec::new();
    for _ in 0..t {
        let h: i64 = itr.next().unwrap().parse().unwrap();
        let c: i64 = itr.next().unwrap().parse().unwrap();
        let t: i64 = itr.next().unwrap().parse().unwrap();
        if t == h {
            writeln!(out, "1").ok();
        } else if t <= (h + c) / 2 {
            writeln!(out, "2").ok();
        } else {
            let mut l = 1;
            let mut r = 1000000;
            while r - l > 1 {
                let mid = (l + r) >> 1;

                if (h + c) * (mid - 1) + h > t * (mid * 2 - 1) {
                    l = mid;
                } else {
                    r = mid;
                }
            }

            if 2 * t * (2 * l - 1) * (2 * l + 1)
                < ((h + c) * (l - 1) + h) * (2 * l + 1) + (l * c + (l + 1) * h) * (2 * l - 1)
            {
                writeln!(out, "{}", r + r - 1).ok();
            } else {
                writeln!(out, "{}", l + l - 1).ok();
            }
        }
    }
    stdout().write_all(&out).unwrap();
}


One very important person has a piece of paper in the form of a rectangle a × b.Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees).A very important person wants to choose two different seals and put them two impressions. Each of the selected seals puts exactly one impression. Impressions should not overlap (but they can touch sides), and the total area occupied by them should be the largest possible. What is the largest area that can be occupied by two seals?

fn solution() {
    let (n, a, b) = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        let mut it = input
            .split_whitespace()
            .map(|k| k.parse::<usize>().unwrap());
        (it.next().unwrap(), it.next().unwrap(), it.next().unwrap())
    };

    let v = {
        let mut v = Vec::new();
        for _ in 0..n {
            let mut input = String::new();
            stdin().read_line(&mut input).unwrap();
            let mut it = input
                .split_whitespace()
                .map(|k| k.parse::<usize>().unwrap());
            v.push([it.next().unwrap(), it.next().unwrap()]);
        }
        v
    };

    let mut ans = 0;

    let r = [a, b];

    for (ind, p) in v.iter().enumerate() {
        for q in v.iter().skip(ind + 1) {
            for i in 0..2 {
                for j in 0..2 {
                    for k in 0..2 {
                        let i2 = (i + 1) % 2;
                        let j2 = (j + 1) % 2;
                        let k2 = (k + 1) % 2;
                        if p[i] + q[j] <= r[k] && max(p[i2], q[j2]) <= r[k2] {
                            ans = max(ans, p[0] * p[1] + q[0] * q[1]);
                        }
                    }
                }
            }
        }
    }

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


You are given a positive integer $$$n$$$, it is guaranteed that $$$n$$$ is even (i.e. divisible by $$$2$$$).You want to construct the array $$$a$$$ of length $$$n$$$ such that:   The first $$$\frac{n}{2}$$$ elements of $$$a$$$ are even (divisible by $$$2$$$);  the second $$$\frac{n}{2}$$$ elements of $$$a$$$ are odd (not divisible by $$$2$$$);  all elements of $$$a$$$ are distinct and positive;  the sum of the first half equals to the sum of the second half ($$$\sum\limits_{i=1}^{\frac{n}{2}} a_i = \sum\limits_{i=\frac{n}{2} + 1}^{n} a_i$$$). If there are multiple answers, you can print any. It is not guaranteed that the answer exists.You have to answer $$$t$$$ independent test cases.

int solution(void) {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int sum = 0;
    int num = 0;
    scanf("%d", &n);
    if (n % 4 != 0) {
      printf("NO\n");
    } else {
      printf("YES\n");
      for (int i = 1; i < (n / 2) + 1; i++) {
        int x = 2 * i;
        sum = sum + x;
        printf("%d ", 2 * i);
      }
      for (int i = 1; i < (n / 2); i++) {
        int h = (2 * i) - 1;
        num = num + h;
        printf("%d ", ((2 * i) - 1));
      }
      printf("%d", (sum - num));
      printf("\n");
    }
  }
  return 0;
}

fn solution() {
    let mut stdin = BufReader::new(io::stdin());
    let mut stdout = BufWriter::new(io::stdout());

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

        if !(n / 2).is_multiple_of(2) {
            writeln!(stdout, "NO").unwrap();
        } else {
            let mut a = vec![0; n];
            for i in (0..n / 2).step_by(2) {
                a[i] = i * 6 + 2;
                a[i + 1] = i * 6 + 4;
                a[n / 2 + i] = i * 6 + 1;
                a[n / 2 + i + 1] = i * 6 + 5;
            }
            let a: Vec<String> = a.iter().map(|x| x.to_string()).collect();
            writeln!(stdout, "YES").unwrap();
            writeln!(stdout, "{}", a.join(" ")).unwrap();
        }
    }
}


A: テスト

問題

  $N$ 個の席が一直線上に並んでいる教室で $M$ 人の生徒がテストを受けることになった。
  席には、前から $1 \dots N$ の番号が振られており、席 $1$ つにつき生徒 $1$ 人が座れる。

  いま、 各生徒は、 $A_1, \dots, A_M$ 番の席に座っている。

  テストを始めるためには、以下の条件を満たさなければならない。

 $1 \dots M$ 番のどの席にも生徒が座っている。

  そこで、条件を満たすまで次の操作を繰り返すことにした。

最も後ろに座っている生徒を移動させ、空いている席のうち最も前に座らせる。

  条件を満たすために必要な操作回数を求めよ。

制約

入力値は全て整数である。

$1 \leq N \leq 1000$

$1 \leq M \leq N$

$1 \leq A_i \leq N$

$1 \leq i < j \leq M$ ならば $A_i < A_j$

入力形式

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

  $N\ M$

  $A_1 \dots A_M$

出力

条件を満たすために必要な操作回数を出力せよ。また、末尾に改行も出力せよ。

サンプル

サンプル入力 1

6 4
1 4 5 6

サンプル出力 1

2

サンプル入力 2

10 3
1 2 3

サンプル出力 2

0

int solution() {
  int m;
  scanf("%*d%d", &m);
  int ans = 0;
  for (int i = 0; i < m; i++) {
    int t;
    scanf("%d", &t);
    if (t <= m) {
      ans++;
    }
  }
  printf("%d\n", m - ans);
}

fn solution() {
    input!(n: usize, m: usize, a: [usize1; m]);
    let mut ans = 0;
    for &a in a.iter() {
        if a >= m {
            ans += 1;
        }
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

Snuke is going to open a contest named "AtCoder <var>s</var> Contest".
Here, <var>s</var> is a string of length <var>1</var> or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.

Snuke has decided to abbreviate the name of the contest as "A<var>x</var>C".
Here, <var>x</var> is the uppercase English letter at the beginning of <var>s</var>.

Given the name of the contest, print the abbreviation of the name.

Constraints

The length of <var>s</var> is between <var>1</var> and <var>100</var>, inclusive.

The first character in <var>s</var> is an uppercase English letter.

The second and subsequent characters in <var>s</var> are lowercase English letters.

Input

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

AtCoder <var>s</var> Contest

Output

Print the abbreviation of the name of the contest.

Sample Input 1

AtCoder Beginner Contest

Sample Output 1

ABC

The contest in which you are participating now.

Sample Input 2

AtCoder Snuke Contest

Sample Output 2

ASC

This contest does not actually exist.

Sample Input 3

AtCoder X Contest

Sample Output 3

AXC

int solution(void) {
  char text0[100];
  char text[100];
  char text1[100];
  scanf("%s", text0);
  scanf("%s", text);
  scanf("%s", text1);
  printf("%c", *text0);
  printf("%c", *text);
  printf("%c", *text1);
  return 0;
}

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


For the New Year, Polycarp decided to send postcards to all his $$$n$$$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $$$w \times h$$$, which can be cut into pieces.Polycarp can cut any sheet of paper $$$w \times h$$$ that he has in only two cases:   If $$$w$$$ is even, then he can cut the sheet in half and get two sheets of size $$$\frac{w}{2} \times h$$$;  If $$$h$$$ is even, then he can cut the sheet in half and get two sheets of size $$$w \times \frac{h}{2}$$$; If $$$w$$$ and $$$h$$$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by $$$1$$$.Help Polycarp to find out if he can cut his sheet of size $$$w \times h$$$ at into $$$n$$$ or more pieces, using only the rules described above.

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

  while (t-- != 0) {

    int w = 0;
    int h = 0;
    int n = 0;
    int count = 1;

    scanf("%d%d%d", &w, &h, &n);

    while (h % 2 == 0) {
      count *= 2;
      h = h / 2;
    }
    while (w % 2 == 0) {
      count *= 2;
      w = w / 2;
    }

    if (count >= n) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }

  return 0;
}

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

    for _ in 0..n.trim().parse::<i32>().unwrap() {
        let mut a = String::new();
        io::stdin().read_line(&mut a).unwrap();

        let array = a.trim().split(" ").collect::<Vec<&str>>();
        let mut w = array[0].parse::<i32>().unwrap();
        let mut h = array[1].parse::<i32>().unwrap();
        let n = array[2].parse::<i32>().unwrap();

        let mut counter = 1;

        while w % 2 == 0 || h % 2 == 0 {
            if w % 2 == 0 {
                w /= 2;
                counter *= 2;
            } else if h % 2 == 0 {
                h /= 2;
                counter *= 2;
            };
        }

        if counter >= n {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>500</var> points

Problem Statement

There is a rooted tree (see Notes) with <var>N</var> vertices numbered <var>1</var> to <var>N</var>.
Each of the vertices, except the root, has a directed edge coming from its parent.
Note that the root may not be Vertex <var>1</var>.

Takahashi has added <var>M</var> new directed edges to this graph.
Each of these <var>M</var> edges, <var>u \rightarrow v</var>, extends from some vertex <var>u</var> to its descendant <var>v</var>.

You are given the directed graph with <var>N</var> vertices and <var>N-1+M</var> edges after Takahashi added edges.
More specifically, you are given <var>N-1+M</var> pairs of integers, <var>(A_1, B_1), ..., (A_{N-1+M}, B_{N-1+M})</var>, which represent that the <var>i</var>-th edge extends from Vertex <var>A_i</var> to Vertex <var>B_i</var>.

Restore the original rooted tree.

Notes

For "tree" and other related terms in graph theory, see the article in Wikipedia, for example.

Constraints

<var>3 \leq N</var>

<var>1 \leq M</var>

<var>N + M \leq 10^5</var>

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

<var>A_i \neq B_i</var>

If <var>i \neq j</var>, <var>(A_i, B_i) \neq (A_j, B_j)</var>.

The graph in input can be obtained by adding <var>M</var> edges satisfying the condition in the problem statement to a rooted tree with <var>N</var> vertices.

Input

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>:</var>
<var>A_{N-1+M}</var> <var>B_{N-1+M}</var>

Output

Print <var>N</var> lines.
In the <var>i</var>-th line, print 0 if Vertex <var>i</var> is the root of the original tree, and otherwise print the integer representing the parent of Vertex <var>i</var> in the original tree.

Note that it can be shown that the original tree is uniquely determined.

Sample Input 1

3 1
1 2
1 3
2 3

Sample Output 1

0
1
2

The graph in this input is shown below:

It can be seen that this graph is obtained by adding the edge <var>1 \rightarrow 3</var> to the rooted tree <var>1 \rightarrow 2 \rightarrow 3</var>.

Sample Input 2

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

Sample Output 2

6
4
2
0
6
2

int solution() {
  int n;
  int m;
  scanf("%d %d", &n, &m);
  m = n - 1 + m;
  int **graph;
  int to[100005] = {0};
  graph = (int **)malloc(sizeof(int *) * (n + 10));
  for (int i = 0; i < n + 10; i++) {
    graph[i] = (int *)malloc(sizeof(int) * (m));
  }
  while (m--) {
    int a;
    int b;
    scanf("%d %d", &a, &b);
    graph[a][++graph[a][0]] = b;
    to[b]++;
  }

  int queue[100005];
  int front = 0;
  int rear = 0;
  for (int i = 1; i <= n; i++) {
    if (!to[i]) {
      queue[rear++] = i;
    }
  }

  int topo[100005] = {0};
  while (front != rear) {
    int now = queue[front++];
    topo[++topo[0]] = now;
    for (int i = 1; i <= graph[now][0]; i++) {
      if (--to[graph[now][i]] == 0) {
        queue[rear++] = graph[now][i];
      }
    }
  }

  int ans[100005] = {0};
  for (int i = 1; i <= topo[0]; i++) {
    for (int j = 1; j <= graph[topo[i]][0]; j++) {
      ans[graph[topo[i]][j]] = topo[i];
    }
  }

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

  return 0;
}

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

    let n = get!();
    let m = get!();
    let mut tree = vec![vec![]; n];
    let mut undi = vec![vec![]; n];
    let mut cnt = vec![0_i32; n];
    let mut pair = vec![std::usize::MAX; n];
    for _ in 0..n + m - 1 {
        let a = get!() - 1;
        let b = get!() - 1;
        cnt[a] += 1;
        tree[a].push(b);
        undi[b].push(a);
    }

    let mut ps = vec![];

    for i in 0..n {
        if cnt[i] == 0 {
            ps.push(i);
        }
    }

    while !ps.is_empty() {
        for &p in ps.iter() {
            for &t in tree[p].iter() {
                if cnt[t] == 0 {
                    cnt[t] = -1;
                    pair[t] = p;
                }
            }
        }
        let mut es = vec![];
        for &p in ps.iter() {
            for &u in undi[p].iter() {
                cnt[u] -= 1;
                if cnt[u] == 0 {
                    es.push(u);
                }
            }
        }
        ps = es;
    }
    for &p in pair.iter() {
        if p == std::usize::MAX {
            println!("0");
        } else {
            println!("{}", p + 1);
        }
    }
}


You are given two strings $$$s$$$ and $$$t$$$, both consisting of exactly $$$k$$$ lowercase Latin letters, $$$s$$$ is lexicographically less than $$$t$$$.Let's consider list of all strings consisting of exactly $$$k$$$ lowercase Latin letters, lexicographically not less than $$$s$$$ and not greater than $$$t$$$ (including $$$s$$$ and $$$t$$$) in lexicographical order. For example, for $$$k=2$$$, $$$s=$$$"az" and $$$t=$$$"bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than $$$s$$$ and not greater than $$$t$$$.

fn solution() {
    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();
    let len = line.trim().parse::<usize>().unwrap();

    let mut s = String::new();
    let mut t = String::new();
    {
        let i = stdin();
        let mut lock = i.lock();
        lock.read_line(&mut s).unwrap();
        lock.read_line(&mut t).unwrap();
    }
    let s: Vec<_> = s.trim().chars().map(|c| (c as u8) - b'a').collect();
    let t: Vec<_> = t.trim().chars().map(|c| (c as u8) - b'a').collect();

    let mut sum: Vec<_> = (0..len + 1).map(|_| 0).collect();
    for i in (1..len + 1).map(|i| len + 1 - i) {
        sum[i] += s[i - 1] + t[i - 1];
        while sum[i] >= 26 {
            sum[i] -= 26;
            sum[i - 1] += 1;
        }
    }

    let mut result: Vec<_> = (0..len + 1).map(|_| 'a').collect();
    let mut carry = 0;
    for i in 0..len + 1 {
        result[i] = (b'a' + (26 * carry + sum[i]) / 2) as char;
        carry = sum[i] % 2;
    }

    let out: String = result.into_iter().skip(1).collect();
    println!("{}", out);
}


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

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

  long long result = 1 + (N + 1);
  long long i = 1;
  long long mod = 1000000007;
  long long n = (long long)N;
  while (N - i >= K) {
    long long max = ((i + 1 + n) * (n - i)) / 2;
    long long min = ((0 + n - i - 1) * (n - i)) / 2;
    result += (long long)((max - min) + 1);
    result = result % mod;
    i++;
  }
  printf("%lld\n", result);

  return 0;
}

fn solution() {
    let a: i64 = 10;
    let mo: i64 = a.pow(9) + 7;
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let (n, k) = {
        let nk: Vec<i64> = st.trim().split(" ").map(|x| x.parse().unwrap()).collect();
        (nk[0], nk[1])
    };
    let mut r: i64 = 0;
    for i in k..(n + 2) {
        let s: i64 = i * (i + 1) / 2;
        let e: i64 = i * (n + 1 + (n + 2 - i)) / 2;
        r += e - s + 1;
        r %= mo;
    }
    println!("{}", r);
}


There are n processes in a queue. Each process has namei and timei.  The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C

int solution(void) {

  int i;
  int n;
  int q;

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

  pro pr[n];

  for (i = 0; i < n; i++) {
    scanf("%*c%s %d", pr[i].na, &pr[i].ti);
  }

  int top = 0;
  int tail = 0;
  int tim = 0;
  int sta = 0;

  while (1) {

    if (sta == 1 && top == tail) {
      break;
    }

    if (pr[top].ti <= q) {

      tim += pr[top].ti;

      pr[top].ti = 0;

      printf("%s %d\n", pr[top].na, tim);

    }

    else {

      tim += q;

      pr[top].ti -= q;

      pr[tail] = pr[top];

      tail++;
    }

    top++;

    if (top != tail) {
      sta = 1;
    }

    if (top == n) {
      top = 0;
    }
    if (tail == n) {
      tail = 0;
    }
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let a = s.split_whitespace().collect::<Vec<&str>>();
    let n = a[0].parse::<usize>().unwrap();
    let q = a[1].parse::<i64>().unwrap();

    let mut queue: VecDeque<(String, i64)> = VecDeque::new();

    for _ in 0..n {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let a = s.split_whitespace().collect::<Vec<&str>>();
        let name = a[0].to_string().clone();
        let t = a[1].parse::<i64>().unwrap();
        queue.push_back((name, t));
    }

    let mut elaps = 0;
    while !queue.is_empty() {
        let mut u = queue.pop_front().unwrap();
        let a = if u.1 < q { u.1 } else { q };
        u.1 -= a;
        elaps += a;
        if u.1 > 0 {
            queue.push_back((u.0, u.1));
        } else {
            println!("{} {}", u.0, elaps);
        }
    }
}


Phoenix has decided to become a scientist! He is currently investigating the growth of bacteria.Initially, on day $$$1$$$, there is one bacterium with mass $$$1$$$.Every day, some number of bacteria will split (possibly zero or all). When a bacterium of mass $$$m$$$ splits, it becomes two bacteria of mass $$$\frac{m}{2}$$$ each. For example, a bacterium of mass $$$3$$$ can split into two bacteria of mass $$$1.5$$$.Also, every night, the mass of every bacteria will increase by one.Phoenix is wondering if it is possible for the total mass of all the bacteria to be exactly $$$n$$$. If it is possible, he is interested in the way to obtain that mass using the minimum possible number of nights. Help him become the best scientist!

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int num;
    int arr[1000000];
    scanf("%d", &num);
    int massbact = 1;
    int rate = 1;
    int count = 0;
    while (1) {
      if (num - massbact >= 4 * rate) {
        arr[count++] = rate;
        rate *= 2;
        massbact += rate;
        ;
      } else if (num - massbact <= 2 * rate) {
        arr[count++] = (num - massbact) - rate;
        break;
      } else {
        arr[count++] = (num - massbact) / 2 - rate;
        rate = (num - massbact) / 2;
        massbact += rate;
      }
    }
    printf("%d\n", count);
    for (int i = 0; i < count; i++) {
      printf("%d ", arr[i]);
    }
    printf("\n");
  }
}

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let test: u64 = str.trim().parse().unwrap();
    for _ in 0..test {
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        let mut n: i64 = str.trim().parse().unwrap();
        n -= 1;
        let mut iter = 1;
        let mut count = 0;
        let mut ans = String::new();
        loop {
            if n > 6 * iter {
                ans += &format!("{} ", iter);
                n -= 2 * iter;
                count += 1;
                iter *= 2;
            } else {
                if n <= 2 * iter {
                    println!("{}", count + 1);
                    println!("{}{}", ans, n - iter);
                } else if n <= 4 * iter {
                    println!("{}", count + 2);
                    println!("{}{} {}", ans, (n - 2 * iter) / 2, (n - 2 * iter) % 2);
                } else {
                    println!("{}", count + 2);
                    println!("{}{} {}", ans, iter, n - 4 * iter);
                }
                break;
            }
        }
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> boxes arranged in a row.
Initially, the <var>i</var>-th box from the left contains <var>a_i</var> candies.

Snuke can perform the following operation any number of times:

Choose a box containing at least one candy, and eat one of the candies in the chosen box.

His objective is as follows:

Any two neighboring boxes contain at most <var>x</var> candies in total.

Find the minimum number of operations required to achieve the objective.

Constraints

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

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

<var>0 ≤ x ≤ 10^9</var>

Input

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

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

Output

Print the minimum number of operations required to achieve the objective.

Sample Input 1

3 3
2 2 2

Sample Output 1

1

Eat one candy in the second box.
Then, the number of candies in each box becomes <var>(2, 1, 2)</var>.

Sample Input 2

6 1
1 6 1 2 0 4

Sample Output 2

11

For example, eat six candies in the second box, two in the fourth box, and three in the sixth box.
Then, the number of candies in each box becomes <var>(1, 0, 1, 0, 0, 1)</var>.

Sample Input 3

5 9
3 1 4 1 5

Sample Output 3

0

The objective is already achieved without performing operations.

Sample Input 4

2 0
5 5

Sample Output 4

10

All the candies need to be eaten.

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let mut itr = s.split_whitespace().map(|e| e.parse().unwrap());
    let _n: i64 = itr.next().unwrap();
    let x: i64 = itr.next().unwrap();
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let mut a: Vec<i64> = s.split_whitespace().map(|e| e.parse().unwrap()).collect();
    let mut ans = 0;

    for e in &mut a {
        let t = min(*e, x);
        ans += *e - t;
        *e = t;
    }

    for i in 1..a.len() {
        let t = max(0, a[i] + a[i - 1] - x);
        ans += t;
        a[i - 1] = min(a[i] + a[i - 1] - t, a[i - 1]);
        a[i] = max(0, a[i] - t);
    }

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


Polycarp wrote on the board a string $$$s$$$ containing only lowercase Latin letters ('a'-'z'). This string is known for you and given in the input.After that, he erased some letters from the string $$$s$$$, and he rewrote the remaining letters in any order. As a result, he got some new string $$$t$$$. You have to find it with some additional information.Suppose that the string $$$t$$$ has length $$$m$$$ and the characters are numbered from left to right from $$$1$$$ to $$$m$$$. You are given a sequence of $$$m$$$ integers: $$$b_1, b_2, \ldots, b_m$$$, where $$$b_i$$$ is the sum of the distances $$$|i-j|$$$ from the index $$$i$$$ to all such indices $$$j$$$ that $$$t_j > t_i$$$ (consider that 'a'<'b'<...<'z'). In other words, to calculate $$$b_i$$$, Polycarp finds all such indices $$$j$$$ that the index $$$j$$$ contains a letter that is later in the alphabet than $$$t_i$$$ and sums all the values $$$|i-j|$$$.For example, if $$$t$$$ = "abzb", then:  since $$$t_1$$$='a', all other indices contain letters which are later in the alphabet, that is: $$$b_1=|1-2|+|1-3|+|1-4|=1+2+3=6$$$;  since $$$t_2$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_2=|2-3|=1$$$;  since $$$t_3$$$='z', then there are no indexes $$$j$$$ such that $$$t_j>t_i$$$, thus $$$b_3=0$$$;  since $$$t_4$$$='b', only the index $$$j=3$$$ contains the letter, which is later in the alphabet, that is: $$$b_4=|4-3|=1$$$. Thus, if $$$t$$$ = "abzb", then $$$b=[6,1,0,1]$$$.Given the string $$$s$$$ and the array $$$b$$$, find any possible string $$$t$$$ for which the following two requirements are fulfilled simultaneously:  $$$t$$$ is obtained from $$$s$$$ by erasing some letters (possibly zero) and then writing the rest in any order;  the array, constructed from the string $$$t$$$ according to the rules above, equals to the array $$$b$$$ specified in the input data.

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

    for _ in 0..q {
        let s: Vec<char> = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            buf.trim_end().chars().collect()
        };
        let m: usize = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            buf.trim_end().parse().unwrap()
        };
        let mut b: 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 counts = std::collections::BTreeMap::new();
        for i in 0..s.len() {
            *counts.entry(s[i]).or_insert(0) += 1;
        }
        let mut iter = counts.iter().rev();

        let mut t = vec!['?'; m];
        loop {
            let mut pos = Vec::new();
            for i in 0..m {
                if b[i] == 0 {
                    pos.push(i);
                }
            }
            if pos.is_empty() {
                break;
            }
            for i in 0..m {
                if b[i] == 0 {
                    b[i] = std::usize::MAX;
                } else {
                    for &j in &pos {
                        b[i] -= j.abs_diff(i);
                    }
                }
            }
            for (&c, &count) in iter.by_ref() {
                if count >= pos.len() {
                    for &j in &pos {
                        t[j] = c;
                    }
                    break;
                }
            }
        }

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


Score : <var>200</var> points

Problem Statement

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

Snuke can perform the following operation when all integers on the blackboard are even:

Replace each integer <var>X</var> on the blackboard by <var>X</var> divided by <var>2</var>.

Find the maximum possible number of operations that Snuke can perform.

Constraints

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

<var>1 \leq A_i \leq 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>A_N</var>

Output

Print the maximum possible number of operations that Snuke can perform.

Sample Input 1

3
8 12 40

Sample Output 1

2

Initially, <var>[8, 12, 40]</var> are written on the blackboard.
Since all those integers are even, Snuke can perform the operation.

After the operation is performed once, <var>[4, 6, 20]</var> are written on the blackboard.
Since all those integers are again even, he can perform the operation.

After the operation is performed twice, <var>[2, 3, 10]</var> are written on the blackboard.
Now, there is an odd number <var>3</var> on the blackboard, so he cannot perform the operation any more.

Thus, Snuke can perform the operation at most twice.

Sample Input 2

4
5 6 8 10

Sample Output 2

0

Since there is an odd number <var>5</var> on the blackboard already in the beginning, Snuke cannot perform the operation at all.

Sample Input 3

6
382253568 723152896 37802240 379425024 404894720 471526144

Sample Output 3

8

int solution(void) {
  int data[200];
  int max = 0;
  int result = 0;
  int i = 0;
  int j = 0;
  scanf("%d", &max);
  for (i = 0; i < max; i++) {
    scanf("%d", &data[i]);
  }
  i = 0;
  for (; i == 0;) {
    for (j = 0; j < max; j++) {
      if (data[j] % 2 != 0) {
        i = 1;
        break;
      }
      data[j] /= 2;
    }
    result++;
  }
  printf("%d", result - 1);
  return 0;
}

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

    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let ns = buffer.trim().split(' ').collect::<Vec<&str>>();
    let xs = ns.into_iter().map(|n| {
        let mut counter = 0;
        let mut x = n.parse::<u32>().unwrap();
        while x % 2 == 0 {
            x /= 2;
            counter += 1;
        }
        counter
    });
    println!("{}", xs.min().unwrap());
}


You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.

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

    use std::io::prelude::*;
    std::io::stdin().read_to_string(&mut input).unwrap();
    let mut it = input.split_whitespace();

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

    let mut cnt = (0, 0);

    for _ in 0..n {
        let (x, _y): (i32, i32) = (
            it.next().unwrap().parse().unwrap(),
            it.next().unwrap().parse().unwrap(),
        );
        if x > 0 {
            cnt.1 += 1;
        } else {
            cnt.0 += 1;
        }
    }

    let ans = cnt.0 <= 1 || cnt.1 <= 1;
    if ans {
        println!("Yes");
    } else {
        println!("No");
    }
}


The only difference between easy and hard versions is the maximum value of $$$n$$$.You are given a positive integer number $$$n$$$. You really love good numbers so you want to find the smallest good number greater than or equal to $$$n$$$.The positive integer is called good if it can be represented as a sum of distinct powers of $$$3$$$ (i.e. no duplicates of powers of $$$3$$$ are allowed).For example:  $$$30$$$ is a good number: $$$30 = 3^3 + 3^1$$$,  $$$1$$$ is a good number: $$$1 = 3^0$$$,  $$$12$$$ is a good number: $$$12 = 3^2 + 3^1$$$,  but $$$2$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ ($$$2 = 3^0 + 3^0$$$),  $$$19$$$ is not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representations $$$19 = 3^2 + 3^2 + 3^0 = 3^2 + 3^1 + 3^1 + 3^1 + 3^0$$$ are invalid),  $$$20$$$ is also not a good number: you can't represent it as a sum of distinct powers of $$$3$$$ (for example, the representation $$$20 = 3^2 + 3^2 + 3^0 + 3^0$$$ is invalid). Note, that there exist other representations of $$$19$$$ and $$$20$$$ as sums of powers of $$$3$$$ but none of them consists of distinct powers of $$$3$$$.For the given positive integer $$$n$$$ find such smallest $$$m$$$ ($$$n \le m$$$) that $$$m$$$ is a good number.You have to answer $$$q$$$ independent queries.

int solution() {
  int q;
  scanf("%d", &q);
  while (q--) {
    int n;
    scanf("%d", &n);

    int i = n;
    while (1) {
      n = i;
      int res = 0;
      while (n > 0) {
        if (n % 3 == 0) {
          n = n / 3;
        } else {
          n--;
          if (n % 3 == 0) {
            n = n / 3;
          } else {
            res = 1;
            break;
          }
        }
      }
      if (res == 0) {
        break;
      }
      i++;
    }
    printf("%d\n", i);
  }
}

fn solution() {
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read input");
    let q: u16 = buffer.trim().parse().expect("invalid input");

    for _ in 0..q {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let a: u64 = input.trim().parse().unwrap();
        let mut p3: Vec<u8> = Vec::with_capacity(39);
        let mut a_mut = a;
        while a_mut != 0 {
            p3.push((a_mut % 3) as u8);
            a_mut /= 3;
        }
        p3.push(0);

        match p3.iter().rposition(|&x| x == 2) {
            Some(x) => {
                for i in 0..=x {
                    p3[i] = 0;
                }

                let mut pos = x + 1;
                while p3[pos] != 0 {
                    p3[pos] = 0;
                    pos += 1;
                }
                p3[pos] = 1;
                let mut total: u64 = 0;
                for i in p3[pos..].iter().rev() {
                    total = 3 * total + *i as u64;
                }
                total *= 3u64.pow(pos as u32);

                println!("{}", total);
            }
            None => {
                println!("{}", a);
            }
        }
    }
}


Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P = [p1, p2, ..., pn], where pi denotes the number of page that should be read i-th in turn.Sometimes Vladik’s mom sorted some subsegment of permutation P from position l to position r inclusive, because she loves the order. For every of such sorting Vladik knows number x — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has px changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.

fn solution() {
    let (_n, m) = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let mut it = input
            .split_whitespace()
            .map(|k| k.parse::<usize>().unwrap());
        (it.next().unwrap(), it.next().unwrap())
    };

    let p: Vec<usize> = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input
            .split_whitespace()
            .map(|k| k.parse().unwrap())
            .collect()
    };

    for _ in 0..m {
        let (l, r, x) = {
            let mut input = String::new();
            io::stdin().read_line(&mut input).unwrap();
            let mut it = input
                .split_whitespace()
                .map(|k| k.parse::<usize>().unwrap());
            (
                it.next().unwrap() - 1,
                it.next().unwrap(),
                it.next().unwrap() - 1,
            )
        };

        let pos = l + p[l..r].iter().filter(|&&k| k < p[x]).count();
        if x == pos {
            println!("Yes");
        } else {
            println!("No");
        }
    }
}


You are given a sequence $$$a=[a_1,a_2,\dots,a_n]$$$ consisting of $$$n$$$ positive integers.Let's call a group of consecutive elements a segment. Each segment is characterized by two indices: the index of its left end and the index of its right end. Denote by $$$a[l,r]$$$ a segment of the sequence $$$a$$$ with the left end in $$$l$$$ and the right end in $$$r$$$, i.e. $$$a[l,r]=[a_l, a_{l+1}, \dots, a_r]$$$.For example, if $$$a=[31,4,15,92,6,5]$$$, then $$$a[2,5]=[4,15,92,6]$$$, $$$a[5,5]=[6]$$$, $$$a[1,6]=[31,4,15,92,6,5]$$$ are segments.We split the given sequence $$$a$$$ into segments so that:   each element is in exactly one segment;  the sums of elements for all segments are equal. For example, if $$$a$$$ = [$$$55,45,30,30,40,100$$$], then such a sequence can be split into three segments: $$$a[1,2]=[55,45]$$$, $$$a[3,5]=[30, 30, 40]$$$, $$$a[6,6]=[100]$$$. Each element belongs to exactly segment, the sum of the elements of each segment is $$$100$$$.Let's define thickness of split as the length of the longest segment. For example, the thickness of the split from the example above is $$$3$$$.Find the minimum thickness among all possible splits of the given sequence of $$$a$$$ into segments in the required way.

int solution(void) {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    scanf("%d", &n);
    int seq[n];
    int seq_sum[n];
    scanf("%d", &seq[0]);
    seq_sum[0] = seq[0];
    for (int j = 1; j < n; j++) {
      scanf("%d", &seq[j]);
      seq_sum[j] = seq_sum[j - 1] + seq[j];
    }
    int min_len = INT32_MAX;
    for (int first_end = 0; first_end < n; first_end++) {
      int each_sum = seq_sum[first_end];
      int max_len = first_end + 1;
      if (seq_sum[n - 1] % each_sum != 0) {
        continue;
      }
      int ptr = first_end;
      int ptr_prev = ptr;
      for (int j = 2; j < seq_sum[n - 1] / each_sum; j++) {
        while (ptr < n && seq_sum[ptr] % (each_sum * j)) {
          ptr++;
        }
        int distance = ptr - ptr_prev;
        max_len = max_len > distance ? max_len : distance;
        ptr_prev = ptr;
      }
      if (ptr >= n) {
        continue;
      }
      int distance = n - 1 - ptr;
      max_len = max_len > distance ? max_len : distance;
      min_len = max_len > min_len ? min_len : max_len;
    }
    printf("%d\n", min_len);
  }
  return 0;
}

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

    for _ in 0..tests {
        let mut testline = String::new();
        io::stdin().read_line(&mut testline).unwrap();
        testline = String::new();
        io::stdin().read_line(&mut testline).unwrap();
        let numbers: Vec<i64> = testline
            .split_whitespace()
            .map(|s| s.trim().parse().unwrap())
            .collect();
        let mut minimal_thickness = numbers.len();
        let mut first_thickness = 0;
        let mut part_sum = 0;
        while part_sum + numbers[first_thickness] < *numbers.iter().max().unwrap() {
            part_sum += numbers[first_thickness];
            first_thickness += 1;
        }

        while first_thickness < numbers.len() && minimal_thickness > first_thickness {
            part_sum += numbers[first_thickness];
            first_thickness += 1;
            let mut idx = first_thickness;
            let mut thickness = first_thickness;
            while idx < numbers.len() {
                let mut part = 0;
                let mut part_length = 0;
                while part < part_sum && idx < numbers.len() {
                    part += numbers[idx];
                    idx += 1;
                    part_length += 1;
                }
                if part != part_sum {
                    thickness = numbers.len();
                    break;
                } else {
                    thickness = cmp::max(thickness, part_length);
                }
            }
            if idx == numbers.len() {
                minimal_thickness = cmp::min(thickness, minimal_thickness);
            }
        }
        println!("{minimal_thickness}")
    }
}


A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $$$n$$$ and $$$k$$$, where $$$n$$$ is even. Next, he takes all the integers from $$$1$$$ to $$$n$$$, and splits them all into pairs $$$(a, b)$$$ (each integer must be in exactly one pair) so that for each pair the integer $$$(a + k) \cdot b$$$ is divisible by $$$4$$$ (note that the order of the numbers in the pair matters), or reports that, unfortunately for viewers, such a split is impossible.Burenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers $$$n$$$ and $$$k$$$.Tonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it.

int solution() {
  int numSets = 0;

  scanf("%d", &numSets);

  for (int current_set = 0; current_set < numSets; ++current_set) {

    int n = 0;
    int k = 0;
    scanf("%d %d", &n, &k);
    if (n % 2 == 1) {
      printf("NO\n");
    }
    int k_remnant = k % 4;
    switch (k_remnant) {
    case 0: {
      printf("NO\n");
      break;
    }
    case 2: {
      printf("YES\n");

      int main_cycle_elements = n & (~3);
      for (int i = 0; i < main_cycle_elements; i += 4) {
        printf("%d %d\n", i + 2, i + 1);
        printf("%d %d\n", i + 3, i + 4);
      }
      if (n > main_cycle_elements) {
        printf("%d %d\n", n, n - 1);
      }
      break;
    }
    default: {
      printf("YES\n");

      for (int i = 0; i < n; i += 2) {
        printf("%d %d\n", i + 1, i + 2);
      }
      break;
    }
    }
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut iterator = stdin.lock().lines();
    let line = iterator.next().unwrap().unwrap();
    let amount = line.parse::<i32>().unwrap();
    for _i in 0..amount {
        let line = iterator.next().unwrap().unwrap();
        let strings: Vec<&str> = line.split(" ").collect();
        let n = strings.first().unwrap().parse::<i32>().unwrap();
        let k = strings.get(1).unwrap().parse::<i32>().unwrap();
        if k % 4 == 0 {
            println!("NO");
        } else if k % 2 == 1 {
            println!("YES");
            let mut x = 1;
            while x < n {
                println!("{} {}", x, x + 1);
                x += 2;
            }
        } else {
            println!("YES");
            let mut x = 1;
            while x < n {
                if (x + k) * (x + 1) % 4 == 0 {
                    println!("{} {}", x, x + 1);
                } else {
                    println!("{} {}", x + 1, x);
                }
                x += 2;
            }
        }
    }
}


Score : <var>100</var> points

Problem Statement

Snuke prepared <var>6</var> problems for a upcoming programming contest.
For each of those problems, Rng judged whether it can be used in the contest or not.

You are given a string <var>S</var> of length <var>6</var>.
If the <var>i</var>-th character of <var>s</var> is 1, it means that the <var>i</var>-th problem prepared by Snuke is accepted to be used; 0 means that the problem is not accepted.

How many problems prepared by Snuke are accepted to be used in the contest?

Constraints

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

<var>S</var> consists of 0 and 1.

Inputs

Input is given from Standard Input in the following format:

<var>S</var>

Outputs

Print the number of problems prepared by Snuke that are accepted to be used in the contest.

Sample Input 1

111100

Sample Output 1

4

The first, second, third and fourth problems are accepted, for a total of four.

Sample Input 2

001001

Sample Output 2

2

Sample Input 3

000000

Sample Output 3

0

fn solution() {
    println!(
        "{}",
        io::stdin()
            .bytes()
            .take(6)
            .filter(|r| r.as_ref().map(|b| b'1' == *b).unwrap_or(false))
            .count()
    );
}


Mikhail walks on a Cartesian plane. He starts at the point $$$(0, 0)$$$, and in one move he can go to any of eight adjacent points. For example, if Mikhail is currently at the point $$$(0, 0)$$$, he can go to any of the following points in one move:   $$$(1, 0)$$$;  $$$(1, 1)$$$;  $$$(0, 1)$$$;  $$$(-1, 1)$$$;  $$$(-1, 0)$$$;  $$$(-1, -1)$$$;  $$$(0, -1)$$$;  $$$(1, -1)$$$. If Mikhail goes from the point $$$(x1, y1)$$$ to the point $$$(x2, y2)$$$ in one move, and $$$x1 \ne x2$$$ and $$$y1 \ne y2$$$, then such a move is called a diagonal move.Mikhail has $$$q$$$ queries. For the $$$i$$$-th query Mikhail's target is to go to the point $$$(n_i, m_i)$$$ from the point $$$(0, 0)$$$ in exactly $$$k_i$$$ moves. Among all possible movements he want to choose one with the maximum number of diagonal moves. Your task is to find the maximum number of diagonal moves or find that it is impossible to go from the point $$$(0, 0)$$$ to the point $$$(n_i, m_i)$$$ in $$$k_i$$$ moves.Note that Mikhail can visit any point any number of times (even the destination point!).

int solution() {
  int q;
  scanf("%d", &q);
  while (q--) {
    long long int a[3];
    int i;
    for (i = 0; i < 3; i++) {
      scanf("%lld", &a[i]);
    }
    long long int bigger;
    long long int smaller;
    long long int ans = 0;
    if (a[0] > a[1]) {
      bigger = a[0];
      smaller = a[1];
    } else {
      bigger = a[1];
      smaller = a[0];
    }

    if (bigger > a[2]) {
      printf("-1\n");
    } else {
      long long int rem = a[2];
      if ((bigger % 2 == 0 && smaller % 2 == 0) ||
          (bigger % 2 == 1 && smaller % 2 == 1)) {
        ans = ans + bigger - 1;
        rem = rem - (bigger - 1);
        if ((rem) % 2 == 1) {
          ans += rem;
        } else {
          ans += rem - 2;
        }
      } else {
        ans = ans + rem - 1;
      }
      printf("%lld\n", ans);
    }
  }

  return 0;
}

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

    handle.read_to_string(&mut buffer).expect("stdin");

    let arr: Vec<_> = buffer
        .split_whitespace()
        .map(|x| x.parse::<i64>().unwrap())
        .collect();

    let mut ind = 0;
    let q = arr[ind];
    ind += 1;

    for _i in 0..q {
        let x2 = arr[ind];
        ind += 1;
        let y2 = arr[ind];
        ind += 1;
        let k = arr[ind];
        ind += 1;

        let _ans = 0;

        let dx = x2.abs();
        let dy = y2.abs();
        use std::cmp;
        let mut num_diagonals = cmp::min(dx, dy);
        let mut num_straight = dx - num_diagonals + dy - num_diagonals;

        num_diagonals += (num_straight / 2) * 2;
        num_straight %= 2;

        let moves = num_diagonals + num_straight;

        if moves > k {
            println!("-1");
        } else {
            let mut moves_left = k - moves;
            if moves_left == 0 {
                println!("{}", num_diagonals);
            } else {
                if num_straight > 0 && moves_left >= 3 {
                    let rep_diag = moves_left / 3;
                    num_diagonals += rep_diag * 3;
                    moves_left %= 3;
                }

                if moves_left >= 2 {
                    let rep_diag = moves_left / 2;
                    num_diagonals += rep_diag * 2;
                    moves_left %= 2;
                }

                if moves_left > 0 {
                    if num_straight > 0 {
                        num_diagonals += 1;
                    } else {
                        num_diagonals -= 1;
                    }
                }
                println!("{}", num_diagonals);
            }
        }
    }
}


Structured Programming

In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops.

Note that use of goto statement is highly discouraged, because it is difficult to trace the control flow of a program which includes goto.

Write a program which does precisely the same thing as the following program (this example is wrtten in C++). Let's try to write the program without goto statements.

void call(int n){
  int i = 1;
 CHECK_NUM:
  int x = i;
  if ( x % 3 == 0 ){
    cout << " " << i;
    goto END_CHECK_NUM;
  }
 INCLUDE3:
  if ( x % 10 == 3 ){
    cout << " " << i;
    goto END_CHECK_NUM;
  }
  x /= 10;
  if ( x ) goto INCLUDE3;
 END_CHECK_NUM:
  if ( ++i <= n ) goto CHECK_NUM;

  cout << endl;
}

Input

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

Output

Print the output result of the above program for given integer <var>n</var>.

Constraints

3 ≤ n ≤ 10000

Sample Input

30

Sample Output

 3 6 9 12 13 15 18 21 23 24 27 30

  Put a single space character before each element.

int solution(void) {
  int n;
  scanf("%d", &n);
  for (int i = 3; i <= n; i++) {
    if (i % 3 == 0) {
      printf(" %d", i);
      continue;
    }
    for (int j = 1; j <= n * 10; j *= 10) {
      if ((i / j) % 10 == 3) {
        printf(" %d", i);
        break;
      }
    }
  }
  printf("\n");
  return 0;
}

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

    for i in 1..n + 1 {
        if i % 3 == 0 || i.to_string().contains("3") {
            print!(" {}", i);
        }
    }
    println!();
}


Score : <var>200</var> points

Problem Statement

Takahashi loves palindromes. Non-palindromic strings are unacceptable to him. Each time he hugs a string, he can change one of its characters to any character of his choice.

Given is a string <var>S</var>. Find the minimum number of hugs needed to make <var>S</var> palindromic.

Constraints

<var>S</var> is a string consisting of lowercase English letters.

The length of <var>S</var> is between <var>1</var> and <var>100</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the minimum number of hugs needed to make <var>S</var> palindromic.

Sample Input 1

redcoder

Sample Output 1

1

For example, we can change the fourth character to o and get a palindrome redooder.

Sample Input 2

vvvvvv

Sample Output 2

0

We might need no hugs at all.

Sample Input 3

abcdabc

Sample Output 3

2

int solution() {
  char a[100];
  int i = 0;
  int count = 0;
  int change = 0;
  scanf("%s", &a[0]);
  for (count = 0; a[count] != '\0'; count++) {
    ;
  }
  for (i = 0; i < count / 2; i++) {
    if (a[i] != a[count - i - 1]) {
      change++;
    }
  }
  printf("%d\n", change);
  return 0;
}

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

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

    let s = s.trim();

    let n = s.len();
    let s: Vec<char> = s.chars().collect();

    let mut answer = 0;

    for i in 0..n {
        if s[i] != s[n - i - 1] {
            answer += 1;
        }
    }

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


階乗 II

<var>n! = n × (n − 1) × (n − 2) ×</var> ... <var> × 3 × 2 × 1</var>

を <var>n</var> の階乗といいます。例えば、12 の階乗は

<var>12! = 12 × 11 × 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 = 479001600</var>

となり、末尾に 0 が 2 つ連続して並んでいます。

整数 <var>n</var> を入力して、<var>n!</var> の末尾に連続して並んでいる 0 の数を出力するプログラムを作成してください。ただし、<var>n</var> は 20000 以下の正の整数とします。

Input

複数のデータが与えられます。各データに <var>n</var> (<var>n</var> ≤ 20000) が１行に与えられます。<var>n</var> が 0 の時入力の最後とします。

データの数は 20 を超えません。

Output

各データに対して <var>n!</var> の末尾に連続して並んでいる 0 の数を１行に出力して下さい。

Sample Input

2
12
10000
0

Output for the Sample Input

0
2
2499

int solution() {
  while (1) {
    int n;
    int c = 0;
    int k = 5;
    scanf("%d", &n);
    if (n == 0) {
      break;
    }
    while (k < 20000) {
      c += n / (k);
      k *= 5;
    }

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

fn solution() {
    let mut input;
    loop {
        input = String::new();
        std::io::stdin().read_line(&mut input).expect("Input error");
        let mut n = input.trim().parse::<u64>().expect("Error parse");
        if n == 0 {
            break;
        }
        let mut zero = 0;
        while n >= 5 {
            zero += n / 5;
            n /= 5;
        }
        println!("{}", zero);
    }
}


A chess tournament will be held soon, where $$$n$$$ chess players will take part. Every participant will play one game against every other participant. Each game ends in either a win for one player and a loss for another player, or a draw for both players.Each of the players has their own expectations about the tournament, they can be one of two types:  a player wants not to lose any game (i. e. finish the tournament with zero losses);  a player wants to win at least one game. You have to determine if there exists an outcome for all the matches such that all the players meet their expectations. If there are several possible outcomes, print any of them. If there are none, report that it's impossible.

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let v = l
            .unwrap()
            .chars()
            .map(|c| c.to_digit(10).unwrap())
            .collect::<Vec<_>>();
        let t = v.iter().filter(|&c| *c == 2).count();
        if matches!(t, 1 | 2) {
            writeln!(o, "NO").ok();
            continue;
        }
        let mut r = vec![vec!['X'; v.len()]; v.len()];
        let s = ['+', '-'];
        for j in 0..v.len() {
            let mut w = 0;
            for k in j..v.len() {
                if j == k {
                    continue;
                }
                let (a, b) = match (v[j], v[k]) {
                    (1, _) | (_, 1) => ('=', '='),
                    _ => {
                        w ^= 1;
                        (s[w], s[w ^ 1])
                    }
                };
                r[j][k] = a;
                r[k][j] = b;
            }
        }
        let s: String = r
            .iter()
            .map(|v| v.iter().collect::<String>() + "\n")
            .collect();
        writeln!(o, "YES\n{}", s.trim()).ok();
    }
}


You are given an array $$$a$$$ of length $$$n$$$.Let's define the eversion operation. Let $$$x = a_n$$$. Then array $$$a$$$ is partitioned into two parts: left and right. The left part contains the elements of $$$a$$$ that are not greater than $$$x$$$ ($$$\le x$$$). The right part contains the elements of $$$a$$$ that are strictly greater than $$$x$$$ ($$$> x$$$). The order of elements in each part is kept the same as before the operation, i. e. the partition is stable. Then the array is replaced with the concatenation of the left and the right parts.For example, if the array $$$a$$$ is $$$[2, 4, 1, 5, 3]$$$, the eversion goes like this: $$$[2, 4, 1, 5, 3] \to [2, 1, 3], [4, 5] \to [2, 1, 3, 4, 5]$$$.We start with the array $$$a$$$ and perform eversions on this array. We can prove that after several eversions the array $$$a$$$ stops changing. Output the minimum number $$$k$$$ such that the array stops changing after $$$k$$$ eversions.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int a[n];
    int max = -1;
    int end = 0;
    int count = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
      if (a[i] >= max) {
        max = a[i];
        end = i;
      }
    }
    int prev = -1;
    for (int i = n - 1; i > end; i--) {
      if (a[i] > prev) {
        count++;
        prev = a[i];
      }
    }
    printf("%d\n", count);
  }

  return 0;
}

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

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

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

        let max = *array.iter().max().unwrap();
        let mut counter = 0;
        let mut element = array[0];

        for value in array {
            if value > element {
                element = value;
                counter += 1;
            }

            if value == max {
                break;
            }
        }

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


Polycarp found a rectangular table consisting of $$$n$$$ rows and $$$m$$$ columns. He noticed that each cell of the table has its number, obtained by the following algorithm "by columns":   cells are numbered starting from one;  cells are numbered from left to right by columns, and inside each column from top to bottom;  number of each cell is an integer one greater than in the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, the table will be numbered as follows:$$$$$$ \begin{matrix} 1 & 4 & 7 & 10 & 13 \\ 2 & 5 & 8 & 11 & 14 \\ 3 & 6 & 9 & 12 & 15 \\ \end{matrix} $$$$$$However, Polycarp considers such numbering inconvenient. He likes the numbering "by rows":   cells are numbered starting from one;  cells are numbered from top to bottom by rows, and inside each row from left to right;  number of each cell is an integer one greater than the number of the previous cell. For example, if $$$n = 3$$$ and $$$m = 5$$$, then Polycarp likes the following table numbering: $$$$$$ \begin{matrix} 1 & 2 & 3 & 4 & 5 \\ 6 & 7 & 8 & 9 & 10 \\ 11 & 12 & 13 & 14 & 15 \\ \end{matrix} $$$$$$Polycarp doesn't have much time, so he asks you to find out what would be the cell number in the numbering "by rows", if in the numbering "by columns" the cell has the number $$$x$$$?

int solution() {
  int t;
  scanf("%d", &t);
  long long n[t];
  long long m[t];
  long long x[t];
  long long c;
  long long r;
  for (int i = 0; i < t; ++i) {
    scanf("%lld %lld %lld", &n[i], &m[i], &x[i]);
    c = x[i] / n[i];
    r = x[i] % n[i];
    if (r == 0) {
      r = n[i];
    } else {
      ++c;
    }
    x[i] = (r - 1) * m[i] + c;
  }
  for (int i = 0; i < t; ++i) {
    printf("%lld\n", x[i]);
  }

  return 0;
}

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

    let case_count: usize = input.trim_end().parse()?;
    input.clear();
    for _ in 0..case_count {
        stdin.read_line(&mut input)?;
        let mut vals = input.trim_end().split_ascii_whitespace();

        let n: i64 = vals.next().unwrap().parse()?;
        let m: i64 = vals.next().unwrap().parse()?;
        let x: i64 = vals.next().unwrap().parse()?;
        input.clear();

        let col = (x - 1) / n;
        let row = (x - 1) % n;

        writeln!(&mut stdout, "{}", (row) * m + (col + 1))?;
    }

    Ok(())
}


Score: <var>400</var> points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next <var>N</var> days. Currently, he has <var>1000</var> yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next <var>N</var> days will be as follows:

<var>A_1</var> yen on the <var>1</var>-st day, <var>A_2</var> yen on the <var>2</var>-nd day, ..., <var>A_N</var> yen on the <var>N</var>-th day.

In the <var>i</var>-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay <var>A_i</var> yen and receive one stock.

Sell stock: Sell one stock for <var>A_i</var> yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

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

<var>100 \leq A_i \leq 200</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>\cdots</var> <var>A_N</var>

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have <var>1685</var> yen in the end is as follows:

Initially, he has <var>1000</var> yen and no stocks.

Day <var>1</var>: Buy <var>10</var> stocks for <var>1000</var> yen. Now he has <var>0</var> yen.

Day <var>2</var>: Sell <var>7</var> stocks for <var>910</var> yen. Now he has <var>910</var> yen.

Day <var>3</var>: Sell <var>3</var> stocks for <var>390</var> yen. Now he has <var>1300</var> yen.

Day <var>4</var>: Do nothing.

Day <var>5</var>: Buy <var>1</var> stock for <var>115</var> yen. Now he has <var>1185</var> yen.

Day <var>6</var>: Buy <var>10</var> stocks for <var>1150</var> yen. Now he has <var>35</var> yen.

Day <var>7</var>: Sell <var>11</var> stocks for <var>1650</var> yen. Now he has <var>1685</var> yen.

There is no way to have <var>1686</var> yen or more in the end, so the answer is <var>1685</var>.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have <var>1000</var> yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy <var>6</var> stocks in Day <var>1</var> and sell them in Day <var>2</var>, after which we will have <var>1216</var> yen.

int solution(void) {

  long n;
  scanf("%ld", &n);
  long a[n];
  for (long i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
  }
  long stock = 0;
  long money = 1000;
  int flag = 0;
  for (long i = 0; i < n; i++) {
    if (flag == 0) {
      if (i != n - 1 && a[i] < a[i + 1]) {
        stock += money / a[i];
        money %= a[i];
        flag = 1;
      }
    } else {
      if (i == n - 1 || (i != n - 1 && a[i] > a[i + 1])) {
        money += stock * a[i];
        stock = 0;
        flag = 0;
      }
    }
  }
  printf("%ld\n", money);

  return 0;
}

fn solution() {
    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 money = 1000;
    let mut stock = 0;
    let mut s = 'n';
    for i in 1..n {
        if a[i - 1] < a[i] {
            if s != 'u' {
                stock += money / a[i - 1];
                money %= a[i - 1];
            }
            s = 'u';
        } else if a[i - 1] > a[i] {
            if s != 'd' {
                money += stock * a[i - 1];
                stock = 0;
            }
            s = 'd';
        }
    }
    money += stock * a[n - 1];
    println!("{}", money);
}


Polycarp has a poor memory. Each day he can remember no more than $$$3$$$ of different letters. Polycarp wants to write a non-empty string of $$$s$$$ consisting of lowercase Latin letters, taking minimum number of days. In how many days will he be able to do it?Polycarp initially has an empty string and can only add characters to the end of that string.For example, if Polycarp wants to write the string lollipops, he will do it in $$$2$$$ days:   on the first day Polycarp will memorize the letters l, o, i and write lolli;  On the second day Polycarp will remember the letters p, o, s, add pops to the resulting line and get the line lollipops. If Polycarp wants to write the string stringology, he will do it in $$$4$$$ days:   in the first day will be written part str;  on day two will be written part ing;  on the third day, part of olog will be written;  on the fourth day, part of y will be written. For a given string $$$s$$$, print the minimum number of days it will take Polycarp to write it.

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Error!");
    let x: i32 = line.trim().parse().expect("Error!");

    for _ in 0..x {
        let mut stroke = String::new();
        io::stdin().read_line(&mut stroke).expect("Error!");

        let mut res = 1;
        let mut daily_let: Vec<char> = Vec::new();
        for ch in stroke.chars() {
            if ch == '\n' || ch == '\r' {
                break;
            }
            if daily_let.len() >= 3 && !daily_let.contains(&ch) {
                daily_let.clear();
                daily_let.push(ch);
                res += 1;
            }
            if !daily_let.contains(&ch) {
                daily_let.push(ch);
            }
        }
        println!("{}", res);
    }
}


Score : <var>100</var> points

Problem Statement

ButCoder Inc. runs a programming competition site called ButCoder. In this site, a user is given an integer value called rating that represents his/her skill, which changes each time he/she participates in a contest. The initial value of a new user's rating is <var>0</var>, and a user whose rating reaches <var>K</var> or higher is called Kaiden ("total transmission"). Note that a user's rating may become negative.

Hikuhashi is a new user in ButCoder. It is estimated that, his rating increases by <var>A</var> in each of his odd-numbered contests (first, third, fifth, ...), and decreases by <var>B</var> in each of his even-numbered contests (second, fourth, sixth, ...).

According to this estimate, after how many contests will he become Kaiden for the first time, or will he never become Kaiden?

Constraints

<var>1 ≤ K, A, B ≤ 10^{18}</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If it is estimated that Hikuhashi will never become Kaiden, print -1. Otherwise, print the estimated number of contests before he become Kaiden for the first time.

Sample Input 1

4000 2000 500

Sample Output 1

5

Each time Hikuhashi participates in a contest, his rating is estimated to change as <var>0</var> → <var>2000</var> → <var>1500</var> → <var>3500</var> → <var>3000</var> → <var>5000</var> → <var>…</var> After his fifth contest, his rating will reach <var>4000</var> or higher for the first time.

Sample Input 2

4000 500 2000

Sample Output 2

-1

Each time Hikuhashi participates in a contest, his rating is estimated to change as <var>0</var> → <var>500</var> → <var>-1500</var> → <var>-1000</var> → <var>-3000</var> → <var>-2500</var> → <var>…</var> He will never become Kaiden.

Sample Input 3

1000000000000000000 2 1

Sample Output 3

1999999999999999997

The input and output values may not fit into <var>32</var>-bit integers.

int solution() {
  long long a;
  long long b;
  long long c;
  scanf("%lld %lld %lld", &a, &b, &c);
  if (a <= b) {
    printf("1\n");
  } else if (b <= c) {
    printf("-1\n");
  } else {
    printf("%lld\n", ((a - b - 1) / (b - c) * 2) + 3);
  }
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let k: usize = itr.next().unwrap().parse().unwrap();
    let a: usize = itr.next().unwrap().parse().unwrap();
    let b: usize = itr.next().unwrap().parse().unwrap();
    if k <= a {
        println!("1");
    } else if a <= b {
        println!("-1");
    } else {
        println!("{}", (k - a).div_ceil(a - b) * 2 + 1);
    }
}


There are n pictures delivered for the new exhibition. The i-th painting has beauty ai. We know that a visitor becomes happy every time he passes from a painting to a more beautiful one.We are allowed to arranged pictures in any order. What is the maximum possible number of times the visitor may become happy while passing all pictures from first to last? In other words, we are allowed to rearrange elements of a in any order. What is the maximum possible number of indices i (1 ≤ i ≤ n - 1), such that ai + 1 > ai.

int solution() {
  int beauty[1005];
  int i = 0;
  for (; i < 1002; i++) {
    beauty[i] = 0;
  }
  int n;
  int a;
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &a);
    beauty[a]++;
  }
  int max = 0;
  for (i = 0; i < 1002; i++) {
    if (beauty[i] > max) {
      max = beauty[i];
    }
  }
  printf("%d", n - max);
  return 0;
}

fn solution() {
    use std::io;

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let mut ns: Vec<usize> = buf
        .split(" ")
        .map(|str| str.trim().parse().unwrap())
        .collect();

    {
        let (i, _) = ns.iter().enumerate().min_by_key(|&(_, n)| n).unwrap();
        ns.swap(0, i);
    }

    let mut increases = 0;
    for i in 1..ns.len() {
        let mut k = usize::max_value();
        let mut min = usize::max_value();
        for j in i..ns.len() {
            if ns[j] > ns[i - 1] && ns[j] < min {
                min = ns[j];
                k = j;
            }
        }

        if min == usize::max_value() {
            let (k, _) = ns
                .iter()
                .enumerate()
                .skip(i)
                .min_by_key(|&(_, n)| n)
                .unwrap();
            ns.swap(i, k);
        } else {
            increases += 1;
            ns.swap(i, k);
        }
    }

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


Score : <var>200</var> points

Problem Statement

Snuke loves working out. He is now exercising <var>N</var> times.

Before he starts exercising, his power is <var>1</var>. After he exercises for the <var>i</var>-th time, his power gets multiplied by <var>i</var>.

Find Snuke's power after he exercises <var>N</var> times. Since the answer can be extremely large, print the answer modulo <var>10^{9}+7</var>.

Constraints

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

Input

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

<var>N</var>

Output

Print the answer modulo <var>10^{9}+7</var>.

Sample Input 1

3

Sample Output 1

6

After Snuke exercises for the first time, his power gets multiplied by <var>1</var> and becomes <var>1</var>.

After Snuke exercises for the second time, his power gets multiplied by <var>2</var> and becomes <var>2</var>.

After Snuke exercises for the third time, his power gets multiplied by <var>3</var> and becomes <var>6</var>.

Sample Input 2

10

Sample Output 2

3628800

Sample Input 3

100000

Sample Output 3

457992974

Print the answer modulo <var>10^{9}+7</var>.

int solution() {
  long long int N = 0;
  long long int power = 1;
  scanf("%lld", &N);
  for (long long int i = 1; i <= N; i++) {
    power = power * i % 1000000007;
  }

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

fn solution() {
    let n: u64 = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).ok();
        buf.trim().parse().unwrap()
    };
    println!(
        "{}",
        (1..(n + 1)).fold(1, |p, k| (p * k) % (10u64.pow(9) + 7))
    );
}


It's a walking tour day in SIS.Winter, so $$$t$$$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $$$i$$$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $$$i+1$$$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.

int solution() {

  int totalGroups;

  scanf("%d", &totalGroups);

  int studentsPerGroup[totalGroups];
  char *groups[totalGroups];

  int *angryStudents[totalGroups];
  int totalAngryStudents[totalGroups];

  for (int i = 0; i < totalGroups; i++) {
    scanf("%d", &studentsPerGroup[i]);
    groups[i] = malloc(studentsPerGroup[i] * sizeof(int));
    angryStudents[i] = malloc(studentsPerGroup[i] * sizeof(int));

    totalAngryStudents[i] = 0;

    for (int j = 0; j < studentsPerGroup[i]; j++) {
      scanf(" %c", (groups[i] + j));
      if (*(groups[i] + j) == 'A') {
        *(angryStudents[i] + totalAngryStudents[i]) = j;
        totalAngryStudents[i]++;
      }
    }
  }

  for (int i = 0; i < totalGroups; i++) {
    int highestInterval = 0;
    for (int j = 0; j < totalAngryStudents[i]; j++) {
      if (j == totalAngryStudents[i] - 1) {
        if (studentsPerGroup[i] - *(angryStudents[i] + j) - 1 >
            *(angryStudents[i] + highestInterval + 1) -
                *(angryStudents[i] + highestInterval) - 1) {
          highestInterval = j;
        }
      } else {
        if (*(angryStudents[i] + j + 1) - *(angryStudents[i] + j) - 1 >
            *(angryStudents[i] + highestInterval + 1) -
                *(angryStudents[i] + highestInterval) - 1) {
          highestInterval = j;
        }
      }
    }

    if (totalAngryStudents[i] == 0) {
      printf("0\n");
    } else if (highestInterval == totalAngryStudents[i] - 1) {
      printf("%d\n",
             studentsPerGroup[i] - *(angryStudents[i] + highestInterval) - 1);
    } else {
      printf("%d\n", *(angryStudents[i] + highestInterval + 1) -
                         *(angryStudents[i] + highestInterval) - 1);
    }
  }

  return 0;
}

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("err");
    let n: i32 = buffer.trim().parse().unwrap();
    for _ in 0..n {
        io::stdin().read_line(&mut buffer).expect("err");
        buffer.clear();
        io::stdin().read_line(&mut buffer).expect("err");

        buffer = String::from(buffer.trim());
        buffer = String::from(buffer.trim_start_matches("P"));

        let subs: Vec<&str> = buffer.split("A").collect();
        let mut max_v = 0;
        for v in subs {
            if v.len() > max_v {
                max_v = v.len();
            }
        }
        println!("{}", max_v);
    }
}


Score : <var>200</var> points

Problem Statement

Alice and Bob are controlling a robot. They each have one switch that controls the robot.

Alice started holding down her button <var>A</var> second after the start-up of the robot, and released her button <var>B</var> second after the start-up.

Bob started holding down his button <var>C</var> second after the start-up, and released his button <var>D</var> second after the start-up.

For how many seconds both Alice and Bob were holding down their buttons?

Constraints

<var>0≤A<B≤100</var>

<var>0≤C<D≤100</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the length of the duration (in seconds) in which both Alice and Bob were holding down their buttons.

Sample Input 1

0 75 25 100

Sample Output 1

50

Alice started holding down her button <var>0</var> second after the start-up of the robot, and released her button <var>75</var> second after the start-up.

Bob started holding down his button <var>25</var> second after the start-up, and released his button <var>100</var> second after the start-up.

Therefore, the time when both of them were holding down their buttons, is the <var>50</var> seconds from <var>25</var> seconds after the start-up to <var>75</var> seconds after the start-up.

Sample Input 2

0 33 66 99

Sample Output 2

0

Alice and Bob were not holding their buttons at the same time, so the answer is zero seconds.

Sample Input 3

10 90 20 80

Sample Output 3

60

int solution() {
  int as = 0;
  int ae = 0;
  int bs = 0;
  int be = 0;

  scanf("%d %d %d %d", &as, &ae, &bs, &be);
  if (as - bs >= 0) {
    if (be - as <= 0) {
      printf("0\n");
    } else if (be - as > 0 && ae - be > 0) {
      printf("%d\n", be - as);
    } else if (be - as > 0 && ae - be <= 0) {
      printf("%d\n", ae - as);
    }
  } else {
    if (ae - bs <= 0) {
      printf("0\n");
    } else if (ae - bs > 0 && be - ae > 0) {
      printf("%d\n", ae - bs);
    } else if (ae - bs > 0 && be - ae <= 0) {
      printf("%d\n", be - bs);
    }
  }

  return 0;
}

fn solution() {
    let mut times: Vec<isize> = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).ok();
        buf.split_whitespace()
            .map(|e| e.trim().parse().ok().unwrap())
            .collect()
    };

    if times[0] >= times[3] || times[1] <= times[2] {
        println!("{}", 0);
        return;
    }

    times.sort();
    println!("{}", times[2] - times[1]);
}