Score : <var>400</var> points

Problem Statement

You are going out for a walk, when you suddenly encounter a monster. Fortunately, you have <var>N</var> katana (swords), Katana <var>1</var>, Katana <var>2</var>, <var>…</var>, Katana <var>N</var>, and can perform the following two kinds of attacks in any order:

Wield one of the katana you have. When you wield Katana <var>i</var> <var>(1 ≤ i ≤ N)</var>, the monster receives <var>a_i</var> points of damage. The same katana can be wielded any number of times.

Throw one of the katana you have. When you throw Katana <var>i</var> <var>(1 ≤ i ≤ N)</var> at the monster, it receives <var>b_i</var> points of damage, and you lose the katana. That is, you can no longer wield or throw that katana.

The monster will vanish when the total damage it has received is <var>H</var> points or more. At least how many attacks do you need in order to vanish it in total?

Constraints

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

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

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>H</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_N</var> <var>b_N</var>

Output

Print the minimum total number of attacks required to vanish the monster.

Sample Input 1

1 10
3 5

Sample Output 1

3

You have one katana. Wielding it deals <var>3</var> points of damage, and throwing it deals <var>5</var> points of damage. By wielding it twice and then throwing it, you will deal <var>3 + 3 + 5 = 11</var> points of damage in a total of three attacks, vanishing the monster.

Sample Input 2

2 10
3 5
2 6

Sample Output 2

2

In addition to the katana above, you also have another katana. Wielding it deals <var>2</var> points of damage, and throwing it deals <var>6</var> points of damage. By throwing both katana, you will deal <var>5 + 6 = 11</var> points of damage in two attacks, vanishing the monster.

Sample Input 3

4 1000000000
1 1
1 10000000
1 30000000
1 99999999

Sample Output 3

860000004

Sample Input 4

5 500
35 44
28 83
46 62
31 79
40 43

Sample Output 4

9

int solution() {
  int s[200000][5];
  int n;
  int i;
  int j;
  int HP;
  int max;
  int katana;
  int exdamage = 0;
  int exkatana = 0;
  int result = 0;
  int exmax;
  int memo;
  int k;
  int l;
  int s2[100001];
  scanf("%d", &n);
  scanf("%d", &HP);

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

  for (i = 0; i < n; i++) {
    if (s[i][0] > max) {
      max = s[i][0];
    }
  }
  for (i = 0; i < n; i++) {

    if (s[i][1] >= max) {
      exdamage = exdamage + s[i][1];
      exkatana++;
    }
  }

  if (exdamage <= HP) {

    for (i = 0; i < 10000000000; i++) {
      if (exdamage >= HP) {
        result = result + exkatana;
        printf("%d", result);
        break;
      }
      HP = HP - max;
      result++;
      if (HP <= 0) {
        printf("%d", result);
        break;
      }
    }

  } else {

    exmax = 0;
    for (j = 0; j < 100010; j++) {
      l = 1;
      for (i = 0; i < n; i++) {

        if (s[i][1] > exmax) {
          l = 1;
          exmax = s[i][1];
          s2[0] = i;
        } else if (s[i][1] == exmax) {
          s2[l] = i;
          l++;
        }
      }
      for (i = 0; i < l; i++) {
        HP = HP - exmax;
        result++;
        s[s2[i]][1] = 0;
        if (HP <= 0) {
          printf("%d", result);
          break;
        }
      }
      exmax = 0;
      if (HP <= 0) {
        break;
      }
    }
  }
  return 0;
}

fn solution() {
    let (n, mut h) = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s = s.trim_end().to_owned();
        let mut ws = s.split_whitespace();
        let n: i32 = ws.next().unwrap().parse().unwrap();
        let h: i32 = ws.next().unwrap().parse().unwrap();
        (n, h)
    };

    let mut v = Vec::new();
    let mut max_a = 0;

    for _ in 0..n {
        let (a, b) = {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            s = s.trim_end().to_owned();
            let mut ws = s.split_whitespace();
            let a: i32 = ws.next().unwrap().parse().unwrap();
            let b: i32 = ws.next().unwrap().parse().unwrap();
            (a, b)
        };

        max_a = std::cmp::max(max_a, a);
        v.push(b);
    }

    v.sort_by(|a, b| b.cmp(a));

    let mut ans = 0;

    for e in v {
        if h <= 0 {
            break;
        }

        if e > max_a {
            h -= e;
            ans += 1;
        } else {
            break;
        }
    }

    if h > 0 {
        ans += h / max_a;
        ans += if h % max_a == 0 { 0 } else { 1 };
    }

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


This is an interactive problem.Initially, there is an array $$$a = [1, 2, \ldots, n]$$$, where $$$n$$$ is an odd positive integer. The jury has selected $$$\frac{n-1}{2}$$$ disjoint pairs of elements, and then the elements in those pairs are swapped. For example, if $$$a=[1,2,3,4,5]$$$, and the pairs $$$1 \leftrightarrow 4$$$ and $$$3 \leftrightarrow 5$$$ are swapped, then the resulting array is $$$[4, 2, 5, 1, 3]$$$. As a result of these swaps, exactly one element will not change position. You need to find this element.To do this, you can ask several queries. In each query, you can pick two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$). In return, you will be given the elements of the subarray $$$[a_l, a_{l + 1}, \dots, a_r]$$$ sorted in increasing order. Find the element which did not change position. You can make at most $$$\mathbf{15}$$$ queries.The array $$$a$$$ is fixed before the interaction and does not change after your queries.Recall that an array $$$b$$$ is a subarray of the array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

int solution() {
  int i;
  int T;
  int n;
  int s;
  int d;
  int c;
  int temp;
  int count;
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    s = 1;
    d = n;
    while (s < d) {
      c = s + d >> 1;
      printf("? %d %d\n", s, c);
      fflush(stdout);
      count = 0;
      for (i = s; i <= c; i++) {
        scanf("%d", &temp);
        if (temp >= s && temp <= c) {
          count++;
        }
      }
      if (count & 1) {
        d = c;
      } else {
        s = c + 1;
      }
    }
    printf("! %d\n", s);
    fflush(stdout);
  }
  return 0;
}

fn solution() {
    let num_tests: usize = io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse()
        .unwrap();
    for _ in 0..num_tests {
        let n: i32 = io::stdin()
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .parse()
            .unwrap();
        let mut left = 1;
        let mut right = n;
        while left < right {
            let middle = (left + right) / 2;
            println!("? {left} {middle}");
            io::stdout().flush();
            let a: Vec<i32> = io::stdin()
                .lock()
                .lines()
                .next()
                .unwrap()
                .unwrap()
                .split(" ")
                .map(|token| token.parse::<i32>().unwrap())
                .collect();
            let mut num_inside = 0;
            for k in a {
                if k >= left && k <= middle {
                    num_inside += 1;
                }
            }
            if num_inside % 2 == 0 {
                left = middle + 1;
            } else {
                right = middle;
            }
        }
        println!("! {left}");
        io::stdout().flush();
    }
}


You are given three integers $$$a$$$, $$$b$$$, $$$k$$$.Find two binary integers $$$x$$$ and $$$y$$$ ($$$x \ge y$$$) such that   both $$$x$$$ and $$$y$$$ consist of $$$a$$$ zeroes and $$$b$$$ ones;  $$$x - y$$$ (also written in binary form) has exactly $$$k$$$ ones.  You are not allowed to use leading zeros for $$$x$$$ and $$$y$$$.

fn solution() -> std::io::Result<()> {
    use std::io::Read;
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf)?;
    let mut itr = buf.split_whitespace();

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

    let (a, b, k) = scan!(usize, usize, usize);
    if a == 0 {
        if k == 0 {
            print!("YES\n");
            for _ in 0..b {
                print!("1");
            }
            print!("\n");
            for _ in 0..b {
                print!("1");
            }
            print!("\n");
        } else {
            print!("NO\n");
        }
    } else if b == 1 {
        if k == 0 {
            print!("YES\n1");
            for _ in 0..a {
                print!("0");
            }
            print!("\n1");
            for _ in 0..a {
                print!("0");
            }
            print!("\n");
        } else {
            print!("NO\n");
        }
    } else {
        if k < a + b - 1 {
            print!("YES\n");
            let mut x = Vec::with_capacity(a + b);
            for _ in 0..a {
                x.push('0');
            }
            for _ in 0..b {
                x.push('1');
            }
            let n = x.len();
            let mut y = x.clone();
            if x[k] == '1' {
                y[k] = '0';
                y[0] = '1';
            } else {
                x[k] = '1';
                x[n - 2] = '0';
                y[k] = '1';
                y[n - 2] = '0';
                y[k] = '0';
                y[0] = '1';
            }

            for &c in x.iter().rev() {
                print!("{}", c);
            }
            print!("\n");

            for &c in y.iter().rev() {
                print!("{}", c);
            }
            print!("\n");
        } else {
            print!("NO\n");
        }
    }

    Ok(())
}


Triangle

  For given two sides of a triangle a and b and the angle C between them, calculate the following properties:

<var>S</var>: Area of the triangle

<var>L</var>: The length of the circumference of the triangle

<var>h</var>: The height of the triangle with side <var>a</var> as a bottom edge

Input

  The length of a, the length of b and the angle C are given in integers.

Output

  Print <var>S</var>, <var>L</var> and <var>h</var> in a line respectively. The output should not contain an absolute error greater than 10-4.

Sample Input

4 3 90

Sample Output

6.00000000
12.00000000
3.00000000

int solution() {
  double a;
  double b;
  double c;
  double PI = acos(-1);
  scanf("%lf %lf %lf", &a, &b, &c);
  c /= 180.0;
  c *= PI;
  printf("%lf\n%lf\n%lf\n", a * b * 0.5 * sin(c),
         a + b + sqrt((a * a) + (b * b) - (2.0 * a * b * cos(c))),
         a * b * sin(c) / a);
  return 0;
}

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

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

    let a = ite.next().unwrap();
    let b = ite.next().unwrap();
    let c = ite.next().unwrap();

    let rad = c.to_radians();

    println!("{}", a * b * rad.sin() * 0.5);
    println!(
        "{}",
        (a.powi(2) + b.powi(2) - 2. * a * b * rad.cos()).sqrt() + a + b
    );
    println!("{}", b * rad.sin());
}


Nezzar has $$$n$$$ balls, numbered with integers $$$1, 2, \ldots, n$$$. Numbers $$$a_1, a_2, \ldots, a_n$$$ are written on them, respectively. Numbers on those balls form a non-decreasing sequence, which means that $$$a_i \leq a_{i+1}$$$ for all $$$1 \leq i < n$$$.Nezzar wants to color the balls using the minimum number of colors, such that the following holds.  For any color, numbers on balls will form a strictly increasing sequence if he keeps balls with this chosen color and discards all other balls.  Note that a sequence with the length at most $$$1$$$ is considered as a strictly increasing sequence.Please help Nezzar determine the minimum number of colors.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int arr[n];
    int repeat = 0;
    int max = 0;

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

      if (arr[i] == arr[i - 1]) {
        repeat++;
      }

      else {

        if (repeat > max) {
          max = repeat;
        }
        repeat = 0;
      }
    }
    if (repeat > max) {
      max = repeat;
    }
    printf("%d\n", max + 1);
  }

  return 0;
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let mut a = [0; 101];
        l.unwrap()
            .split(' ')
            .for_each(|w| a[w.parse::<usize>().unwrap()] += 1);
        writeln!(o, "{}", a.iter().max().unwrap()).ok();
    }
}


There are $$$n$$$ students standing in a circle in some order. The index of the $$$i$$$-th student is $$$p_i$$$. It is guaranteed that all indices of students are distinct integers from $$$1$$$ to $$$n$$$ (i. e. they form a permutation).Students want to start a round dance. A clockwise round dance can be started if the student $$$2$$$ comes right after the student $$$1$$$ in clockwise order (there are no students between them), the student $$$3$$$ comes right after the student $$$2$$$ in clockwise order, and so on, and the student $$$n$$$ comes right after the student $$$n - 1$$$ in clockwise order. A counterclockwise round dance is almost the same thing — the only difference is that the student $$$i$$$ should be right after the student $$$i - 1$$$ in counterclockwise order (this condition should be met for every $$$i$$$ from $$$2$$$ to $$$n$$$). For example, if the indices of students listed in clockwise order are $$$[2, 3, 4, 5, 1]$$$, then they can start a clockwise round dance. If the students have indices $$$[3, 2, 1, 4]$$$ in clockwise order, then they can start a counterclockwise round dance.Your task is to determine whether it is possible to start a round dance. Note that the students cannot change their positions before starting the dance; they cannot swap or leave the circle, and no other student can enter the circle. You have to answer $$$q$$$ independent queries.

int solution() {
  int t;
  scanf(" %d", &t);
  while (t--) {
    int n;
    scanf(" %d", &n);
    int nums[n];
    for (int i = 0; i < n; ++i) {
      scanf(" %d", &nums[i]);
    }
    int first = nums[0];
    int po = 1;
    for (int i = 1; i < n && po; ++i) {
      if (nums[i] - 1 != first && (nums[i] != 1 || first != n)) {
        po = 0;
      }
      first = nums[i];
    }
    if (po) {
      puts("YES");
      continue;
    }
    first = nums[0];
    po = 1;
    for (int i = 1; i < n && po; ++i) {
      if (nums[i] + 1 != first && (first != 1 || nums[i] != n)) {
        po = 0;
      }
      first = nums[i];
    }
    if (po) {
      puts("YES");
    } else {
      puts("NO");
    }
  }
  return 0;
}

fn solution() -> Result<(), Box<dyn std::error::Error>> {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    let stdout = io::stdout();
    let mut out = io::BufWriter::with_capacity(2 * 1024 * 1024, stdout.lock());

    let q = next!(u32);
    for _ in 0..q {
        let n = next!(u32);
        let (r, _) = next!()
            .split_ascii_whitespace()
            .map(|w| w.parse().unwrap())
            .fold((true, 0), |(f, p), e| {
                if f && p != 0 {
                    let mut p1 = p + 1;
                    if p1 > n {
                        p1 = 1;
                    }
                    let mut p2 = p - 1;
                    if p2 < 1 {
                        p2 = n;
                    }
                    (p1 == e || p2 == e, e)
                } else {
                    (f, e)
                }
            });
        put!("{}\n", if r { "YES" } else { "NO" })
    }

    Ok(())
}


Space Coconut Crab

宇宙ヤシガニ

English text is not available in this practice contest.

ケン・マリンブルーは，宇宙ヤシガニを求めて全銀河を旅するスペースハンターである．宇宙ヤシガニは，宇宙最大とされる甲殻類であり，成長後の体長は 400 メートル以上，足を広げれば 1,000 メートル以上にもなると言われている．既に多数の人々が宇宙ヤシガニを目撃しているが，誰一人として捕らえることに成功していない．

ケンは，長期間の調査によって，宇宙ヤシガニの生態に関する重要な事実を解明した．宇宙ヤシガニは，驚くべきことに，相転移航法と呼ばれる最新のワープ技術と同等のことを行い，通常空間と超空間の間を往来しながら生きていた．さらに，宇宙ヤシガニが超空間から通常空間にワープアウトするまでには長い時間がかかり，またワープアウトしてからしばらくは超空間に移動できないことも突き止めた．

そこで，ケンはついに宇宙ヤシガニの捕獲に乗り出すことにした．戦略は次のとおりである．はじめに，宇宙ヤシガニが通常空間から超空間に突入する際のエネルギーを観測する．このエネルギーを e とするとき，宇宙ヤシガニが超空間からワープアウトする座標 (x, y, z) は以下の条件を満たすことがわかっている．

x, y, z はいずれも非負の整数である．

x + y2 + z3 = e である．

上記の条件の下で x + y + z の値を最小にする．

これらの条件だけでは座標が一意に決まるとは限らないが，x + y + z の最小値を m としたときに，ワープアウトする座標が平面 x + y + z = m 上にあることは確かである．そこで，この平面上に十分な大きさのバリアを張る．すると，宇宙ヤシガニはバリアの張られたところにワープアウトすることになる．バリアの影響を受けた宇宙ヤシガニは身動きがとれなくなる．そこをケンの操作する最新鋭宇宙船であるウェポン・ブレーカー号で捕獲しようという段取りである．

バリアは一度しか張ることができないため，失敗するわけにはいかない．そこでケンは，任務の遂行にあたって計算機の助けを借りることにした．あなたの仕事は，宇宙ヤシガニが超空間に突入する際のエネルギーが与えられたときに，バリアを張るべき平面 x + y + z = m を求めるプログラムを書くことである．用意されたテストケースの全てに対して正しい結果を出力したとき，あなたのプログラムは受け入れられるであろう．

Input

入力は複数のデータセットで構成される．各データセットは 1 行のみからなり，1 つの正の整数 e (e ≦ 1,000,000) が含まれる．これは，宇宙ヤシガニが超空間に突入した際のエネルギーを表す．入力は e = 0 の時に終了し，これはデータセットには含まれない．

Output

各データセットについて，m の値を 1 行に出力しなさい．出力には他の文字を含めてはならない．

Sample Input

1
2
4
27
300
1250
0

Output for the Sample Input

1
2
2
3
18
44

fn solution() {
    loop {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let mut iter = s.split_whitespace();
        let e: i64 = iter.next().unwrap().parse().unwrap();

        if e == 0 {
            break;
        }

        let mut min_ = 1e8 as i64;
        let _flag: bool = false;
        for z in 0..101_i64 {
            for y in 0..1001_i64 {
                let x = e - z.pow(3) - y.pow(2);

                if x < 0 {
                    break;
                }
                if min_ > x + y + z {
                    min_ = x + y + z;
                }
            }
        }
        println!("{}", min_);
    }
}


Score : <var>300</var> points

Problem Statement

There is a rectangle in a coordinate plane. The coordinates of the four vertices are <var>(0,0)</var>, <var>(W,0)</var>, <var>(W,H)</var>, and <var>(0,H)</var>.
You are given a point <var>(x,y)</var> which is within the rectangle or on its border. We will draw a straight line passing through <var>(x,y)</var> to cut the rectangle into two parts. Find the maximum possible area of the part whose area is not larger than that of the other. Additionally, determine if there are multiple ways to cut the rectangle and achieve that maximum.

Constraints

<var>1 \leq W,H \leq 10^9</var>

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

<var>0\leq y\leq H</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>W</var> <var>H</var> <var>x</var> <var>y</var>

Output

Print the maximum possible area of the part whose area is not larger than that of the other, followed by 1 if there are multiple ways to cut the rectangle and achieve that maximum, and 0 otherwise.

The area printed will be judged correct when its absolute or relative error is at most <var>10^{-9}</var>.

Sample Input 1

2 3 1 2

Sample Output 1

3.000000 0

The line <var>x=1</var> gives the optimal cut, and no other line does.

Sample Input 2

2 2 1 1

Sample Output 2

2.000000 1

int solution(void) {

  double w = 0;
  double h = 0;
  double x = 0;
  double y = 0;
  double max;

  scanf("%lf %lf %lf %lf", &w, &h, &x, &y);

  max = (w * h) / 2;

  if (w == x * 2 && h == y * 2) {
    printf("%lf %d", max, 1);
  } else {
    printf("%lf %d", max, 0);
  }

  return 0;
}

fn solution() {
    let (w, h, x, y) = {
        let mut inputline = String::new();
        std::io::stdin().read_line(&mut inputline).ok();
        let mut inputline = inputline.split_whitespace();
        (
            inputline.next().unwrap().parse::<usize>().ok().unwrap(),
            inputline.next().unwrap().parse::<usize>().ok().unwrap(),
            inputline.next().unwrap().parse::<usize>().ok().unwrap(),
            inputline.next().unwrap().parse::<usize>().ok().unwrap(),
        )
    };
    let s = (w * h) as f64 / 2.0;
    let fukusuu = if x * 2 == w && y * 2 == h { 1 } else { 0 };
    println!("{} {}", s, fukusuu);
}


Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.There are $$$n$$$ flowers in a row in the exhibition. Sonya can put either a rose or a lily in the $$$i$$$-th position. Thus each of $$$n$$$ positions should contain exactly one flower: a rose or a lily.She knows that exactly $$$m$$$ people will visit this exhibition. The $$$i$$$-th visitor will visit all flowers from $$$l_i$$$ to $$$r_i$$$ inclusive. The girl knows that each segment has its own beauty that is equal to the product of the number of roses and the number of lilies.Sonya wants her exhibition to be liked by a lot of people. That is why she wants to put the flowers in such way that the sum of beauties of all segments would be maximum possible.

int solution(void) {
  int n = 0;
  int m = 0;

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

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("err");
    let n: i32 = buffer.split_whitespace().collect::<Vec<&str>>()[0]
        .parse()
        .unwrap();
    for i in 1..n {
        print!("{}", {
            if i % 2 == 0 {
                '1'
            } else {
                '0'
            }
        });
    }
    println!("{}", {
        if n % 2 == 0 {
            '1'
        } else {
            '0'
        }
    });
}


Theofanis has a string $$$s_1 s_2 \dots s_n$$$ and a character $$$c$$$. He wants to make all characters of the string equal to $$$c$$$ using the minimum number of operations.In one operation he can choose a number $$$x$$$ ($$$1 \le x \le n$$$) and for every position $$$i$$$, where $$$i$$$ is not divisible by $$$x$$$, replace $$$s_i$$$ with $$$c$$$. Find the minimum number of operations required to make all the characters equal to $$$c$$$ and the $$$x$$$-s that he should use in his operations.

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    char c;
    char x;
    scanf("%d %c ", &n, &c);
    int last = 0;
    int count = 0;
    int flag = 1;
    while ((x = getchar()) != '\n' && x != EOF) {
      count++;
      if (x == c) {
        last = count;
      } else {
        flag = 0;
      }
    }

    if (flag) {
      printf("0\n");
    } else if (2 * last > n) {
      printf("1\n");
      printf("%d\n", last);
    } else {
      printf("2\n");
      printf("%d %d\n", n, n - 1);
    }
  }

  return 0;
}

fn solution() -> io::Result<()> {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s)?;
    let mut it = s.split_whitespace().map(|s| s.to_string());
    let t: usize = it.next().unwrap().parse().unwrap();
    let mut out = String::new();
    for _ in 1..=t {
        let n: usize = it.next().unwrap().parse().unwrap();
        let c: char = it.next().unwrap().parse().unwrap();
        let s: String = it.next().unwrap().parse().unwrap();
        let mut moves = vec![];
        if s.chars().any(|x| x != c) {
            let mut ok = false;
            for i in (1..n).rev() {
                let _v: Vec<usize> = (i..n).step_by(i + 1).collect();

                if (i..n).step_by(i + 1).all(|j| s.as_bytes()[j] == c as u8) {
                    moves.push(i + 1);
                    ok = true;
                    break;
                }
            }
            if !ok {
                moves.push(n - 1);
                moves.push(n);
            }
        }
        let ans = format!("{}\n", moves.len());
        out.push_str(ans.as_str());
        for i in 0..moves.len() {
            if i + 1 == moves.len() {
                let ans = format!("{}\n", moves[i]);
                out.push_str(ans.as_str());
            } else {
                let ans = format!("{} ", moves[i]);
                out.push_str(ans.as_str());
            }
        }
    }
    print!("{}", out);
    Ok(())
}


Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

int solution(void) {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    char string[200000];
    scanf("%s", string);
    int bcount = 0;
    int acount = 0;
    int count = 0;
    int truthVal = 1;
    for (int j = 0; string[j] != '\0'; j++) {
      if (string[j] == 'A') {
        acount++;
      } else if (string[j] == 'B') {
        bcount++;
      }
      count = j;
      if (acount < bcount) {
        truthVal = 0;
        break;
      }
    }
    if (truthVal == 1 && string[count] != 'A') {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

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

    let t: usize = str.trim().parse::<usize>().unwrap();
    for _t in 0..t {
        str.clear();
        io::stdin().read_line(&mut str).unwrap();

        if !str.trim().ends_with("B") {
            println!("NO");
            continue;
        }

        let mut cnt = 0;
        let mut works = true;
        for char in str.trim().chars() {
            if char == 'B' {
                cnt -= 1;
                if cnt < 0 {
                    works = false;
                    break;
                }
            } else {
                cnt += 1;
            }
        }
        if works {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>700</var> points

Problem Statement

There are <var>N</var> cats.
We number them from <var>1</var> through <var>N</var>.

Each of the cats wears a hat.
Cat <var>i</var> says: "there are exactly <var>a_i</var> different colors among the <var>N - 1</var> hats worn by the cats except me."

Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats.

Constraints

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

<var>1 ≤ a_i ≤ N-1</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print Yes if there exists a sequence of colors of the hats that is consistent with the remarks of the cats; print No otherwise.

Sample Input 1

3
1 2 2

Sample Output 1

Yes

For example, if cat <var>1</var>, <var>2</var> and <var>3</var> wears red, blue and blue hats, respectively, it is consistent with the remarks of the cats.

Sample Input 2

3
1 1 2

Sample Output 2

No

From the remark of cat <var>1</var>, we can see that cat <var>2</var> and <var>3</var> wear hats of the same color.
Also, from the remark of cat <var>2</var>, we can see that cat <var>1</var> and <var>3</var> wear hats of the same color.
Therefore, cat <var>1</var> and <var>2</var> wear hats of the same color, which contradicts the remark of cat <var>3</var>.

Sample Input 3

5
4 3 4 3 4

Sample Output 3

No

Sample Input 4

3
2 2 2

Sample Output 4

Yes

Sample Input 5

4
2 2 2 2

Sample Output 5

Yes

Sample Input 6

5
3 3 3 3 3

Sample Output 6

No

int solution() {
  int max = 0;
  int min = 1000000;
  int maxnum = 0;
  int minnum = 0;
  int n;
  int s[100005];
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &s[i]);
    if (max < s[i]) {
      max = s[i];
    }
    if (min > s[i]) {
      min = s[i];
    }
  }
  if (max - min >= 2) {
    printf("No");
    return 0;
  }

  for (int i = 0; i < n; i++) {
    if (max == s[i]) {
      maxnum++;
    }
    if (min == s[i]) {
      minnum++;
    }
  }
  if (max == min && (n - maxnum + 1 <= max && max <= n - maxnum + maxnum / 2 ||
                     max + 1 == n)) {
    printf("Yes");
    return 0;
  }
  if (max == min) {
    printf("No");
    return 0;
  }

  if (n - maxnum + 1 <= max && max <= n - maxnum + maxnum / 2) {
    printf("Yes");
    return 0;
  }
  printf("No");
}

fn solution() {
    input! {
        n: usize,
        mut v: [usize; n]
    }
    v.sort();
    if v[n - 1] - v[0] > 1 {
        println!("No");
    } else if v[0] == v[n - 1] {
        if v[0] <= n / 2 || v[0] == n - 1 {
            println!("Yes");
        } else {
            println!("No");
        }
    } else {
        let mut a = 0;
        for &x in &v {
            if x == v[0] {
                a += 1;
            } else {
                break;
            }
        }
        if a <= v[0] && v[0] < (n - a) / 2 + a {
            println!("Yes");
        } else {
            println!("No");
        }
    }
}


Score : <var>300</var> points

Problem Statement

Tak has <var>N</var> cards. On the <var>i</var>-th <var>(1 \leq i \leq N)</var> card is written an integer <var>x_i</var>.
He is selecting one or more cards from these <var>N</var> cards, so that the average of the integers written on the selected cards is exactly <var>A</var>.
In how many ways can he make his selection?

Constraints

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

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

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

<var>N,\,A,\,x_i</var> are integers.

Partial Score

<var>200</var> points will be awarded for passing the test set satisfying <var>1 \leq N \leq 16</var>.

Input

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

<var>N</var> <var>A</var>
<var>x_1</var> <var>x_2</var> <var>...</var> <var>x_N</var>

Output

Print the number of ways to select cards such that the average of the written integers is exactly <var>A</var>.

Sample Input 1

4 8
7 9 8 9

Sample Output 1

5

The following are the <var>5</var> ways to select cards such that the average is <var>8</var>:

Select the <var>3</var>-rd card.

Select the <var>1</var>-st and <var>2</var>-nd cards.

Select the <var>1</var>-st and <var>4</var>-th cards.

Select the <var>1</var>-st, <var>2</var>-nd and <var>3</var>-rd cards.

Select the <var>1</var>-st, <var>3</var>-rd and <var>4</var>-th cards.

Sample Input 2

3 8
6 6 9

Sample Output 2

0

Sample Input 3

8 5
3 6 2 8 7 6 5 9

Sample Output 3

19

Sample Input 4

33 3
3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

Sample Output 4

8589934591

The answer may not fit into a <var>32</var>-bit integer.

int solution(void) {

  long long N;
  long long A;

  scanf("%lld%lld", &N, &A);

  long long x[N + 1];

  long long sum = 0;

  for (long long i = 1; i <= N; i++) {
    scanf("%lld", &x[i]);
    sum += x[i];
  }

  long long dp[N + 1][N + 1][sum + 1];

  for (long long j = 0; j <= N; j++) {
    for (long long k = 0; k <= N; k++) {
      for (long long s = 0; s <= sum; s++) {
        if (j >= 1 && s < x[j]) {
          dp[j][k][s] = dp[j - 1][k][s];
        } else if (j >= 1 && k >= 1 && s >= x[j]) {
          dp[j][k][s] = dp[j - 1][k][s] + dp[j - 1][k - 1][s - x[j]];
        } else if (j == 0 && k == 0 && s == 0) {
          dp[j][k][s] = 1;
        } else {
          dp[j][k][s] = 0;
        }
      }
    }
  }

  long long ans = 0;

  long long max;

  if (sum / A < N) {
    max = sum / A;
  } else {
    max = N;
  }

  for (long long k = 1; k <= max; k++) {
    ans += dp[N][k][k * A];
  }

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

  return 0;
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> observatories in AtCoder Hill, called Obs. <var>1</var>, Obs. <var>2</var>, <var>...</var>, Obs. <var>N</var>. The elevation of Obs. <var>i</var> is <var>H_i</var>.
There are also <var>M</var> roads, each connecting two different observatories. Road <var>j</var> connects Obs. <var>A_j</var> and Obs. <var>B_j</var>.

Obs. <var>i</var> is said to be good when its elevation is higher than those of all observatories that can be reached from Obs. <var>i</var> using just one road.
Note that Obs. <var>i</var> is also good when no observatory can be reached from Obs. <var>i</var> using just one road.

How many good observatories are there?

Constraints

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

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

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

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

<var>A_i \neq B_i</var>

Multiple roads may connect the same pair of observatories.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>H_1</var> <var>H_2</var> <var>...</var> <var>H_N</var>
<var>A_1</var> <var>B_1</var>
<var>A_2</var> <var>B_2</var>
<var>:</var>
<var>A_M</var> <var>B_M</var>

Output

Print the number of good observatories.

Sample Input 1

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

Sample Output 1

2

From Obs. <var>1</var>, you can reach Obs. <var>3</var> using just one road. The elevation of Obs. <var>1</var> is not higher than that of Obs. <var>3</var>, so Obs. <var>1</var> is not good.

From Obs. <var>2</var>, you can reach Obs. <var>3</var> and <var>4</var> using just one road. The elevation of Obs. <var>2</var> is not higher than that of Obs. <var>3</var>, so Obs. <var>2</var> is not good.

From Obs. <var>3</var>, you can reach Obs. <var>1</var> and <var>2</var> using just one road. The elevation of Obs. <var>3</var> is higher than those of Obs. <var>1</var> and <var>2</var>, so Obs. <var>3</var> is good.

From Obs. <var>4</var>, you can reach Obs. <var>2</var> using just one road. The elevation of Obs. <var>4</var> is higher than that of Obs. <var>2</var>, so Obs. <var>4</var> is good.

Thus, the good observatories are Obs. <var>3</var> and <var>4</var>, so there are two good observatories.

Sample Input 2

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

Sample Output 2

3

int solution() {

  int N = 0;
  int M = 0;
  int A = 0;
  int B = 0;
  int H[100000] = {0};
  bool great[100000] = {false};
  int count = 0;
  scanf("%d %d", &N, &M);
  for (int i = 0; i < N; i++) {
    great[i] = true;
  }
  for (int i = 0; i < N; i++) {
    scanf("%d", &H[i]);
  }
  for (int i = 0; i < M; i++) {
    scanf("%d %d", &A, &B);
    if (H[A - 1] <= H[B - 1]) {
      great[A - 1] = false;
    }
    if (H[A - 1] >= H[B - 1]) {
      great[B - 1] = false;
    }
  }
  for (int i = 0; i < N; i++) {
    if (great[i]) {
      count++;
    }
  }
  printf("%d\n", count);
  return 0;
}

fn solution() -> Result<(), Box<dyn std::error::Error>> {
    let mut buffer = String::new();
    io::stdin().read_to_string(&mut buffer)?;
    let mut input = buffer.lines();
    input.next();
    let mut input = input.map(|s| s.split_whitespace());
    let mut elevations: Vec<(u32, bool)> = input
        .next()
        .unwrap()
        .map(|n| (n.parse().unwrap(), true))
        .collect();
    let input = input.map(|l| l.map(|n| n.parse::<usize>().unwrap() - 1));
    for mut pair in input {
        let left = pair.next().unwrap();
        let right = pair.next().unwrap();
        match elevations[left].0.cmp(&elevations[right].0) {
            Less => elevations[left].1 = false,
            Equal => {
                elevations[left].1 = false;
                elevations[right].1 = false;
            }
            Greater => elevations[right].1 = false,
        }
    }
    let output = elevations.into_iter().filter(|&(_, good)| good).count();
    println!("{}", output);
    Ok(())
}


Score : <var>700</var> points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of <var>K</var>.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of <var>K</var>.

Sample Input 1

6

Sample Output 1

3

<var>12=6×2</var> yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

<var>11111=41×271</var> yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36

fn solution() {
    input! {
        k: usize
    }
    let mut q = VecDeque::new();
    q.push_back(1);
    let mut d = vec![k + 1; k];
    d[1] = 1;
    while let Some(v) = q.pop_front() {
        if v == 0 {
            println!("{}", d[v]);
            return;
        }
        if d[(v + 1) % k] > d[v] + 1 {
            d[(v + 1) % k] = d[v] + 1;
            q.push_back((v + 1) % k);
        }
        if d[v * 10 % k] > d[v] {
            d[v * 10 % k] = d[v];
            q.push_front(v * 10 % k);
        }
    }
}


Polycarp was presented with some sequence of integers $$$a$$$ of length $$$n$$$ ($$$1 \le a_i \le n$$$). A sequence can make Polycarp happy only if it consists of different numbers (i.e. distinct numbers).In order to make his sequence like this, Polycarp is going to make some (possibly zero) number of moves.In one move, he can:   remove the first (leftmost) element of the sequence. For example, in one move, the sequence $$$[3, 1, 4, 3]$$$ will produce the sequence $$$[1, 4, 3]$$$, which consists of different numbers.Determine the minimum number of moves he needs to make so that in the remaining sequence all elements are different. In other words, find the length of the smallest prefix of the given sequence $$$a$$$, after removing which all values in the sequence will be unique.

int solution() {
  int T;
  scanf("%d", &T);
  for (int i = 0; i < T; i++) {
    int N;
    scanf("%d", &N);
    int arr[N];

    int freq[2 * 100000];
    int index = 0;
    int count = 0;
    for (int i = 0; i < N; i++) {
      scanf("%d", &arr[i]);
      freq[arr[i]] = 0;
    }

    for (int i = N - 1; i >= 0; i--) {
      freq[arr[i]]++;
      if (freq[arr[i]] > 1) {
        index = i;
        count++;
        break;
      }
    }
    if (index == 0 && count == 0) {
      index = -1;
    }
    if (index == 0 && count != 0) {
      index = 0;
    }
    printf("%d\n", index + 1);
  }
}

fn solution() -> Result<(), Box<dyn Error + Send + Sync>> {
    let stdin = std::io::stdin();
    let mut stdin = stdin.lock();

    let stdout = std::io::stdout();
    let mut stdout = stdout.lock();

    let mut line = String::with_capacity(32);
    let mut data = vec![];
    let mut data_uniq = HashSet::new();

    stdin.read_line(&mut line)?;
    let test_cases = line.trim().parse::<u32>()?;

    for _ in 0..test_cases {
        line.clear();
        let _len = stdin.read_line(&mut line)?;

        line.clear();
        stdin.read_line(&mut line)?;

        data.clear();
        data_uniq.clear();

        for x in line.trim().split_ascii_whitespace() {
            let value = x.parse::<u32>()?;
            data.push(value);
        }

        let mut answer = 0;
        for x in data.iter().copied().rev() {
            if !data_uniq.insert(x) {
                answer = data.len() - data_uniq.len();
                break;
            }
        }

        writeln!(stdout, "{}", answer)?;
    }

    stdout.flush()?;
    Ok(())
}


Tanya is learning how to add numbers, but so far she is not doing it correctly. She is adding two numbers $$$a$$$ and $$$b$$$ using the following algorithm:  If one of the numbers is shorter than the other, Tanya adds leading zeros so that the numbers are the same length.  The numbers are processed from right to left (that is, from the least significant digits to the most significant).  In the first step, she adds the last digit of $$$a$$$ to the last digit of $$$b$$$ and writes their sum in the answer.  At each next step, she performs the same operation on each pair of digits in the same place and writes the result to the left side of the answer.  For example, the numbers $$$a = 17236$$$ and $$$b = 3465$$$ Tanya adds up as follows:$$$$$$ \large{ \begin{array}{r} + \begin{array}{r} 17236\\ 03465\\ \end{array} \\ \hline \begin{array}{r} 1106911 \end{array} \end{array}} $$$$$$  calculates the sum of $$$6 + 5 = 11$$$ and writes $$$11$$$ in the answer.  calculates the sum of $$$3 + 6 = 9$$$ and writes the result to the left side of the answer to get $$$911$$$.  calculates the sum of $$$2 + 4 = 6$$$ and writes the result to the left side of the answer to get $$$6911$$$.  calculates the sum of $$$7 + 3 = 10$$$, and writes the result to the left side of the answer to get $$$106911$$$.  calculates the sum of $$$1 + 0 = 1$$$ and writes the result to the left side of the answer and get $$$1106911$$$. As a result, she gets $$$1106911$$$.You are given two positive integers $$$a$$$ and $$$s$$$. Find the number $$$b$$$ such that by adding $$$a$$$ and $$$b$$$ as described above, Tanya will get $$$s$$$. Or determine that no suitable $$$b$$$ exists.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long a;
    long long s;
    scanf("%lld%lld", &a, &s);
    if (a >= s) {
      printf("-1\n");
      continue;
    }
    long long x = s % 10;
    long long y = a % 10;
    long long b = 0;
    long long c = 1;
    while (s > 0) {
      if (x < y) {
        x = s % 100;
        b = (x - y) * c + b;
        if (x - y >= 10 || x - y < 0) {
          break;
        }
        s /= 100;
        a /= 10;
        c *= 10;
        x = s % 10;
        y = a % 10;

      } else {
        b = (x - y) * c + b;
        if (x - y >= 10 || x - y < 0) {
          break;
        }
        s /= 10;
        a /= 10;
        c *= 10;
        x = s % 10;
        y = a % 10;
      }
    }
    if (a != 0) {
      printf("-1\n");
    } else {
      printf("%lld\n", b);
    }
  }
}

fn solution() {
    let stdout = stdout();
    let mut bw = BufWriter::new(stdout);

    let stdin = stdin();
    let mut br = BufReader::new(stdin);
    let mut num_tests_str = String::new();
    br.read_line(&mut num_tests_str).unwrap();
    let num_tests: usize = num_tests_str.trim_end().parse::<usize>().unwrap();

    for _ in 0..num_tests {
        let mut test_case = String::new();
        br.read_line(&mut test_case).unwrap();
        let (a_str, s_str) = test_case.trim().split_once(' ').unwrap();
        let mut a: i64 = a_str.parse().unwrap();
        let mut s: i64 = s_str.parse().unwrap();
        let mut b: i64 = 0;
        let mut pow_10: i64 = 1;

        while a > 0 || s > 0 {
            let a_digit = a % 10;
            let mut s_digit = s % 10;
            let mut b_digit = s_digit - a_digit;
            if b_digit >= 0 {
                s /= 10;
            } else {
                s_digit = s % 100;
                b_digit = s_digit - a_digit;
                if !(0..=9).contains(&b_digit) {
                    b = -1;
                    break;
                }
                s /= 100;
            }
            a /= 10;
            b += b_digit * pow_10;
            pow_10 *= 10;
        }

        writeln!(bw, "{}", b).expect("Could not write to stdout");
    }
}


Score : <var>100</var> points

Problem Statement

There is an <var>N</var>-car train.

You are given an integer <var>i</var>. Find the value of <var>j</var> such that the following statement is true: "the <var>i</var>-th car from the front of the train is the <var>j</var>-th car from the back."

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>i</var>

Output

Print the answer.

Sample Input 1

4 2

Sample Output 1

3

The second car from the front of a <var>4</var>-car train is the third car from the back.

Sample Input 2

1 1

Sample Output 2

1

Sample Input 3

15 11

Sample Output 3

5

int solution() {
  int n = 0;
  int i = 0;
  scanf("%d%d", &n, &i);
  printf("%d", n - i + 1);
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let s = s.trim_end().to_owned();
    let vec: Vec<&str> = s.split_whitespace().collect();
    let n: i32 = vec[0].parse().unwrap_or(0);
    let i: i32 = vec[1].parse().unwrap_or(0);
    println!("{}", format!("{}", n - i + 1));
}


You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive.  All the written labels are distinct.  The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|l| l.unwrap());
    let n: u64 = lines.next().unwrap().parse().unwrap();
    let mut edges = Vec::new();
    for _ in 0..n - 1 {
        let line = lines.next().unwrap();
        let mut parts = line.split_whitespace();
        let u: u64 = parts.next().unwrap().parse().unwrap();
        let v: u64 = parts.next().unwrap().parse().unwrap();
        edges.push((u - 1, v - 1));
    }

    let mut fixed_edges = edges.clone();
    for (u, v) in edges.iter() {
        fixed_edges.push((*v, *u));
    }

    fixed_edges.sort();
    fixed_edges.dedup();

    let mut adj = Vec::new();
    for _ in 0..n {
        adj.push(Vec::<u64>::new());
    }
    for (u, v) in fixed_edges {
        adj[u as usize].push(v);
    }

    if adj.iter().all(|l| l.len() <= 2) {
        for i in 0..n - 1 {
            println!("{}", i);
        }
    } else {
        let (i_center, adj_center) = adj.iter().enumerate().find(|(_, l)| l.len() >= 3).unwrap();

        let e_0 = (i_center as u64, adj_center[0]);
        let e_1 = (i_center as u64, adj_center[1]);
        let e_2 = (i_center as u64, adj_center[2]);

        let mut counter = 3;
        for edge in edges.iter() {
            match edge {
                t if (t.0, t.1) == e_0 || (t.1, t.0) == e_0 => {
                    println!("0");
                }
                t if (t.0, t.1) == e_1 || (t.1, t.0) == e_1 => {
                    println!("1");
                }
                t if (t.0, t.1) == e_2 || (t.1, t.0) == e_2 => {
                    println!("2");
                }
                _ => {
                    println!("{}", counter);
                    counter += 1;
                }
            }
        }
    }
}


Score: <var>200</var> points

Problem Statement

Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid <var>N</var> yen (the currency of Japan) for it.

The consumption tax rate for foods in this shop is <var>8</var> percent. That is, to buy an apple pie priced at <var>X</var> yen before tax, you have to pay <var>X \times 1.08</var> yen (rounded down to the nearest integer).

Takahashi forgot the price of his apple pie before tax, <var>X</var>, and wants to know it again. Write a program that takes <var>N</var> as input and finds <var>X</var>. We assume <var>X</var> is an integer.

If there are multiple possible values for <var>X</var>, find any one of them. Also, Takahashi's memory of <var>N</var>, the amount he paid, may be incorrect. If no value could be <var>X</var>, report that fact.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If there are values that could be <var>X</var>, the price of the apple pie before tax, print any one of them.

If there are multiple such values, printing any one of them will be accepted.

If no value could be <var>X</var>, print :(.

Sample Input 1

432

Sample Output 1

400

If the apple pie is priced at <var>400</var> yen before tax, you have to pay <var>400 \times 1.08 = 432</var> yen to buy one.

Otherwise, the amount you have to pay will not be <var>432</var> yen.

Sample Input 2

1079

Sample Output 2

:(

There is no possible price before tax for which you have to pay <var>1079</var> yen with tax.

Sample Input 3

1001

Sample Output 3

927

If the apple pie is priced <var>927</var> yen before tax, by rounding down <var>927 \times 1.08 = 1001.16</var>, you have to pay <var>1001</var> yen.

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

    for i in 1..n + 1 {
        if i * 108 / 100 == n {
            println!("{}", i);
            return;
        }
    }
    println!(":(")
}


Score : <var>200</var> points

Problem Statement

Takahashi loves numbers divisible by <var>2</var>.

You are given a positive integer <var>N</var>. Among the integers between <var>1</var> and <var>N</var> (inclusive), find the one that can be divisible by <var>2</var> for the most number of times. The solution is always unique.

Here, the number of times an integer can be divisible by <var>2</var>, is how many times the integer can be divided by <var>2</var> without remainder.

For example,

<var>6</var> can be divided by <var>2</var> once: <var>6</var> -> <var>3</var>.

<var>8</var> can be divided by <var>2</var> three times: <var>8</var> -> <var>4</var> -> <var>2</var> -> <var>1</var>.

<var>3</var> can be divided by <var>2</var> zero times.

Constraints

<var>1 ≤ N ≤ 100</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer.

Sample Input 1

7

Sample Output 1

4

<var>4</var> can be divided by <var>2</var> twice, which is the most number of times among <var>1</var>, <var>2</var>, ..., <var>7</var>.

Sample Input 2

32

Sample Output 2

32

Sample Input 3

1

Sample Output 3

1

Sample Input 4

100

Sample Output 4

64

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let upper = buf.trim().parse::<i32>().unwrap();

    let mut pow2 = 1;
    if upper == 1 {
        println!("1");
    } else {
        while pow2 <= upper {
            pow2 *= 2;
        }
        println!("{}", pow2 / 2);
    }
}


Celsius/Fahrenheit

  In Japan, temperature is usually expressed using the Celsius (&#x2103) scale. In America, they used the Fahrenheit (&#x2109) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Today’s temperature is $68$ degrees" is commonly encountered while you are in America.

A value in Fahrenheit can be converted to Celsius by first subtracting $32$ and then multiplying by $\frac{5}{9}$. A simplified method may be used to produce a rough estimate: first subtract $30$ and then divide by $2$. Using the latter method, $68$ Fahrenheit is converted to $19$ Centigrade, i.e., $\frac{(68-30)}{2}$.

  Make a program to convert Fahrenheit to Celsius using the simplified method: $C = \frac{F - 30}{2}$.

Input

  The input is given in the following format.

$F$

  The input line provides a temperature in Fahrenheit $F$ ($30 \leq F \leq 100$), which is an integer divisible by $2$.

Output

  Output the converted Celsius temperature in a line.

Sample Input 1

68

Sample Output 1

19

Sample Input 2

50

Sample Output 2

10

fn solution() {
    let stdin = stdin();
    let line = stdin.lock().lines().next().unwrap().unwrap();

    let f: i32 = line.parse().unwrap();

    let c = (f - 30) / 2;

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


Score : <var>400</var> points

Problem Statement

You have a sequence <var>A</var> composed of <var>N</var> positive integers: <var>A_{1}, A_{2}, \cdots, A_{N}</var>.

You will now successively do the following <var>Q</var> operations:

In the <var>i</var>-th operation, you replace every element whose value is <var>B_{i}</var> with <var>C_{i}</var>.

For each <var>i</var> <var>(1 \leq i \leq Q)</var>, find <var>S_{i}</var>: the sum of all elements in <var>A</var> just after the <var>i</var>-th operation.

Constraints

All values in input are integers.

<var> 1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5} </var>

<var> B_{i} \neq C_{i} </var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_{1}</var> <var>A_{2}</var> <var>\cdots</var> <var>A_{N}</var>
<var>Q</var>
<var>B_{1}</var> <var>C_{1}</var>
<var>B_{2}</var> <var>C_{2}</var>
<var>\vdots</var>
<var>B_{Q}</var> <var>C_{Q}</var>

Output

Print <var>Q</var> integers <var>S_{i}</var> to Standard Output in the following format:

<var>S_{1}</var>
<var>S_{2}</var>
<var>\vdots</var>
<var>S_{Q}</var>

Note that <var>S_{i}</var> may not fit into a <var>32</var>-bit integer.

Sample Input 1

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

Sample Output 1

11
12
16

Initially, the sequence <var>A</var> is <var>1,2,3,4</var>.

After each operation, it becomes the following:

<var>2, 2, 3, 4</var>

<var>2, 2, 4, 4</var>

<var>4, 4, 4, 4</var>

Sample Input 2

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

Sample Output 2

8
4
4

Note that the sequence <var>A</var> may not contain an element whose value is <var>B_{i}</var>.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000

int solution() {

  int n = 0;

  int data[100002];
  int nannko[1000002];
  for (int i = 0; i < 1000001; i++) {
    nannko[i] = 0;
  }

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

  scanf("%d", &q);

  long long count = 0;
  int a;
  int move;
  long long disa = 0;
  for (int i = 0; i < 100001; i++) {
    count = count + (long long)nannko[i] * i;
  }
  for (int j = 0; j < q; j++) {
    scanf("%d %d", &a, &move);
    disa = (long long)nannko[a] * (move - a);
    nannko[move] = nannko[move] + nannko[a];
    nannko[a] = 0;

    count = count + disa;
    printf("%lld\n", count);
  }
}

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

    let mut cnt = vec![0; 100010];
    for i in 0..n {
        cnt[a[i]] += 1;
    }
    let mut sum = a.iter().sum::<usize>();

    let mut out = Vec::new();
    for _ in 0..q {
        let b: usize = itr.next().unwrap().parse().unwrap();
        let c: usize = itr.next().unwrap().parse().unwrap();

        let v1 = cnt[c] * c;
        let v2 = cnt[b] * b;
        sum -= v2 + v1;
        cnt[c] += cnt[b];
        cnt[b] = 0;
        sum += cnt[c] * c;
        writeln!(out, "{}", sum).ok();
    }
    stdout().write_all(&out).unwrap();
}


You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations:   Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation:   $$$x = 0$$$, $$$y = 6$$$;  $$$x = 0$$$, $$$y = 8$$$;  $$$x = -1$$$, $$$y = 7$$$;  $$$x = 1$$$, $$$y = 7$$$.   Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation:   $$$x = -1$$$, $$$y = 6$$$;  $$$x = 1$$$, $$$y = 8$$$.  Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.

int solution() {

  int n;
  scanf("%d", &n);
  while (n--) {
    long long x;
    long long y;
    long long a;
    long long b;
    long long cost = 0;
    scanf("%lld %lld", &x, &y);
    scanf("%lld %lld", &a, &b);
    if (x > 0 && y > 0 && a * 2 >= b) {
      if (x > y) {
        cost += b * y;
        x -= y;
        y = 0;
        cost += a * x;
      } else {
        cost += b * x;
        y -= x;
        x = 0;
        cost += a * y;
      }
    } else {
      cost += a * x;
      cost += a * y;
    }
    printf("%lld\n", cost);
  }

  return 0;
}

fn solution() {
    let mut input_str = String::new();
    io::stdin().read_line(&mut input_str).expect("err");
    let t = input_str.trim().parse::<u32>().unwrap();
    for _ in 0..t {
        input_str.clear();
        io::stdin().read_line(&mut input_str).expect("err");
        io::stdin().read_line(&mut input_str).expect("err");

        let line = input_str.replace("\n", " ");
        let list: Vec<&str> = line.split_whitespace().collect();
        let (x, y, a, b) = (
            list[0].parse::<u64>().unwrap(),
            list[1].parse::<u64>().unwrap(),
            list[2].parse::<u64>().unwrap(),
            list[3].parse::<u64>().unwrap(),
        );

        if b < 2 * a {
            let min_val = cmp::min(x, y);
            let max_val = cmp::max(x, y);
            println!("{}", min_val * b + (max_val - min_val) * a);
        } else {
            println!("{}", (x + y) * a);
        }
    }
}


You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.

int solution() {
  int n;
  scanf("%d", &n);
  int a[n + 1];
  int i;
  int visit[n + 1];
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    visit[i + 1] = 0;
  }
  int l = 0;
  int r = a[0];
  int max_value = a[0];
  int count;
  int max = -1;
  visit[a[0]] = -1;
  for (i = 1; i < n; i++) {

    if (l < a[i] && r > a[i]) {
      visit[r]++;
      l = a[i];
    } else if (a[i] > r) {

      l = r;
      r = a[i];
      visit[a[i]] = -1;
    } else if (a[i] < l) {
      visit[a[i]] = 0;
    }
  }
  max = -2;
  for (i = 1; i <= n; i++) {
    if (max < visit[i]) {
      max_value = i;
      max = visit[i];
    }
  }
  printf("%d\n", max_value);

  return 0;
}

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()
        .map(|x| x.parse::<usize>().unwrap());

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

    if n == 1 {
        println!("1");
        return;
    }

    let p: Vec<_> = it.collect();

    let m_2m: Vec<_> = p
        .iter()
        .cloned()
        .scan((0, 0), |state, p| {
            if p > state.0 {
                state.1 = state.0;
                state.0 = p;
            } else if p > state.1 {
                state.1 = p;
            }
            Some(*state)
        })
        .collect();

    let mut cnts = vec![0; n + 1];
    for i in 0..n - 1 {
        if m_2m[i].1 < p[i + 1] && p[i + 1] < m_2m[i].0 {
            cnts[m_2m[i].0] += 1;
        }
    }

    let m = cnts.iter().cloned().max().unwrap();
    let ans = if m > 1 {
        cnts.iter().cloned().position(|cnt| cnt == m).unwrap()
    } else {
        if let Some((idx, _)) = p
            .iter()
            .cloned()
            .skip(1)
            .zip(m_2m.iter().map(|x| x.0))
            .filter(|&(p, max)| p < max)
            .min()
        {
            idx
        } else {
            1
        }
    };

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


Circle in a Rectangle

  Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.

Input

  Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line.

Output

  Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line.

Constraints

$ -100  \leq x, y \leq 100$

$ 0  < W, H, r \leq 100$

Sample Input 1

5 4 2 2 1

Sample Output 1

Yes

Sample Input 2

5 4 2 4 1

Sample Output 2

No

int solution() {
  int W = 0;
  int H = 0;
  int x = 0;
  int y = 0;
  int r = 0;

  scanf("%d %d %d %d %d", &W, &H, &x, &y, &r);

  if ((x >= r) && (W >= (x + r)) && (y >= r) && (H >= (y + r))) {
    printf("Yes\n");
  } else {
    printf("No\n");
  }

  return 0;
}

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

    let mut line = String::new();

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

    let W: i32 = vec[0].parse().unwrap_or(0);
    let H: i32 = vec[1].parse().unwrap_or(0);
    let x: i32 = vec[2].parse().unwrap_or(0);
    let y: i32 = vec[3].parse().unwrap_or(0);
    let r: i32 = vec[4].parse().unwrap_or(0);

    if x >= r && x <= (W - r) && y >= r && y <= (H - r) {
        println!("Yes");
    } else {
        println!("No");
    }
}


There are $$$n$$$ dormitories in Berland State University, they are numbered with integers from $$$1$$$ to $$$n$$$. Each dormitory consists of rooms, there are $$$a_i$$$ rooms in $$$i$$$-th dormitory. The rooms in $$$i$$$-th dormitory are numbered from $$$1$$$ to $$$a_i$$$.A postman delivers letters. Sometimes there is no specific dormitory and room number in it on an envelope. Instead of it only a room number among all rooms of all $$$n$$$ dormitories is written on an envelope. In this case, assume that all the rooms are numbered from $$$1$$$ to $$$a_1 + a_2 + \dots + a_n$$$ and the rooms of the first dormitory go first, the rooms of the second dormitory go after them and so on.For example, in case $$$n=2$$$, $$$a_1=3$$$ and $$$a_2=5$$$ an envelope can have any integer from $$$1$$$ to $$$8$$$ written on it. If the number $$$7$$$ is written on an envelope, it means that the letter should be delivered to the room number $$$4$$$ of the second dormitory.For each of $$$m$$$ letters by the room number among all $$$n$$$ dormitories, determine the particular dormitory and the room number in a dormitory where this letter should be delivered.

int solution() {
  long int n;
  long int m;
  long int j = 0;
  long long int roomnbr = 0;
  scanf("%ld%ld", &n, &m);
  long long int rooms[n];
  long long int lettersnbr[m];
  for (long int i = 0; i < n; i++) {
    scanf("%lld", &rooms[i]);
  }

  for (long int i = 0; i < m; i++) {
    scanf("%lld", &lettersnbr[i]);
  }

  for (long int i = 0; i < n; i++) {
    roomnbr += rooms[i];
    while (j < m) {
      if (lettersnbr[j] <= roomnbr && i == 0) {
        printf("%ld %lld\n", i + 1, lettersnbr[j]);
      } else if (lettersnbr[j] <= roomnbr) {
        printf("%ld %lld\n", i + 1, lettersnbr[j] - (roomnbr - rooms[i]));
      } else if (lettersnbr[j] > roomnbr) {
        break;
      }
      j++;
    }
  }

  return 0;
}

fn solution() {
    let mut string = String::new();
    io::stdin().read_line(&mut string).unwrap();
    let mut iter = string.trim().split(" ").map(|x| x.parse().unwrap());
    let (_n, _m): (usize, usize) = (iter.next().unwrap(), iter.next().unwrap());
    let mut string = String::new();
    io::stdin().read_line(&mut string).unwrap();
    let a: Vec<u64> = string
        .trim()
        .split(" ")
        .map(|x| x.parse().unwrap())
        .collect();
    let mut string = String::new();
    io::stdin().read_line(&mut string).unwrap();
    let rooms: Vec<u64> = string
        .trim()
        .split(" ")
        .map(|x| x.parse().unwrap())
        .collect();

    let mut room_sum = 0;
    let mut current_dorm: usize = 0;
    for room in rooms {
        let mut just_above = room - room_sum;
        if just_above <= a[current_dorm] {
            println!("{} {}", current_dorm + 1, just_above);
        } else {
            while just_above > a[current_dorm] {
                room_sum += a[current_dorm];
                just_above = room - room_sum;
                current_dorm += 1;
            }
            println!("{} {}", current_dorm + 1, just_above);
        }
    }
}


Score : <var>200</var> points

Problem Statement

You have an integer variable <var>x</var>.
Initially, <var>x=0</var>.

Some person gave you a string <var>S</var> of length <var>N</var>, and using the string you performed the following operation <var>N</var> times.
In the <var>i</var>-th operation, you incremented the value of <var>x</var> by <var>1</var> if <var>S_i=</var>I, and decremented the value of <var>x</var> by <var>1</var> if <var>S_i=</var>D.

Find the maximum value taken by <var>x</var> during the operations (including before the first operation, and after the last operation).

Constraints

<var>1≤N≤100</var>

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

No characters except I and D occur in <var>S</var>.

Input

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

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

Output

Print the maximum value taken by <var>x</var> during the operations.

Sample Input 1

5
IIDID

Sample Output 1

2

After each operation, the value of <var>x</var> becomes <var>1</var>, <var>2</var>, <var>1</var>, <var>2</var> and <var>1</var>, respectively. Thus, the output should be <var>2</var>, the maximum value.

Sample Input 2

7
DDIDDII

Sample Output 2

0

The initial value <var>x=0</var> is the maximum value taken by <var>x</var>, thus the output should be <var>0</var>.

int solution() {
  int n = 0;
  int a = 0;
  int b = 0;
  int max = 0;
  char s[101];
  scanf("%d %s", &n, s);
  for (a = 0; a < n; a++) {
    if (s[a] == 'I') {
      b++;

    } else {
      b--;
    }

    if (max < b) {
      max = b;
    }
  }
  printf("%d\n", max);
  return 0;
}

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

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

    let mut x = 0;
    let mut max = 0;
    for c in s.chars() {
        if c == 'I' {
            x += 1;
            if x > max {
                max = x;
            }
        } else {
            x -= 1;
        }
    }
    println!("{}", max);
}


int solution(const int arr[], int n, int key) {
  int low = 0;
  int high = n - 1;
  while (low <= high && key >= arr[low] && key <= arr[high]) {

    int pos =
        low + (((key - arr[low]) * (high - low)) / (arr[high] - arr[low]));
    if (key > arr[pos]) {
      low = pos + 1;
    } else if (key < arr[pos]) {
      high = pos - 1;
    } else {
      return pos;
    }
  }

  return -1;
}

fn solution<Ordering>(nums: &[i32], item: &i32) -> Result<usize, usize> {
    if nums.is_empty() {
        return Err(0);
    }
    let mut low: usize = 0;
    let mut high: usize = nums.len() - 1;
    while low <= high {
        if *item < nums[low] || *item > nums[high] {
            break;
        }
        let offset: usize = low
            + (((high - low) / (nums[high] - nums[low]) as usize) * (*item - nums[low]) as usize);
        match nums[offset].cmp(item) {
            std::cmp::Ordering::Equal => return Ok(offset),
            std::cmp::Ordering::Less => low = offset + 1,
            std::cmp::Ordering::Greater => high = offset - 1,
        }
    }
    Err(0)
}


We will consider the numbers $$$a$$$ and $$$b$$$ as adjacent if they differ by exactly one, that is, $$$|a-b|=1$$$.We will consider cells of a square matrix $$$n \times n$$$ as adjacent if they have a common side, that is, for cell $$$(r, c)$$$ cells $$$(r, c-1)$$$, $$$(r, c+1)$$$, $$$(r-1, c)$$$ and $$$(r+1, c)$$$ are adjacent to it.For a given number $$$n$$$, construct a square matrix $$$n \times n$$$ such that:   Each integer from $$$1$$$ to $$$n^2$$$ occurs in this matrix exactly once;  If $$$(r_1, c_1)$$$ and $$$(r_2, c_2)$$$ are adjacent cells, then the numbers written in them must not be adjacent.

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

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

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

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

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

        if n == 2 {
            writeln!(&mut output, "-1").unwrap();
            continue;
        }

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

        let mut x = 1;

        let mut i = 0;
        while i < mat.len() {
            mat[i] = x;
            x += 1;
            i += 2;
        }

        let mut i = 1;
        while i < mat.len() {
            mat[i] = x;
            x += 1;
            i += 2;
        }

        let mut it = mat.into_iter();
        for _ in 0..n {
            for _ in 0..n {
                write!(&mut output, "{} ", it.next().unwrap()).unwrap();
            }
            writeln!(&mut output).unwrap();
        }
        continue;

        let mut x = 1;
        let mut y = n * n;
        let mut c = 0;

        while x <= y {
            write!(&mut output, "{} ", x).unwrap();
            c += 1;
            x += 1;
            if c == n {
                c = 0;
                writeln!(&mut output).unwrap()
            }

            write!(&mut output, "{} ", x).unwrap();
            c += 1;
            y -= 1;
            if c == n {
                c = 0;
                writeln!(&mut output).unwrap()
            }
        }
    }
}


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

int solution() {
  char message[30];
  char message1[30];
  char A[500];
  char B[500];
  int check;
  int a;
  int b;
  int c;
  int d;
  int k;
  int i;
  int j;
  int q;
  scanf("%d", &q);
  for (i = 0; i < q; i++) {
    check = 1;
    scanf("%s", message);
    scanf("%s", message1);
    a = strlen(message);
    b = strlen(message1);
    c = strlen(message);
    d = strlen(message1);
    while (a != 0 && b != 0) {
      if (a >= b) {
        a = a % b;
      } else {
        b = b % a;
      }
    }
    if (a == 0) {
      k = c * d / b;
    } else {
      k = c * d / a;
    }
    for (j = 0; j < k; j++) {
      A[j] = message[j % c];
      B[j] = message1[j % d];
      if (A[j] != B[j]) {
        check = 0;
        break;
      }
    }
    if (check == 1) {
      if (d >= c) {
        for (j = 0; j < k / d; j++) {
          printf("%s", message1);
        }
        printf("\n");
      } else {
        for (j = 0; j < k / c; j++) {
          printf("%s", message);
        }
        printf("\n");
      }
    } else {
      printf("-1\n");
    }
  }
  return 0;
}

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

    let mut lines = input.lines();

    lines.next();

    while let Some(line) = lines.next() {
        let s = line;
        let t = lines.next().unwrap();

        for (i, (c0, c1)) in s.chars().cycle().zip(t.chars().cycle()).enumerate() {
            if i > 0 && i % s.len() == 0 && i % t.len() == 0 {
                for _ in 0..(i / s.len()) {
                    print!("{}", s);
                }
                println!();
                break;
            }

            if c0 != c1 {
                println!("-1");
                break;
            }
        }
    }
}


Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up.

int solution() {
  int n;
  int M;
  int i;
  int array[100002];
  scanf("%d %d", &n, &M);
  array[0] = 0;
  for (i = 0; i < n; i++) {
    scanf("%d", &array[i + 1]);
  }
  array[n + 1] = M;
  int max = 0;
  int state = 0;
  for (i = 0; i < n + 2; i++) {
    if (state == 1) {
      max += array[i] - array[i - 1];
      state = 0;
    } else {
      state = 1;
    }
  }
  int up0 = 0;
  int up1 = max - (array[1] - array[0]);
  state = 1;
  for (i = 1; i < n + 2; i++) {
    int reverse = M - array[i] - up1;
    int change = up0 + array[i] - array[i - 1] - 1 + reverse;
    if (state == 1) {
      if (change > max) {
        max = change;
      }
      up0 += array[i] - array[i - 1];
      state = 0;
    } else {
      if (change > max) {
        max = change;
      }
      if (i < n + 1) {
        up1 -= array[i + 1] - array[i];
      }
      state = 1;
    }
  }
  printf("%d\n", max);
  return 0;
}

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

    let n = get!(usize);
    let m = get!();
    let mut xs = vec![];
    xs.push(0);
    for _ in 0..n {
        xs.push(get!());
    }
    xs.push(m);
    let mut ontime = 0;
    let mut offtime = 0;
    for i in 0..n + 1 {
        if i % 2 == 0 {
            ontime += xs[i + 1] - xs[i];
        } else {
            offtime += xs[i + 1] - xs[i];
        }
    }
    let mut ans = ontime;
    let mut tmp_ontime = 0;
    let mut tmp_offtime = 0;
    for i in 0..n + 1 {
        if i % 2 == 0 {
            let rem_offtime = offtime - tmp_offtime;
            let j = xs[i + 1] - 1;
            if j > xs[i] {
                ans = std::cmp::max(ans, tmp_ontime + (j - xs[i]) + rem_offtime);
            }
            tmp_ontime += xs[i + 1] - xs[i];
        } else {
            let rem_offtime = offtime - tmp_offtime - (xs[i + 1] - xs[i]);
            let j = xs[i] + 1;
            if j < xs[i + 1] {
                ans = std::cmp::max(ans, tmp_ontime + (xs[i + 1] - j) + rem_offtime);
            }
            tmp_offtime += xs[i + 1] - xs[i];
        }
    }

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


Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$.  Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.

int solution() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int N;
    scanf("%d", &N);
    int arr[N + 1];
    for (int i = 0; i < N; i++) {
      scanf("%d", arr + i);
    }
    arr[N] = 0;
    long long a1 = arr[0];
    long long ans = 0;
    for (int i = 0; i < N - 1; i++) {
      long long d = arr[i + 1] - arr[i];
      if (d <= 0) {
        ans -= d, a1 += d;
      } else {
        ans += d;
      }
    }
    printf("%lld\n", ans + (a1 >= 0 ? a1 : -a1));
  }
}

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

    let mut lines = content.lines();
    let num_tests: i32 = lines.next().unwrap().parse().unwrap();
    for _ in 0..num_tests {
        let _n: usize = lines.next().unwrap().parse().unwrap();
        let a: Vec<i64> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse::<i64>().unwrap())
            .collect();
        let mut result = 0;
        let mut left = -a[0];
        for i in 0..a.len() - 1 {
            if a[i] < a[i + 1] {
                result += a[i + 1] - a[i];
            } else {
                result += a[i] - a[i + 1];
                left += a[i] - a[i + 1];
            }
        }
        result += left.abs();
        println!("{result}");
    }
}


Score : <var>200</var> points

Problem Statement

It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts.

There are <var>N</var> houses along TopCoDeer street. The <var>i</var>-th house is located at coordinate <var>a_i</var>. He has decided to deliver gifts to all these houses.

Find the minimum distance to be traveled when AtCoDeer can start and end his travel at any positions.

Constraints

<var>1 ≤ N ≤ 100</var>

<var>0 ≤ a_i ≤ 1000</var>

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum distance to be traveled.

Sample Input 1

4
2 3 7 9

Sample Output 1

7

The travel distance of <var>7</var> can be achieved by starting at coordinate <var>9</var> and traveling straight to coordinate <var>2</var>.

It is not possible to do with a travel distance of less than <var>7</var>, and thus <var>7</var> is the minimum distance to be traveled.

Sample Input 2

8
3 1 4 1 5 9 2 6

Sample Output 2

8

There may be more than one house at a position.

int solution() {

  int N = 0;
  int POS[110];
  for (int i = 0; i < 110; i++) {
    POS[i] = 0;
  }

  int MAX = 0;
  int MIN = 10000;

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

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

    if (POS[i] > MAX) {
      MAX = POS[i];
    }

    if (POS[i] < MIN) {
      MIN = POS[i];
    }
  }

  printf("%d", MAX - MIN);

  return 0;
}

fn solution() {
    use std::io;
    let mut input1 = String::new();
    let mut input2 = String::new();
    let _ = io::stdin().read_line(&mut input1);
    let _ = io::stdin().read_line(&mut input2);

    let inputs: Vec<isize> = input2
        .split_whitespace()
        .map(|x| x.parse::<isize>().unwrap())
        .collect::<Vec<_>>();

    let mut min = 1000;
    let mut max = 0;
    for val in &inputs {
        if min > *val {
            min = *val;
        }
        if max < *val {
            max = *val;
        }
    }
    println!("{}", max - min);
}


Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let mut input_iter = input.split_whitespace();
    let n = input_iter.next().unwrap().parse::<u32>().unwrap();
    let d = input_iter.next().unwrap().parse::<u32>().unwrap();
    let e = 5 * input_iter.next().unwrap().parse::<u32>().unwrap();
    let min = (n - ((n / d) * d)..=n)
        .step_by(d as usize)
        .map(|i| i % e)
        .fold(n, |min, x| if x < min { x } else { min });
    println!("{}", min);
}


A binary string is a string where each character is either 0 or 1. Two binary strings $$$a$$$ and $$$b$$$ of equal length are similar, if they have the same character in some position (there exists an integer $$$i$$$ such that $$$a_i = b_i$$$). For example:  10010 and 01111 are similar (they have the same character in position $$$4$$$);  10010 and 11111 are similar;  111 and 111 are similar;  0110 and 1001 are not similar. You are given an integer $$$n$$$ and a binary string $$$s$$$ consisting of $$$2n-1$$$ characters. Let's denote $$$s[l..r]$$$ as the contiguous substring of $$$s$$$ starting with $$$l$$$-th character and ending with $$$r$$$-th character (in other words, $$$s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r$$$).You have to construct a binary string $$$w$$$ of length $$$n$$$ which is similar to all of the following strings: $$$s[1..n]$$$, $$$s[2..n+1]$$$, $$$s[3..n+2]$$$, ..., $$$s[n..2n-1]$$$.

fn solution() {
    let mut string = String::new();
    io::stdin()
        .read_line(&mut string)
        .expect("Failed to read string");
    for _ in 0..string.trim().parse().unwrap() {
        string.clear();
        io::stdin()
            .read_line(&mut string)
            .expect("Failed to read string");
        let n = string.trim().parse().unwrap();
        string.clear();
        io::stdin()
            .read_line(&mut string)
            .expect("Failed to read string");
        let byte_string = string.trim();
        let mut ans = String::with_capacity(n);
        for (idx, substr) in byte_string.as_bytes().windows(n).enumerate() {
            ans.push(substr[idx] as char);
        }
        println!("{}", ans);
    }
}


Score : <var>100</var> points

Problem Statement

This contest is CODE FESTIVAL.
However, Mr. Takahashi always writes it CODEFESTIVAL, omitting the single space between CODE and FESTIVAL.

So he has decided to make a program that puts the single space he omitted.

You are given a string <var>s</var> with <var>12</var> letters.
Output the string putting a single space between the first <var>4</var> letters and last <var>8</var> letters in the string <var>s</var>.

Constraints

<var>s</var> contains exactly <var>12</var> letters.

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

Input

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

<var>s</var>

Output

Print the string putting a single space between the first <var>4</var> letters and last <var>8</var> letters in the string <var>s</var>.
Put a line break at the end.

Sample Input 1

CODEFESTIVAL

Sample Output 1

CODE FESTIVAL

Putting a single space between the first <var>4</var> letters and last <var>8</var> letters in CODEFESTIVAL makes it CODE FESTIVAL.

Sample Input 2

POSTGRADUATE

Sample Output 2

POST GRADUATE

Sample Input 3

ABCDEFGHIJKL

Sample Output 3

ABCD EFGHIJKL

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

    let S = buf_it.next().unwrap();

    println!("{} {}", &S[..4], &S[4..]);
}


George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.

int solution() {
  int n = 0;
  int i = 0;
  int retval = 0;
  int p[100];
  int q[100];
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d %d", p + i, q + i);
  }
  for (i = 0; i < n; i++) {
    if (q[i] > p[i] + 1) {
      retval++;
    }
  }
  printf("%d", retval);
  return 0;
}

fn solution() {
    let mut n_text = String::new();
    std::io::stdin().read_line(&mut n_text).expect("");
    let n = n_text.trim().parse::<i32>().expect("");
    let mut result = 0;
    for _ in 0..n {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).expect("");
        let mut it = line.split_whitespace();
        let p = it.next().unwrap().parse::<i32>().expect("");
        let q = it.next().unwrap().parse::<i32>().expect("");
        if p + 2 <= q {
            result += 1
        }
    }
    println!("{}", result);
}


You are given two integers $$$a$$$ and $$$b$$$. In one turn, you can do one of the following operations:   Take an integer $$$c$$$ ($$$c > 1$$$ and $$$a$$$ should be divisible by $$$c$$$) and replace $$$a$$$ with $$$\frac{a}{c}$$$;  Take an integer $$$c$$$ ($$$c > 1$$$ and $$$b$$$ should be divisible by $$$c$$$) and replace $$$b$$$ with $$$\frac{b}{c}$$$. Your goal is to make $$$a$$$ equal to $$$b$$$ using exactly $$$k$$$ turns.For example, the numbers $$$a=36$$$ and $$$b=48$$$ can be made equal in $$$4$$$ moves:   $$$c=6$$$, divide $$$b$$$ by $$$c$$$ $$$\Rightarrow$$$ $$$a=36$$$, $$$b=8$$$;  $$$c=2$$$, divide $$$a$$$ by $$$c$$$ $$$\Rightarrow$$$ $$$a=18$$$, $$$b=8$$$;  $$$c=9$$$, divide $$$a$$$ by $$$c$$$ $$$\Rightarrow$$$ $$$a=2$$$, $$$b=8$$$;  $$$c=4$$$, divide $$$b$$$ by $$$c$$$ $$$\Rightarrow$$$ $$$a=2$$$, $$$b=2$$$. For the given numbers $$$a$$$ and $$$b$$$, determine whether it is possible to make them equal using exactly $$$k$$$ turns.

int solution() {
  int t;
  scanf("%d", &t);
  while (t > 0) {
    long long int a;
    long long int b;
    long long int k;
    long long int i;
    long long int n;
    long long int count = 0;
    long long int counta = 0;
    long long int countb = 0;
    scanf("%lld%lld%lld", &a, &b, &k);
    if (k == 1) {
      if ((a % b == 0 || b % a == 0) && a != b) {
        printf("YES\n");
      } else {
        printf("NO\n");
      }
    } else {
      if (a > b) {
        n = sqrt(a);
      } else {
        n = sqrt(b);
      }

      while (a % 2 == 0) {
        a = a / 2;
        counta++;
      }
      while (b % 2 == 0) {
        b = b / 2;
        countb++;
      }
      for (i = 3; i <= n; i = i + 2) {

        while (a % i == 0) {
          a = a / i;
          counta++;
        }
        while (b % i == 0) {
          b = b / i;
          countb++;
        }
      }
      if (a > 2 && b > 2 && a == b) {
        count++;
      }
      if (a > 2) {
        counta++;
      }
      if (b > 2) {
        countb++;
      }
      if (counta + countb < k) {
        printf("NO\n");
      } else {
        printf("YES\n");
      }
    }
    t--;
  }
}

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

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

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

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

    let np = 100_000;
    let mut sieve = vec![true; np];
    sieve[0] = false;
    sieve[1] = false;
    for p in (2..).take_while(|&p| p * p <= np) {
        if !sieve[p] {
            continue;
        }
        for i in (p..).take_while(|&i| p * i < np) {
            sieve[i * p] = false;
        }
    }

    let prime_list: Vec<_> = sieve
        .into_iter()
        .enumerate()
        .filter_map(|(p, b)| if b { Some(p as u64) } else { None })
        .collect();

    'cases: for _case_index in 1..=t {
        let s = lines.next().unwrap();
        let mut it = s.split_whitespace().map(|s| s.parse::<u64>().unwrap());

        let a = it.next().unwrap();
        let b = it.next().unwrap();
        let k = it.next().unwrap();

        let ndivisors = |n| {
            let mut x = n;
            let mut r = 0;

            for &p in &prime_list {
                if x == 1 {
                    break;
                }
                if p * p > x {
                    r += 1;
                    break;
                }
                while x % p == 0 {
                    x /= p;
                    r += 1;
                }
            }

            r
        };

        let ans = if k == 1 {
            a != b && (a % b == 0 || b % a == 0)
        } else {
            let stall = ndivisors(a) + ndivisors(b);
            k <= stall
        };

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

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


Score : <var>700</var> points

Problem Statement

Aoki loves numerical sequences and trees.

One day, Takahashi gave him an integer sequence of length <var>N</var>, <var>a_1, a_2, ..., a_N</var>, which made him want to construct a tree.

Aoki wants to construct a tree with <var>N</var> vertices numbered <var>1</var> through <var>N</var>, such that for each <var>i = 1,2,...,N</var>, the distance between vertex <var>i</var> and the farthest vertex from it is <var>a_i</var>, assuming that the length of each edge is <var>1</var>.

Determine whether such a tree exists.

Constraints

<var>2 ≦ N ≦ 100</var>

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

Input

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

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

Output

If there exists a tree that satisfies the condition, print Possible. Otherwise, print Impossible.

Sample Input 1

5
3 2 2 3 3

Sample Output 1

Possible

The diagram above shows an example of a tree that satisfies the conditions. The red arrows show paths from each vertex to the farthest vertex from it.

Sample Input 2

3
1 1 2

Sample Output 2

Impossible

Sample Input 3

10
1 2 2 2 2 2 2 2 2 2

Sample Output 3

Possible

Sample Input 4

10
1 1 2 2 2 2 2 2 2 2

Sample Output 4

Impossible

Sample Input 5

6
1 1 1 1 1 5

Sample Output 5

Impossible

Sample Input 6

5
4 3 2 3 4

Sample Output 6

Possible

int solution(void) {
  int N;
  int i;
  int j;
  int k;
  int num[101] = {0};

  scanf("%d", &N);
  for (i = 0; i < N; i++) {
    scanf("%d", &k);
    num[k]++;
  }

  for (i = 0; num[i] == 0; i++) {
    ;
  }
  if (num[i] > 2) {
    puts("Impossible");
    return 0;
  }

  k = i;

  for (i++; num[i] != 0; i++) {
    if (num[i] == 1) {
      puts("Impossible");
      return 0;
    }
  }

  for (j = i + 1; j < N; j++) {
    if (num[j] != 0) {
      puts("Impossible");
      return 0;
    }
  }

  if (i - 1 > k * 2 - (num[k] - 1)) {
    puts("Impossible");
  } else {
    puts("Possible");
  }
  return 0;
}

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

    let mut c = vec![0; N];
    for &x in &a {
        c[x] += 1;
    }
    let m = *a.iter().min().unwrap();
    let ans = if (c[m] == 1
        && ((m + 1)..(2 * m + 1)).all(|i| c[i] >= 2)
        && ((2 * m + 1)..N).all(|i| c[i] == 0))
        || (c[m] == 2 && ((m + 1)..(2 * m)).all(|i| c[i] >= 2) && ((2 * m)..N).all(|i| c[i] == 0))
    {
        "Possible"
    } else {
        "Impossible"
    };

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


You are given a string $$$s$$$. You need to find two non-empty strings $$$a$$$ and $$$b$$$ such that the following conditions are satisfied:  Strings $$$a$$$ and $$$b$$$ are both subsequences of $$$s$$$.  For each index $$$i$$$, character $$$s_i$$$ of string $$$s$$$ must belong to exactly one of strings $$$a$$$ or $$$b$$$.  String $$$a$$$ is lexicographically minimum possible; string $$$b$$$ may be any possible string. Given string $$$s$$$, print any valid $$$a$$$ and $$$b$$$.Reminder:A string $$$a$$$ ($$$b$$$) is a subsequence of a string $$$s$$$ if $$$a$$$ ($$$b$$$) can be obtained from $$$s$$$ by deletion of several (possibly, zero) elements. For example, "dores", "cf", and "for" are subsequences of "codeforces", while "decor" and "fork" are not.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds:  $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$;  in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

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

  char buffer[102];
  for (int c = 0; c < n; c++) {
    scanf("%s", buffer);

    int i = 0;
    int min = (int)'z';
    int min_i = 0;
    while (buffer[i] != '\0') {
      if ((int)buffer[i] < min) {
        min = (int)buffer[i];
        min_i = i;
      }
      i += 1;
    }

    buffer[min_i] = '\0';
    printf("%c %s%s\n", min, buffer, &buffer[min_i + 1]);
  }
  return 0;
}

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

    let t = input.next().unwrap().parse().unwrap();
    for _ in 0..t {
        let s = input.next().unwrap().as_bytes();
        let mn_pos = s
            .iter()
            .enumerate()
            .fold(0, |mn_pos, (i, c)| if c < &s[mn_pos] { i } else { mn_pos });
        println!(
            "{} {}",
            s[mn_pos] as char,
            String::from_utf8(s[..mn_pos].to_vec()).unwrap()
                + core::str::from_utf8(&s[mn_pos + 1..]).unwrap()
        );
    }
}


Score : <var>500</var> points

Problem Statement

You are going to eat <var>X</var> red apples and <var>Y</var> green apples.

You have <var>A</var> red apples of deliciousness <var>p_1,p_2, \dots, p_A</var>, <var>B</var> green apples of deliciousness <var>q_1,q_2, \dots, q_B</var>, and <var>C</var> colorless apples of deliciousness <var>r_1,r_2, \dots, r_C</var>.

Before eating a colorless apple, you can paint it red or green, and it will count as a red or green apple, respectively.

From the apples above, you will choose the apples to eat while making the sum of the deliciousness of the eaten apples as large as possible.

Find the maximum possible sum of the deliciousness of the eaten apples that can be achieved when optimally coloring zero or more colorless apples.

Constraints

<var>1 \leq X \leq A \leq 10^5</var>

<var>1 \leq Y \leq B \leq 10^5</var>

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

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>Y</var> <var>A</var> <var>B</var> <var>C</var>
<var>p_1</var> <var>p_2</var> <var>...</var> <var>p_A</var>
<var>q_1</var> <var>q_2</var> <var>...</var> <var>q_B</var>
<var>r_1</var> <var>r_2</var> <var>...</var> <var>r_C</var>

Output

Print the maximum possible sum of the deliciousness of the eaten apples.

Sample Input 1

1 2 2 2 1
2 4
5 1
3

Sample Output 1

12

The maximum possible sum of the deliciousness of the eaten apples can be achieved as follows:

Eat the <var>2</var>-nd red apple.

Eat the <var>1</var>-st green apple.

Paint the <var>1</var>-st colorless apple green and eat it.

Sample Input 2

2 2 2 2 2
8 6
9 1
2 1

Sample Output 2

25

Sample Input 3

2 2 4 4 4
11 12 13 14
21 22 23 24
1 2 3 4

Sample Output 3

74

fn solution() {
    let (x, y, _a, _b, _c) = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let s: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
        (s[0], s[1], s[2], s[3], s[4])
    };
    let mut p: Vec<i64> = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.split_whitespace().map(|x| x.parse().unwrap()).collect()
    };
    let mut q: Vec<i64> = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.split_whitespace().map(|x| x.parse().unwrap()).collect()
    };
    let mut r: Vec<i64> = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.split_whitespace().map(|x| x.parse().unwrap()).collect()
    };
    p.sort();
    p.reverse();
    p.truncate(x);
    q.sort();
    q.reverse();
    q.truncate(y);
    r.extend(p);
    r.extend(q);
    r.sort();
    r.reverse();
    r.truncate(x + y);
    println!("{}", r.into_iter().sum::<i64>());
}