Given an array $$$a$$$ of length $$$n$$$, find another array, $$$b$$$, of length $$$n$$$ such that:  for each $$$i$$$ $$$(1 \le i \le n)$$$ $$$MEX(\{b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_i\})=a_i$$$. The $$$MEX$$$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.If such array doesn't exist, determine this.

int solution() {
  long long int n;
  scanf("%lld", &n);

  long long int i;
  long long int a[n];

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

  long long int *isin =
      (long long int *)malloc((pow(10, 6) + 1) * sizeof(long long int));
  long long int *sol = (long long int *)malloc(n * sizeof(long long int));

  for (i = 0; i < pow(10, 6) + 1; ++i) {
    isin[i] = 0;
  }
  for (i = 0; i < n; ++i) {
    sol[i] = -1;
  }

  for (i = 0; i < n; ++i) {
    isin[a[i]] = 1;
  }

  long long int cnt = 0;
  while (isin[cnt] != 0 && cnt <= pow(10, 6)) {
    cnt += 1;
  }
  sol[0] = cnt;
  ++cnt;

  for (i = 1; i < n; ++i) {
    if (a[i] != a[i - 1]) {
      sol[i] = a[i - 1];
    } else {
      if (cnt > pow(10, 6)) {
        sol[i] = cnt;
        ++cnt;
      } else {
        while (isin[cnt] != 0 && cnt <= pow(10, 6)) {
          cnt += 1;
        }
        sol[i] = cnt;
        ++cnt;
      }
    }
  }

  for (i = 0; i < n; ++i) {
    printf("%lld ", sol[i]);
  }
  printf("\n");
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    let xs: Vec<i32> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|x| x.parse().unwrap())
        .collect();
    let mut ys: Vec<i32> = vec![-1; n];
    let mut zs: Vec<i32> = Vec::new();
    for i in 1..n {
        if xs[i - 1] != xs[i] {
            ys[i] = xs[i - 1];
            zs.push(xs[i - 1]);
        }
    }
    zs.push(xs[n - 1]);
    let mut k: usize = 0;
    let mut next: i32 = 0;
    for i in 0..n {
        if ys[i] >= 0 {
            continue;
        }
        while next == zs[k] {
            next += 1;
            if k < zs.len() - 1 {
                k += 1;
            }
        }
        ys[i] = next;
        next += 1;
    }
    for y in ys {
        print!("{} ", y);
    }
    println!();
}


Score : <var>100</var> points

Problem Statement

You are given a string <var>S</var> of length <var>2</var> or <var>3</var> consisting of lowercase English letters. If the length of the string is <var>2</var>, print it as is; if the length is <var>3</var>, print the string after reversing it.

Constraints

The length of <var>S</var> is <var>2</var> or <var>3</var>.

<var>S</var> consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If the length of <var>S</var> is <var>2</var>, print <var>S</var> as is; if the length is <var>3</var>, print <var>S</var> after reversing it.

Sample Input 1

abc

Sample Output 1

cba

As the length of <var>S</var> is <var>3</var>, we print it after reversing it.

Sample Input 2

ac

Sample Output 2

ac

As the length of <var>S</var> is <var>2</var>, we print it as is.

int solution(void) {
  char S[5];
  scanf("%s", &S[0]);

  if (strlen(S) == 2) {
    printf("%c%c", S[0], S[1]);
    return 0;
  }

  if (strlen(S) == 3) {
    printf("%c%c%c", S[2], S[1], S[0]);
    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 s = get().as_bytes();

    if s.len() == 2 {
        print!("{}", s[0] as char);
        println!("{}", s[1] as char);
    } else {
        print!("{}", s[2] as char);
        print!("{}", s[1] as char);
        println!("{}", s[0] as char);
    }
}


This is yet another problem dealing with regular bracket sequences.We should remind you that a bracket sequence is called regular, if by inserting «+» and «1» into it we can get a correct mathematical expression. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not. You are given a string of «(» and «)» characters. You are to find its longest substring that is a regular bracket sequence. You are to find the number of such substrings as well.

int solution() {
  char string[10009001];
  fgets(string, 10090001, stdin);
  int len = strlen(string);
  int stack[10000001];
  stack[0] = -1;
  int top = 0;
  int max_len = 0;
  int temp_len = 0;
  int count = 0;

  for (int i = 0; i < len - 1; i++) {
    if (string[i] == '(') {
      stack[++top] = i;
    } else {
      if (top > 0) {

        top -= 1;

        temp_len = i - stack[top];

        if (temp_len > max_len) {
          max_len = temp_len;
          count = 1;
        } else if (temp_len == max_len) {
          count += 1;
        }
      } else {
        top = 0;
        stack[top] = i;
      }
    }
  }
  if (max_len) {
    printf("%d %d\n", max_len, count);
  } else {
    printf("%d %d\n", 0, 1);
  }
}

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

    let mut cnt = 1;
    let mut max = 0;
    let mut xs: Vec<i64> = vec![-1];
    for (i, &c) in line.as_bytes().to_vec().iter().enumerate() {
        if c == b'(' {
            xs.push(i as i64);
        } else if xs.len() > 1 {
            xs.pop();
            let len = i as i64 - *xs.last().unwrap();
            if max == len {
                cnt += 1;
            } else if max < len {
                cnt = 1;
                max = len;
            }
        } else {
            xs[0] = i as i64;
        }
    }

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


Score : <var>400</var> points

Problem Statement

There are <var>N</var> squares aligned in a row.
The <var>i</var>-th square from the left contains an integer <var>a_i</var>.

Initially, all the squares are white.
Snuke will perform the following operation some number of times:

Select <var>K</var> consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares are overwritten.

After Snuke finishes performing the operation, the score will be calculated as the sum of the integers contained in the black squares.
Find the maximum possible score.

Constraints

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

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

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

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

Input

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

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

Output

Print the maximum possible score.

Sample Input 1

5 3
-10 10 -10 10 -10

Sample Output 1

10

Paint the following squares black: the second, third and fourth squares from the left.

Sample Input 2

4 2
10 -10 -10 10

Sample Output 2

20

One possible way to obtain the maximum score is as follows:

Paint the following squares black: the first and second squares from the left.

Paint the following squares black: the third and fourth squares from the left.

Paint the following squares white: the second and third squares from the left.

Sample Input 3

1 1
-10

Sample Output 3

0

Sample Input 4

10 5
5 -4 -5 -8 -4 7 2 -4 0 7

Sample Output 4

17

int solution(void) {
  int n;
  int k;
  scanf("%d%d", &n, &k);
  int a[n];
  long long ans = 0;
  long long plus[n + 1];
  long long all = 0;
  long long sum = 0;
  long long tmp;
  plus[0] = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    if (a[i] > 0) {
      all += a[i];
      plus[i + 1] = plus[i] + a[i];
    } else {
      plus[i + 1] = plus[i];
    }
    if (i < k) {
      sum += a[i];
    }
  }
  for (int i = 0; i <= n - k; i++) {
    if (sum > 0) {
      tmp = all + plus[i] - plus[i + k] + sum;
    } else {
      tmp = all + plus[i] - plus[i + k];
    }
    if (ans < tmp) {
      ans = tmp;
    }
    sum = sum - a[i] + a[i + k];
  }
  printf("%lld\n", ans);
  return 0;
}

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

    let opt = a.iter().filter(|&&x| x > 0).sum::<i64>();
    let w_sum = a[..K].iter().filter(|&&x| x < 0).sum::<i64>();
    let b_sum = a[..K].iter().filter(|&&x| x > 0).sum::<i64>();
    let (ans, _, _) = (K..N).fold(
        (std::cmp::max(opt + w_sum, opt - b_sum), w_sum, b_sum),
        |(res, w_sum, b_sum), i| {
            let w_sum_next = w_sum + std::cmp::min(0, a[i]) - std::cmp::min(0, a[i - K]);
            let b_sum_next = b_sum + std::cmp::max(0, a[i]) - std::cmp::max(0, a[i - K]);
            (
                *[res, opt + w_sum_next, opt - b_sum_next]
                    .iter()
                    .max()
                    .unwrap(),
                w_sum_next,
                b_sum_next,
            )
        },
    );

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


Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...$$$n$$$ friends live in a city which can be represented as a number line. The $$$i$$$-th friend lives in a house with an integer coordinate $$$x_i$$$. The $$$i$$$-th friend can come celebrate the New Year to the house with coordinate $$$x_i-1$$$, $$$x_i+1$$$ or stay at $$$x_i$$$. Each friend is allowed to move no more than once.For all friends $$$1 \le x_i \le n$$$ holds, however, they can come to houses with coordinates $$$0$$$ and $$$n+1$$$ (if their houses are at $$$1$$$ or $$$n$$$, respectively).For example, let the initial positions be $$$x = [1, 2, 4, 4]$$$. The final ones then can be $$$[1, 3, 3, 4]$$$, $$$[0, 2, 3, 3]$$$, $$$[2, 2, 5, 5]$$$, $$$[2, 1, 3, 5]$$$ and so on. The number of occupied houses is the number of distinct positions among the final ones.So all friends choose the moves they want to perform. After that the number of occupied houses is calculated. What is the minimum and the maximum number of occupied houses can there be?

fn solution() {
    let is_print = false;
    let mut input_str = String::new();

    let mut friend_count = 0_usize;
    match io::stdin().read_line(&mut input_str) {
        Ok(_n) => {
            if input_str.as_str() == "" {
                panic!("friend count number");
            }

            friend_count = input_str.trim().parse::<usize>().unwrap();
        }
        Err(error) => panic!("error: {}", error),
    }

    input_str = String::new();

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

    let max_vec_len = friend_count + 2;
    if is_print {
        println!("max count for friends {}", max_vec_len);
    }
    let mut has_person_local: Vec<i32> = vec![0; max_vec_len];
    match io::stdin().read_line(&mut input_str) {
        Ok(_n) => {
            if input_str.as_str() == "" {
                panic!("friend ");
            }

            let voter_str_vec: Vec<&str> = input_str.split(' ').collect();
            let mut index = 0_usize;
            for location in voter_str_vec {
                index = location.trim().parse::<usize>().unwrap();
                has_person_local[index] += 1;
            }
        }
        Err(error) => panic!("error: {}", error),
    }

    for index in 0..max_vec_len {
        let mut item: (i32, i32, i32) = (0, 0, 0);

        let mut perNum: i32 = 0;
        perNum += has_person_local[index];
        item.2 += has_person_local[index];

        if index > 0 {
            perNum += has_person_local[index - 1];
        }

        if index < (max_vec_len - 1) {
            perNum += has_person_local[index + 1];
        }
        item.0 = perNum;
        localtion_vec.push(item);
    }

    for index in 0..max_vec_len {
        let item = localtion_vec.get(index).unwrap();

        let mut valueNum = 0;
        valueNum += item.0;

        if index > 0 {
            let next_item = localtion_vec.get(index - 1).unwrap();
            valueNum += next_item.0;
        }

        if index < (max_vec_len - 1) {
            let pre_item = localtion_vec.get(index + 1).unwrap();
            valueNum += pre_item.0;
        }

        let item_mut = localtion_vec.get_mut(index).unwrap();
        item_mut.1 = valueNum;
    }

    let mut index = 0_usize;
    let mut min_house_num = 0;
    while index < max_vec_len {
        if is_print {
            println!("process the index {}", index);
        }
        if has_person_local[index] == 0 {
            index += 1;
            continue;
        }

        let mut max_value_index = index;

        let mut maxPer = 0;
        let mut minValue = 1000000000;

        for i in 0..2 {
            max_value_index = index + i;

            if index + i >= max_vec_len {
                break;
            }

            let item = localtion_vec.get(index + i).unwrap();

            if item.0 > maxPer {
                max_value_index = index + i;
                maxPer = item.0;
                minValue = item.1;
            } else if item.0 == maxPer && item.1 < minValue {
                max_value_index = index + i;
                maxPer = item.0;
                minValue = item.1;
            }
        }

        min_house_num += 1;
        if is_print {
            println!("use house index {}", max_value_index);
        }

        index = max_value_index + 2;
    }

    let mut max_house_num = 0;
    let mut min_person_local = has_person_local.clone();
    if is_print {
        println!("before min vec {:?}", has_person_local);
    }

    for min_index in 0..max_vec_len {
        if min_person_local[min_index] == 0 {
            if min_index < (max_vec_len - 1) && min_person_local[min_index + 1] > 0 {
                min_person_local[min_index + 1] -= 1;
                min_person_local[min_index] += 1;
                max_house_num += 1;
                continue;
            }
        } else if min_person_local[min_index] > 1 {
            if has_person_local[min_index] > 0 {
                let mut temp_num = has_person_local[min_index] - 1;
                if has_person_local[min_index] < min_person_local[min_index] {
                    temp_num = has_person_local[min_index];
                }

                if has_person_local[min_index] > min_person_local[min_index] {
                    temp_num = min_person_local[min_index] - 1;
                }

                min_person_local[min_index] -= temp_num;
                min_person_local[min_index + 1] += temp_num;
            }

            max_house_num += 1;
        } else {
            max_house_num += 1;
        }
    }

    if is_print {
        println!("after min vec {:?}", min_person_local);
    }
    println!("{} {}", min_house_num, max_house_num);
}


The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.

int solution() {
  int n = 0;
  scanf("%d", &n);
  int a[n + 1];
  int b[n + 1];
  for (int i = 0; i < n; i++) {
    a[i] = 0;
    b[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &b[i]);
  }
  int north = 0;
  int south = 0;
  double time;
  if (a[0] > a[1]) {
    north = 0;
    south = 1;
    time = (double)(a[north] - a[south]) / (b[north] + b[south]);
  } else {
    north = 1;
    south = 0;
    time = (double)(a[north] - a[south]) / (b[north] + b[south]);
  }
  for (int i = 2; i < n; i++) {
    if (a[i] > a[north]) {
      if ((double)(a[i] - a[south]) / (b[i] + b[south]) > time) {
        time = (double)(a[i] - a[south]) / (b[i] + b[south]);
        if ((double)(a[i] - a[north]) / (b[north] + b[i]) > time) {
          south = north;
          north = i;
          time = (double)(a[i] - a[south]) / (b[south] + b[i]);
          continue;
        }
        north = i;
      }
    } else if (a[i] < a[south]) {
      if ((double)(a[north] - a[i]) / (b[north] + b[i]) > time) {
        time = (double)(a[north] - a[i]) / (b[north] + b[i]);
        if ((double)(a[south] - a[i]) / (b[south] + b[i]) > time) {
          north = south;
          south = i;
          time = (double)(a[north] - a[i]) / (b[north] + b[i]);
          continue;
        }
        south = i;
      }
    } else {
      if ((double)(a[i] - a[south]) / (b[i] + b[south]) > time) {
        time = (double)(a[i] - a[south]) / (b[i] + b[south]);
        if ((double)(a[north] - a[i]) / (b[north] + b[i]) > time) {
          south = i;
          time = (double)(a[north] - a[i]) / (b[north] + b[i]);
          continue;
        }
        north = i;
      } else if ((double)(a[north] - a[i]) / (b[north] + b[i]) > time) {
        south = i;
        time = (double)(a[north] - a[i]) / (b[north] + b[i]);
      }
    }
  }

  printf("%f", time);
  return 0;
}

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

    let mut input = io::stdin();
    let reader = BufReader::new(&mut input);

    let mut line = reader.lines().map(|a| a.expect(""));

    let a: Vec<f64> = line
        .next()
        .unwrap()
        .trim()
        .split(' ')
        .map(|x| x.parse::<f64>().unwrap())
        .collect();
    let v: Vec<f64> = line
        .next()
        .unwrap()
        .trim()
        .split(' ')
        .map(|x| x.parse::<f64>().unwrap())
        .collect();

    let (mut l, mut r) = (0_f64, 1e9_f64);
    for _ in 0..100 {
        let m = (l + r) / 2.0;
        let pl = l;
        let (mut ll, mut rr) = (-1e-233_f64, 1e233_f64);
        for i in 0..n {
            let l = a[i] - v[i] * m;
            let r = a[i] + v[i] * m;
            ll = ll.max(l);
            rr = rr.min(r);
        }
        if ll <= rr {
            r = m;
        } else {
            l = m;
            if (l - pl).abs() < 1e-6 {
                break;
            }
        }
    }
    println!("{:.10}", l);
}


The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.

fn solution() {
    let mut input = stdin();
    let _output = stdout();
    let mut buffer = [0; 4 * 2 * 100 + 100];
    let mut boys_girls = [0; 202];
    let len = input.read(&mut buffer).unwrap();

    let mut mi = 0;
    let mut pos = 0;
    let mut skip = true;
    let (mut n_s, mut n_e) = (0, 0);
    let mut num = 0;
    let (mut boys_len, mut girls_len) = (0, 0);
    for b in 0..len {
        match buffer[b] {
            b'\r' => (),
            b'\n' if skip => {
                skip = false;
                n_s = b + 1;
                n_e = n_s;
            }
            b'\n' if !skip => {
                for i in n_s..n_e {
                    num *= 10;
                    num += buffer[i] - b'0';
                }
                boys_girls[mi + pos] = num;
                if boys_len == 0 {
                    boys_len = pos + 1;
                } else {
                    girls_len = pos + 1;
                }
                pos = 0;
                num = 0;
                skip = true;
                mi = 100;
                n_s = b + 1;
                n_e = n_s;
            }
            _ if skip => (),
            b' ' => {
                for i in n_s..n_e {
                    num *= 10;
                    num += buffer[i] - b'0';
                }
                boys_girls[mi + pos] = num;
                pos += 1;
                num = 0;
                n_s = b + 1;
                n_e = n_s;
            }
            _ => n_e += 1,
        }
    }
    boys_girls[..boys_len].sort();
    boys_girls[100..100 + girls_len].sort();

    let mut gi = 0;
    let mut bi = 0;
    let mut res = 0;
    loop {
        if gi >= girls_len || bi >= boys_len {
            break;
        }
        if boys_girls[100 + gi] <= boys_girls[bi] {
            if boys_girls[bi] - boys_girls[100 + gi] <= 1 {
                res += 1;
                bi += 1;
            }
            gi += 1;
        } else {
            if boys_girls[100 + gi] - boys_girls[bi] <= 1 {
                res += 1;
                gi += 1;
            }
            bi += 1;
        }
    }
    println!("{}", res);
}


You are given a text consisting of n lines. Each line contains some space-separated words, consisting of lowercase English letters.We define a syllable as a string that contains exactly one vowel and any arbitrary number (possibly none) of consonants. In English alphabet following letters are considered to be vowels: 'a', 'e', 'i', 'o', 'u' and 'y'.Each word of the text that contains at least one vowel can be divided into syllables. Each character should be a part of exactly one syllable. For example, the word "mamma" can be divided into syllables as "ma" and "mma", "mam" and "ma", and "mamm" and "a". Words that consist of only consonants should be ignored.The verse patterns for the given text is a sequence of n integers p1, p2, ..., pn. Text matches the given verse pattern if for each i from 1 to n one can divide words of the i-th line in syllables in such a way that the total number of syllables is equal to pi.You are given the text and the verse pattern. Check, if the given text matches the given verse pattern.

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let tokens: Vec<&str> = line.split_whitespace().collect();
    let n = tokens[0].parse().unwrap();

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

    let mut v: Vec<i32> = vec![0; n];
    for i in 0..n {
        v[i] = tokens[i].parse().unwrap();
    }

    let mut yes: bool = true;
    for i in 0..n {
        let mut line = String::new();
        let mut cnt: i32 = 0;
        io::stdin().read_line(&mut line).unwrap();
        for c in line.chars() {
            if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y' {
                cnt += 1;
            }
        }
        if cnt != v[i] {
            yes = false;
            break;
        }
    }

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


Mainak has an array $$$a_1, a_2, \ldots, a_n$$$ of $$$n$$$ positive integers. He will do the following operation to this array exactly once:  Pick a subsegment of this array and cyclically rotate it by any amount.  Formally, he can do the following exactly once:  Pick two integers $$$l$$$ and $$$r$$$, such that $$$1 \le l \le r \le n$$$, and any positive integer $$$k$$$.  Repeat this $$$k$$$ times: set $$$a_l=a_{l+1}, a_{l+1}=a_{l+2}, \ldots, a_{r-1}=a_r, a_r=a_l$$$ (all changes happen at the same time). Mainak wants to maximize the value of $$$(a_n - a_1)$$$ after exactly one such operation. Determine the maximum value of $$$(a_n - a_1)$$$ that he can obtain.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int A[n];
    int ans = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", A + i);
    }
    for (int i = 0; i < n; i++) {
      int k = A[i] - A[(i + 1) % n];
      int k0 = A[i] - A[0];
      int kn = A[n - 1] - A[i];
      ans = k > ans ? k : ans;
      ans = k0 > ans ? k0 : ans;
      ans = kn > ans ? kn : ans;
    }

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

fn solution() {
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line).unwrap();
    let t: i32 = input_line.trim().parse().unwrap();
    for _ in 0..t {
        input_line.clear();
        io::stdin().read_line(&mut input_line).unwrap();
        input_line.clear();
        std::io::stdin().read_line(&mut input_line).unwrap();
        let a: Vec<i32> = input_line
            .split_whitespace()
            .map(|s| s.parse().unwrap())
            .collect();
        let (f, l, mut p, mut max_diff) = (a[0], a[a.len() - 1], a[0], 0);
        for ai in a[1..].iter() {
            max_diff = if (ai - f) > max_diff {
                ai - f
            } else {
                max_diff
            };
            max_diff = if (l - ai) > max_diff {
                l - ai
            } else {
                max_diff
            };
            max_diff = if (p - ai) > max_diff {
                p - ai
            } else {
                max_diff
            };
            p = *ai;
        }
        println!("{}", max_diff);
    }
}


During a daily walk Alina noticed a long number written on the ground. Now Alina wants to find some positive number of same length without leading zeroes, such that the sum of these two numbers is a palindrome. Recall that a number is called a palindrome, if it reads the same right to left and left to right. For example, numbers $$$121, 66, 98989$$$ are palindromes, and $$$103, 239, 1241$$$ are not palindromes.Alina understands that a valid number always exist. Help her find one!

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

    stdin().read_to_string(&mut buffer).unwrap();
    let input_params: Vec<&str> = buffer.split_whitespace().collect();
    let mut param_iter = input_params.iter();
    let t = param_iter.next().unwrap().parse::<u32>().unwrap();
    for _i in 0..t {
        let n = param_iter.next().unwrap().parse::<usize>().unwrap();
        let num = *param_iter.next().unwrap();
        let num_bytes = num.as_bytes();
        let mut result1: Vec<u8> = Vec::new();
        let mut result9: Vec<u8> = Vec::new();
        let mut carry = 1;
        for i in 1..=n {
            let mut result_digit = b'9' - num_bytes.get((n - i)).unwrap() + carry + 1;
            carry = 0;
            while result_digit >= 10 {
                result_digit -= 10;
                carry += 1;
            }
            result1.insert(0, b'0' + result_digit);
        }

        for byte in num_bytes {
            let result_digit = b'9' - byte;
            result9.push(b'0' + result_digit);
        }

        if carry > 0 {
            result1.insert(0, b'0' + carry);
        }

        if result1.len() == n {
            println!(
                "{}",
                std::str::from_utf8(&result1)
                    .unwrap()
                    .trim_start_matches('0')
            );
        } else {
            println!(
                "{}",
                std::str::from_utf8(&result9)
                    .unwrap()
                    .trim_start_matches('0')
            );
        }
    }
}


幹線道路 (Trunk Road)

問題文

JOI 市は，東西方向にまっすぐに伸びる <var>H</var> 本の道路と，南北方向にまっすぐに伸びる <var>W</var> 本の道路によって，碁盤の目の形に区分けされている．道路と道路の間隔は <var>1</var> である．JOI 市では，これら <var>H+W</var> 本の道路から，東西方向に <var>1</var> 本，南北方向に <var>1</var> 本，合計 <var>2</var> 本の道路を幹線道路として選ぶことになった．

北から <var>i</var> 本目 (<var>1≦i≦H</var>) の道路と，西から <var>j</var> 本目 (<var>1≦j≦W</var>) の道路の交差点を，交差点 <var>(i,j)</var> とする．交差点 <var>(i,j)</var> と北から <var>m</var> 本目 (<var>1≦m≦H</var>) の道路の距離は <var>|i-m|</var> であり，交差点 <var>(i,j)</var> と西から <var>n</var> 本目 (<var>1≦n≦W</var>) の道路の距離は <var>|j-n|</var> である．
また，交差点 <var>(i,j)</var> の近くには <var>A_{i,j}</var> 人の住人が住んでいる．

<var>2</var> 本の幹線道路を選んだときの，JOI 市の全ての住人に対する，最寄りの交差点から近い方の幹線道路への距離の総和の最小値を求めよ．

制約

<var>2 ≦ H ≦ 25</var>

<var>2 ≦ W ≦ 25</var>

<var>0 ≦ A_{i,j} ≦ 100</var> (<var>1 ≦ i ≦ H</var>, <var>1 ≦ j ≦ W</var>)

入力・出力

入力

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

<var>H</var> <var>W</var>

<var>A_{1,1}</var> <var>A_{1,2}</var> ... <var>A_{1,W}</var>

:

<var>A_{H,1}</var> <var>A_{H,2}</var> ... <var>A_{H,W}</var>

出力

JOI 市の全ての住人に対する，最寄りの交差点から近い方の幹線道路への距離の総和の最小値を出力せよ．

入出力例

入力例 1

3 5
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

出力例 1

8

例えば，北から <var>2</var> 本目の道路と西から <var>1</var> 本目の道路を幹線道路とすればよい．

入力例 2

5 5
1 2 3 1 5
1 22 11 44 3
1 33 41 53 2
4 92 35 23 1
4 2 6 3 5

出力例 2

164

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

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

    let h: usize = iter.next().unwrap().parse().unwrap();
    let w: usize = iter.next().unwrap().parse().unwrap();
    let a: Vec<Vec<usize>> = (0..h)
        .map(|_| iter.by_ref().take(w).map(|s| s.parse().unwrap()).collect())
        .collect();

    println!(
        "{}",
        (0..h)
            .map::<usize, _>(|ri| {
                (0..w)
                    .map(|rj| {
                        (0..h)
                            .map::<usize, _>(|i| {
                                let di = ri.abs_diff(i);
                                (0..w)
                                    .map(|j| {
                                        let dj = rj.abs_diff(j);
                                        let d = min(di, dj);
                                        a[i][j] * d
                                    })
                                    .sum()
                            })
                            .sum()
                    })
                    .min()
                    .unwrap()
            })
            .min()
            .unwrap()
    );
}


Score: <var>100</var> points

Problem Statement

Takahashi is solving quizzes. He has easily solved all but the last one.

The last quiz has three choices: <var>1</var>, <var>2</var>, and <var>3</var>.

With his supernatural power, Takahashi has found out that the choices <var>A</var> and <var>B</var> are both wrong.

Print the correct choice for this problem.

Constraints

Each of the numbers <var>A</var> and <var>B</var> is <var>1</var>, <var>2</var>, or <var>3</var>.

<var>A</var> and <var>B</var> are different.

Input

Input is given from Standard Input in the following format:

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

Output

Print the correct choice.

Sample Input 1

3
1

Sample Output 1

2

When we know <var>3</var> and <var>1</var> are both wrong, the correct choice is <var>2</var>.

Sample Input 2

1
2

Sample Output 2

3

int solution(void) {

  int A = 0;
  int B = 0;

  scanf("%d", &A);
  scanf("%d", &B);

  if (A != 1 && B != 1) {
    printf("1\n");
  } else if (A != 2 && B != 2) {
    printf("2\n");
  } else {
    printf("3\n");
  }

  return 0;
}

fn solution() {
    let mut input = String::new();
    let _ = io::stdin().read_to_string(&mut input);
    let lines: Vec<&str> = input.split("\n").collect();
    let a = lines[0].parse::<i32>().unwrap();
    let b = lines[1].parse::<i32>().unwrap();

    println!("{}", 6 - a - b);
}


Score : <var>100</var> points

Problem Statement

There are two buttons, one of size <var>A</var> and one of size <var>B</var>.

When you press a button of size <var>X</var>, you get <var>X</var> coins and the size of that button decreases by <var>1</var>.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

<var>3 \leq A, B \leq 20</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get <var>5 + 4 = 9</var> coins by pressing the button of size <var>5</var> twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12

int solution() {
  int a = 0;
  int b = 0;
  scanf("%d %d", &a, &b);
  if (a == b) {
    printf("%d\n", a * 2);
  } else if (a > b) {
    printf("%d\n", (a * 2) - 1);
  } else {
    printf("%d\n", (b * 2) - 1);
  }
  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let mut buf = String::new();
    let _ = stdin.read_line(&mut buf);
    let ns = buf
        .split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect::<Vec<isize>>();
    let (a, b) = (ns[0], ns[1]);
    if a < b {
        println!("{}", b * 2 - 1);
    } else if b < a {
        println!("{}", a * 2 - 1);
    } else {
        println!("{}", a * 2);
    }
}


Score : <var>100</var> points

Problem Statement

In order to pass the entrance examination tomorrow, Taro has to study for <var>T</var> more hours.

Fortunately, he can leap to World B where time passes <var>X</var> times as fast as it does in our world (World A).

While <var>(X \times t)</var> hours pass in World B, <var>t</var> hours pass in World A.

How many hours will pass in World A while Taro studies for <var>T</var> hours in World B?

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>T</var> <var>X</var>

Output

Print the number of hours that will pass in World A.

The output will be regarded as correct when its absolute or relative error from the judge's output is at most <var>10^{-3}</var>.

Sample Input 1

8 3

Sample Output 1

2.6666666667

While Taro studies for eight hours in World B where time passes three times as fast, <var>2.6666...</var> hours will pass in World A.

Note that an absolute or relative error of at most <var>10^{-3}</var> is allowed.

Sample Input 2

99 1

Sample Output 2

99.0000000000

Sample Input 3

1 100

Sample Output 3

0.0100000000

int solution(void) {
  float t = 0;
  float x = 0;
  scanf("%f %f", &t, &x);
  printf("%f\n", t / x);
  return 0;
}

fn solution() {
    let mut tx = String::new();
    stdin().read_line(&mut tx).unwrap();
    let tx: Vec<isize> = tx.split_whitespace().flat_map(str::parse).collect();
    let t = tx[0] * 10000;
    let x = tx[1];
    println!("{}.{:>04}", t / x / 10000, (t / x) % 10000);
}


The round carousel consists of $$$n$$$ figures of animals. Figures are numbered from $$$1$$$ to $$$n$$$ in order of the carousel moving. Thus, after the $$$n$$$-th figure the figure with the number $$$1$$$ follows. Each figure has its own type — the type of the animal corresponding to this figure (the horse, the tiger and so on). The type of animal of the $$$i$$$-th figure equals $$$t_i$$$.    The example of the carousel for $$$n=9$$$ and $$$t=[5, 5, 1, 15, 1, 5, 5, 1, 1]$$$. You want to color each figure in one of the colors. You think that it's boring if the carousel contains two different figures (with the distinct types of animals) going one right after another and colored in the same color.Your task is to color the figures in such a way that the number of distinct colors used is the minimum possible and there are no figures of the different types going one right after another and colored in the same color. If you use exactly $$$k$$$ distinct colors, then the colors of figures should be denoted with integers from $$$1$$$ to $$$k$$$.

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

    for _ in 0..q {
        let mut line = String::new();
        lock.read_line(&mut line).unwrap();

        let mut line = String::new();
        lock.read_line(&mut line).unwrap();
        let t: Vec<usize> = line
            .split_whitespace()
            .map(|x| x.parse().unwrap())
            .collect();

        let mut all_same = true;
        for i in 1..t.len() {
            if t[i] != t[i - 1] {
                all_same = false;
                break;
            }
        }

        if all_same {
            println!("{}", 1);

            for _ in 0..t.len() {
                print!("{} ", 1);
            }

            println!();
            continue;
        }

        let mut dp = Vec::with_capacity(t.len());
        dp.push((true, false));

        for i in 1..t.len() {
            if t[i] == t[i - 1] {
                dp.push((true, true));
            } else {
                dp.push((dp[i - 1].1, dp[i - 1].0));
            }
        }

        let mut sol = vec![0; t.len()];
        if dp.last().unwrap().1 {
            *sol.last_mut().unwrap() = 2;
        } else {
            *sol.last_mut().unwrap() = 1;
        }

        for i in (0..sol.len() - 1).rev() {
            if sol[i + 1] == 1 {
                sol[i] = if dp[i].1 { 2 } else { 1 };
            } else {
                sol[i] = if dp[i].0 { 1 } else { 2 };
            }
        }

        if *sol.last().unwrap() == 1 && t.last().unwrap() != t.first().unwrap() {
            *sol.last_mut().unwrap() = 3;
        }

        println!("{}", if *sol.last().unwrap() == 3 { 3 } else { 2 });

        for i in sol {
            print!("{} ", i);
        }

        println!();
    }
}


You are given an array $$$a_1, a_2, \dots, a_n$$$, consisting of $$$n$$$ positive integers. Initially you are standing at index $$$1$$$ and have a score equal to $$$a_1$$$. You can perform two kinds of moves:   move right — go from your current index $$$x$$$ to $$$x+1$$$ and add $$$a_{x+1}$$$ to your score. This move can only be performed if $$$x<n$$$.  move left — go from your current index $$$x$$$ to $$$x-1$$$ and add $$$a_{x-1}$$$ to your score. This move can only be performed if $$$x>1$$$. Also, you can't perform two or more moves to the left in a row. You want to perform exactly $$$k$$$ moves. Also, there should be no more than $$$z$$$ moves to the left among them.What is the maximum score you can achieve?

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

    for _ in 0..t {
        let (n, k, z): (usize, usize, usize) = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

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

        let mut ans = 0;
        for i in 0..=z {
            if k < 2 * i {
                break;
            }
            let sum = { a[0..=(k - 2 * i)].iter().sum::<usize>() };
            let max = {
                (0..=std::cmp::min(n - 2, k - 2 * i))
                    .map(|j| a[j] + a[j + 1])
                    .max()
                    .unwrap()
            };
            ans = std::cmp::max(ans, sum + max * i);
        }
        println!("{}", ans);
    }
}


This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

int solution() {
  long int q;
  long int n;
  long int i;
  long int j;
  long int k;
  long int l;
  long int f;
  long int c;
  scanf("%ld", &q);
  for (i = 0; i < q; i++) {
    f = 0;
    c = 0;
    k = 0;
    scanf("%ld", &n);
    long int ar[n];
    long int br[n];
    long int cr[n];
    for (j = 0; j < n; j++) {
      br[j] = 0;
      scanf("%ld", &ar[j]);
    }
    for (j = 0; j < n; j++) {
      br[ar[j] - 1]++;
    }
    for (j = 0; j < n; j++) {

      f = 0;
      if (br[j] != 0) {
        while (br[j] != 0) {
          f = 0;
          for (l = 0; l < k; l++) {
            if (cr[l] == br[j]) {
              f = 1;
              break;
            }
          }
          if (f == 0) {
            break;
          }
          br[j]--;
        }
        if (br[j] != 0) {
          cr[k++] = br[j];
          c += br[j];
        }
      }
    }
    printf("%ld\n", c);
  }
}

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

    for _ in 1..q + 1 {
        stdin.read_line(&mut input)?;

        let mut input = String::new();
        stdin.read_line(&mut input)?;
        let candies = input
            .split_whitespace()
            .map(|x| x.trim().parse::<u32>().unwrap());

        let mut map = HashMap::new();
        for candie in candies {
            if let std::collections::hash_map::Entry::Vacant(e) = map.entry(candie) {
                e.insert(1);
            } else {
                let x = map.get_mut(&candie).unwrap();
                *x += 1;
            }
        }

        let mut counts: Vec<_> = map.iter().collect();
        counts.sort_by(|x, y| y.1.cmp(x.1));

        let mut size = 0;
        let mut last_count = std::u32::MAX;

        for (_, &count) in counts {
            let i = min(last_count - 1, count);

            size += i;
            last_count = i;
            if last_count == 0 {
                break;
            }
        }

        println!("{:?}", size);
    }

    Ok(())
}


Score : <var>100</var> points

Problem Statement

You are given a trapezoid. The lengths of its upper base, lower base, and height are <var>a</var>, <var>b</var>, and <var>h</var>, respectively.

An example of a trapezoid

Find the area of this trapezoid.

Constraints

<var>1≦a≦100</var>

<var>1≦b≦100</var>

<var>1≦h≦100</var>

All input values are integers.

<var>h</var> is even.

Input

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

<var>a</var>
<var>b</var>
<var>h</var>

Output

Print the area of the given trapezoid. It is guaranteed that the area is an integer.

Sample Input 1

3
4
2

Sample Output 1

7

When the lengths of the upper base, lower base, and height are <var>3</var>, <var>4</var>, and <var>2</var>, respectively, the area of the trapezoid is <var>(3+4)×2/2 = 7</var>.

Sample Input 2

4
4
4

Sample Output 2

16

In this case, a parallelogram is given, which is also a trapezoid.

int solution(void) {
  int a = 0;
  int h = 0;
  int b = 0;
  scanf("%d", &a);
  scanf("%d", &b);
  scanf("%d", &h);
  printf("%d\n", (a + b) * h / 2);

  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let a: i64 = s.trim().parse().unwrap();
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let b: i64 = s.trim().parse().unwrap();
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let h: i64 = s.trim().parse().unwrap();

    println!("{}", (a + b) * h / 2);
}


Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \times n$$$. Alice has a single piece left — a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself — he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.

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

    let arr: Vec<_> = buffer
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .collect();
    let _n = arr[0];
    let (ax, ay) = (arr[1], arr[2]);
    let (bx, by) = (arr[3], arr[4]);
    let (cx, cy) = (arr[5], arr[6]);
    let (dcx, dcy) = (cx - ax, cy - ay);
    let (dbx, dby) = (bx - ax, by - ay);
    let x_sign_same = (dcx > 0 && dbx > 0) || (dcx < 0 && dbx < 0);
    let y_sign_same = (dcy > 0 && dby > 0) || (dcy < 0 && dby < 0);
    if x_sign_same && y_sign_same {
        println!("YES");
    } else {
        println!("NO");
    }
}


There is a grid with $$$n$$$ rows and $$$m$$$ columns, and three types of cells:   An empty cell, denoted with '.'.  A stone, denoted with '*'.  An obstacle, denoted with the lowercase Latin letter 'o'. All stones fall down until they meet the floor (the bottom row), an obstacle, or other stone which is already immovable. (In other words, all the stones just fall down as long as they can fall.)Simulate the process. What does the resulting grid look like?

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    int m;
    scanf("%d %d", &n, &m);
    char grid[n + 2][m + 3];
    for (int j = 0; j < n; j++) {
      char newlinechar;
      scanf("%1c", &newlinechar);
      for (int k = 0; k < m; k++) {
        scanf("%1c", &grid[j][k]);
      }
    }
    for (int k = 0; k < m; k++) {
      for (int j = n - 1; j >= 0; j--) {
        if (grid[j][k] == '*') {
          int height = j;
          grid[j][k] = '.';
          while (grid[height][k] != '*' && grid[height][k] != 'o' &&
                 height < n) {
            height++;
          }
          grid[--height][k] = '*';
        }
      }
    }
    for (int j = 0; j < n; j++) {
      for (int k = 0; k < m; k++) {
        printf("%c", grid[j][k]);
      }
      printf("\n");
    }
    printf("\n");
  }
  return 0;
}

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

    stdin().read_line(&mut line).unwrap();
    let t = line.trim().parse::<i32>().unwrap();

    for _tx in 0..t {
        line.clear();
        stdin().read_line(&mut line).unwrap();
        let mut nm = line.trim().split(" ").filter(|x| !x.is_empty());

        let n = nm.next().unwrap().parse::<usize>().unwrap();
        let m = nm.next().unwrap().parse::<usize>().unwrap();

        let mut g: Vec<Vec<char>> = Vec::new();

        for _nx in 0..n {
            line.clear();
            stdin().read_line(&mut line).unwrap();
            g.push(line.trim().chars().collect());
        }

        for j in 0..m {
            let mut b = 0;
            let mut c = 0;
            for i in 0..(n + 1) {
                if i == n || g[i][j] == 'o' {
                    for i1 in b..(i - c) {
                        g[i1][j] = '.';
                    }
                    for i1 in (i - c)..i {
                        g[i1][j] = '*';
                    }
                    b = i + 1;
                    c = 0;
                } else if g[i][j] == '*' {
                    c += 1;
                }
            }
        }

        for r in g {
            for x in r {
                print!("{}", x);
            }
            println!();
        }
        println!();
    }
}


Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

int solution() {
  int n = 0;
  scanf("%d", &n);
  if (n <= 1) {
    printf("%d", n);
    return 0;
  }
  int a[n];
  int sum = 0;
  int mymoney = 0;
  for (int i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
    sum += a[i];
  }
  for (int c = 0; c < n - 1; c++) {
    for (int d = 0; d < n - c - 1; d++) {
      if (a[d] < a[d + 1]) {
        int swap = a[d];
        a[d] = a[d + 1];
        a[d + 1] = swap;
      }
    }
  }
  for (int i = 0; i < n; ++i) {
    if (mymoney <= sum / 2) {
      mymoney += a[i];
    } else {
      printf("%d", i);
      return 0;
    }
  }
  printf("%d", n);
  return 0;
}

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

    io::stdin().read_line(&mut input).expect("Input error");

    input.clear();
    io::stdin().read_line(&mut input).expect("Input error");

    let mut coins: Vec<i32> = input
        .trim()
        .split_ascii_whitespace()
        .map(|coin| coin.parse::<i32>().expect("Parsing error"))
        .collect();

    coins.sort();
    coins.reverse();

    let mut total: i32 = coins.iter().sum();
    let mut sum = 0;
    let mut count = 0;

    for i in coins {
        sum += i;
        total -= i;
        count += 1;
        if sum > total {
            break;
        }
    }

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


— Hey folks, how do you like this problem?— That'll do it. BThero is a powerful magician. He has got $$$n$$$ piles of candies, the $$$i$$$-th pile initially contains $$$a_i$$$ candies. BThero can cast a copy-paste spell as follows:   He chooses two piles $$$(i, j)$$$ such that $$$1 \le i, j \le n$$$ and $$$i \ne j$$$.  All candies from pile $$$i$$$ are copied into pile $$$j$$$. Formally, the operation $$$a_j := a_j + a_i$$$ is performed. BThero can cast this spell any number of times he wants to — but unfortunately, if some pile contains strictly more than $$$k$$$ candies, he loses his magic power. What is the maximum number of times BThero can cast the spell without losing his power?

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n;
    int knum;
    scanf("%d", &n);
    scanf("%d", &knum);
    int arr[n];
    int pos = 0;
    for (int j = 0; j < n; j++) {
      scanf("%d", &arr[j]);
    }
    int min = arr[0];
    for (int k = 1; k < n; k++) {
      if (min > arr[k]) {
        min = arr[k];
        pos = k;
      }
    }
    int sum = 0;
    for (int l = 0; l < n; l++) {
      if (pos != l && knum > arr[l]) {
        sum += (knum - arr[l]) / min;
      }
    }
    printf("%d\n", sum);
  }
}

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

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

    for _i in 0..t {
        let mut n_k = String::new();
        io::stdin().read_line(&mut n_k).unwrap();

        let v = n_k.trim().split(" ").collect::<Vec<&str>>();
        let _n = v[0].parse::<u32>().unwrap();
        let k = v[1].parse::<u32>().unwrap();

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

        let mut vals = vals
            .trim()
            .split(" ")
            .map(|e| e.parse::<u32>().unwrap())
            .collect::<Vec<u32>>();

        vals.sort();

        let mut m = 0;
        for (i1, v1) in vals.iter().enumerate().rev() {
            let mut b = 0;
            for (i2, v2) in vals.iter().enumerate() {
                if i1 == i2 {
                    break;
                }

                let num = (k - *v1) / *v2;

                if num > b {
                    b = num;
                }
            }

            m += b;
        }

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


You are given $$$n$$$ chips on a number line. The $$$i$$$-th chip is placed at the integer coordinate $$$x_i$$$. Some chips can have equal coordinates.You can perform each of the two following types of moves any (possibly, zero) number of times on any chip:  Move the chip $$$i$$$ by $$$2$$$ to the left or $$$2$$$ to the right for free (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 2$$$ or with $$$x_i + 2$$$);  move the chip $$$i$$$ by $$$1$$$ to the left or $$$1$$$ to the right and pay one coin for this move (i.e. replace the current coordinate $$$x_i$$$ with $$$x_i - 1$$$ or with $$$x_i + 1$$$). Note that it's allowed to move chips to any integer coordinate, including negative and zero.Your task is to find the minimum total number of coins required to move all $$$n$$$ chips to the same coordinate (i.e. all $$$x_i$$$ should be equal after some sequence of moves).

fn solution() {
    let mut _buffer = String::new();
    io::stdin()
        .read_line(&mut _buffer)
        .expect("failed to read input");
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read input");
    let a = buffer
        .split_whitespace()
        .map(|x| x.parse::<u32>().unwrap())
        .collect::<Vec<u32>>();
    let even = a
        .iter()
        .fold(0, |acc, x| if x % 2 == 0 { acc + 1 } else { acc });
    let odd = a.len() - even;

    println!("{}", even.min(odd));
}


You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?

int solution() {
  int t;
  scanf("%d", &t);
  int arr[101];
  while (t--) {
    int n;
    int d;
    scanf("%d%d", &n, &d);
    int check = 1;
    int min = 101;
    int temp = -1;
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      if (arr[i] > d) {
        check = 0;
      }
      if (arr[i] < min) {
        min = arr[i];
        temp = i;
      }
    }
    if (check == 1) {
      printf("Yes\n");
    } else {
      check = 0;
      for (int i = 0; i < n; i++) {
        if (arr[i] + min <= d && i != temp) {
          check = 1;
        }
      }
      printf("%s\n", check ? "Yes" : "No");
    }
  }
  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 d: u8 = line.split_whitespace().nth(1).unwrap().parse().unwrap();
        let line = lines.next().unwrap();

        let mut v: Vec<u8> = line
            .split_whitespace()
            .map(|x| x.parse().unwrap())
            .collect();
        v.sort();

        let ans = v.last().cloned().unwrap() <= d || v[0..2].iter().cloned().sum::<u8>() <= d;

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


Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size $$$n \times n$$$ is called prime if the following three conditions are held simultaneously:   all numbers on the square are non-negative integers not exceeding $$$10^5$$$;  there are no prime numbers in the square;  sums of integers in each row and each column are prime numbers. Sasha has an integer $$$n$$$. He asks you to find any prime square of size $$$n \times n$$$. Sasha is absolutely sure such squares exist, so just help him!

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

    for _i in 0..t {
        let mut n = String::new();
        stdin().read_line(&mut n).unwrap();
        let n: u32 = n.trim().parse().unwrap();
        for height in 0..n {
            for width in 0..n {
                if !n.is_multiple_of(2)
                    && ((height == n / 2 && width == 0) || (width == n / 2 && height == 0))
                {
                    print!("1 ");
                } else if height == width || height == (n - width - 1) {
                    print!("1 ");
                } else {
                    print!("0 ");
                }
            }
            println!();
        }
    }
}


Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

 q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].

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

    let N = buf_it.next().unwrap().parse::<usize>().unwrap();
    let A = (0..N)
        .map(|_| buf_it.next().unwrap().parse::<usize>().unwrap())
        .collect::<Vec<_>>();

    let Q = buf_it.next().unwrap().parse::<usize>().unwrap();
    let M = (0..Q)
        .map(|_| buf_it.next().unwrap().parse::<usize>().unwrap())
        .collect::<Vec<_>>();

    let mut ans = HashSet::new();
    ans.insert(0);
    for &a in &A {
        let tmp = ans.iter().map(|&b| a + b).collect::<HashSet<_>>();
        ans = ans.union(&tmp).copied().collect();
    }

    for m in &M {
        println!("{}", if ans.contains(m) { "yes" } else { "no" });
    }
}


You are given an array $$$a$$$ of length $$$n$$$, which initially is a permutation of numbers from $$$1$$$ to $$$n$$$. In one operation, you can choose an index $$$i$$$ ($$$1 \leq i < n$$$) such that $$$a_i < a_{i + 1}$$$, and remove either $$$a_i$$$ or $$$a_{i + 1}$$$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $$$[1, 3, 2]$$$, you can choose $$$i = 1$$$ (since $$$a_1 = 1 < a_2 = 3$$$), then either remove $$$a_1$$$ which gives the new array $$$[3, 2]$$$, or remove $$$a_2$$$ which gives the new array $$$[1, 2]$$$.Is it possible to make the length of this array equal to $$$1$$$ with these operations?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int ns[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &ns[i]);
    }
    if (ns[0] <= ns[n - 1]) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let mut ms: Vec<usize> = vec![0; n];
        ms[n - 1] = xs[n - 1];
        for i in (0..(n - 1)).rev() {
            ms[i] = max(xs[i], ms[i + 1]);
        }
        let mut x = xs[0];
        let mut ok = true;
        for i in 1..n {
            if xs[i - 1] >= xs[i] && x >= ms[i] {
                ok = false;
                x = xs[i];
            }
        }
        println!("{}", if ok { "YES" } else { "NO" });
    }
}


You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1.Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0.You have to color the tree into the given colors using the smallest possible number of steps. On each step you can choose a vertex v and a color x, and then color all vectices in the subtree of v (including v itself) in color x. In other words, for every vertex u, such that the path from root to u passes through v, set cu = x.It is guaranteed that you have to color each vertex in a color different from 0.You can learn what a rooted tree is using the link: https://en.wikipedia.org/wiki/Tree_(graph_theory).

int solution() {

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

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

  int steps = n;

  for (i = 1; i < n; i++) {
    if (c[p[i] - 1] == c[i]) {
      steps--;
    }
  }

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

  return 0;
}

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

    let n = get!(usize);
    let mut tree = vec![vec![]; n + 1];
    for i in 2..n + 1 {
        let p = get!(usize);
        tree[p].push(i);
    }
    let mut colors = vec![0; n + 1];
    for i in 1..n + 1 {
        let c = get!();
        colors[i] = c;
    }
    let mut tmp = vec![1];
    let mut current = vec![0; n + 1];
    let mut ans = 0;
    while !tmp.is_empty() {
        let x = tmp.pop().unwrap();
        let cl = colors[x];
        if current[x] != cl {
            ans += 1;
            current[x] = cl;
        }
        for &v in &tree[x] {
            current[v] = cl;
            tmp.push(v);
        }
    }
    println!("{}", ans);
}


Score : <var>700</var> points

Problem Statement

There are <var>N</var> stones arranged in a row. The <var>i</var>-th stone from the left is painted in the color <var>C_i</var>.

Snuke will perform the following operation zero or more times:

Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.

Find the number of possible final sequences of colors of the stones, modulo <var>10^9+7</var>.

Constraints

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

<var>1 \leq C_i \leq 2\times 10^5(1\leq i\leq N)</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>C_1</var>
<var>:</var>
<var>C_N</var>

Output

Print the number of possible final sequences of colors of the stones, modulo <var>10^9+7</var>.

Sample Input 1

5
1
2
1
2
2

Sample Output 1

3

We can make three sequences of colors of stones, as follows:

<var>(1,2,1,2,2)</var>, by doing nothing.

<var>(1,1,1,2,2)</var>, by choosing the first and third stones to perform the operation.

<var>(1,2,2,2,2)</var>, by choosing the second and fourth stones to perform the operation.

Sample Input 2

6
4
2
5
4
2
4

Sample Output 2

5

Sample Input 3

7
1
3
1
2
3
3
2

Sample Output 3

5

fn solution() {
    input! {
        n: usize,
        v: [usize; n]
    }
    let d = 1000000007;
    let mut map: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for i in 0..n {
        map.entry(v[i]).or_default().push(i);
    }
    let css: Vec<Vec<usize>> = map.values().cloned().collect();
    let mut line: Vec<usize> = (0..n).collect();
    for cs in css {
        for i in 1..cs.len() {
            line[cs[i]] = cs[i - 1];
        }
    }
    let mut dp: Vec<usize> = vec![0; n];
    dp[0] = 1;
    for i in 1..n {
        dp[i] = dp[i - 1];
        if line[i] < i - 1 {
            dp[i] = (dp[i] + dp[line[i]]) % d;
        }
    }
    println!("{}", dp[n - 1]);
}


Score : <var>200</var> points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year <var>i</var> be <var>x_i</var> gram. For <var>i≥2000</var>, the following formula holds:

<var>x_{i+1} = rx_i - D</var>

You are given <var>r</var>, <var>D</var> and <var>x_{2000}</var>. Calculate <var>x_{2001}</var>, <var>...</var>, <var>x_{2010}</var> and print them in order.

Constraints

<var>2 ≤ r ≤ 5</var>

<var>1 ≤ D ≤ 100</var>

<var>D < x_{2000} ≤ 200</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>r</var> <var>D</var> <var>x_{2000}</var>

Output

Print <var>10</var> lines. The <var>i</var>-th line (<var>1 ≤ i ≤ 10</var>) should contain <var>x_{2000+i}</var> as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, <var>x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30</var> and <var>x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50</var>.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560

int solution(void) {

  int r = 0;
  int d = 0;
  int x = 0;

  scanf("%d %d %d", &r, &d, &x);

  for (int i = 1; i <= 10; i++) {
    x = r * x - d;
    printf("%d\n", x);
  }

  return 0;
}

fn solution() {
    let mut ab = String::new();
    stdin().read_line(&mut ab).unwrap();
    let ab: Vec<isize> = ab.split_whitespace().flat_map(str::parse).collect();
    let (r, d, x) = (ab[0], ab[1], ab[2]);

    let mut v = x;
    for _ in 0..10 {
        v = r * v - d;
        println!("{}", v);
    }
}


You work in the quality control department of technical support for a large company. Your job is to make sure all client issues have been resolved.Today you need to check a copy of a dialog between a client and a technical support manager. According to the rules of work, each message of the client must be followed by one or several messages, which are the answer of a support manager. However, sometimes clients ask questions so quickly that some of the manager's answers to old questions appear after the client has asked some new questions.Due to the privacy policy, the full text of messages is not available to you, only the order of messages is visible, as well as the type of each message: a customer question or a response from the technical support manager. It is guaranteed that the dialog begins with the question of the client.You have to determine, if this dialog may correspond to the rules of work described above, or the rules are certainly breached.

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

  int number_of_messages[testcases];

  int result[testcases];

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

    char array[number_of_messages[i] + 1];

    scanf("%s", array);

    result[i] = 0;

    for (int j = 0; j < number_of_messages[i]; j++) {
      if (*(array + j) == 'Q') {
        result[i]++;
      } else if (*(array + j) == 'A' && result[i] > 0) {
        result[i]--;
      }
    }
  }

  for (int i = 0; i < testcases; i++) {
    if (result[i] == 0) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }
  }

  return 0;
}

fn solution() -> io::Result<()> {
    let mut t = String::new();
    io::stdin().read_line(&mut t)?;
    let t = t.trim().parse::<i64>().unwrap();

    for _ in 0..t {
        let mut n = String::new();
        io::stdin().read_line(&mut n)?;
        let mut str = String::new();
        io::stdin().read_line(&mut str)?;

        let mut vec = Vec::new();

        for symb in str.chars() {
            if symb == 'Q' {
                vec.push(1);
            } else if symb == 'A' {
                vec.pop();
            }
        }

        if !vec.is_empty() {
            println!("No");
        } else {
            println!("Yes");
        }
    }

    Ok(())
}


Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.

int solution() {
  int h;
  int A[100005];
  int i;
  int j;
  int flag = 0;
  scanf("%d", &h);
  for (i = 0; i <= h; i++) {
    scanf("%d", &A[i]);
  }
  for (i = 0; i < h; i++) {
    if (A[i] > 1 && A[i + 1] > 1) {
      flag = 1;
    }
  }
  if (flag == 0) {
    printf("perfect\n");
  } else {
    printf("ambiguous\n");
    int prlst = 0;
    int nwlst = 0;
    for (i = 0; i <= h; i++) {
      for (j = 0; j < A[i]; j++) {
        printf("%d ", prlst);
        nwlst++;
      }
      prlst = nwlst;
    }
    prlst = 0;
    nwlst = 0;
    flag = 0;
    printf("\n");
    for (i = 0; i <= h; i++) {
      if (flag == 1) {
        flag = 2;
        for (j = 0; j < A[i]; j++) {
          if (j % 2) {
            printf("%d ", prlst);
          } else {
            printf("%d ", prlst - 1);
          }
          nwlst++;
        }
        prlst = nwlst;
      } else {
        if (A[i] > 1 && A[i + 1] > 1 && flag == 0) {
          flag = 1;
        }
        for (j = 0; j < A[i]; j++) {
          printf("%d ", prlst);
          nwlst++;
        }
        prlst = nwlst;
      }
    }
  }
  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 h = get!(usize);
    let mut tree = vec![0; h + 1];
    let mut n = 0;
    let mut flag = true;
    for i in 0..h + 1 {
        tree[i] = get!(usize);
        if i > 0 && tree[i - 1] > 1 && tree[i] > 1 {
            flag = false;
        }
        n += tree[i];
    }
    let tree = tree;
    let n = n;
    if flag {
        println!("perfect");
        return;
    }
    let mut tmp = vec![0; n + 1];
    let mut x = 0;
    let mut p = 0;
    for i in 0..h + 1 {
        for i in 1..tree[i] + 1 {
            tmp[x + i] = x;
        }
        x += tree[i];
        if p == 0 && i < h && tree[i] > 1 && tree[i + 1] > 1 {
            p = x;
        }
    }
    let p = p;
    println!("ambiguous");
    for i in 1..n + 1 {
        if i > 1 {
            print!(" ");
        }
        print!("{}", tmp[i]);
    }
    println!();
    tmp[p + 1] -= 1;
    for i in 1..n + 1 {
        if i > 1 {
            print!(" ");
        }
        print!("{}", tmp[i]);
    }
    println!();
}


Suppose you have two points $$$p = (x_p, y_p)$$$ and $$$q = (x_q, y_q)$$$. Let's denote the Manhattan distance between them as $$$d(p, q) = |x_p - x_q| + |y_p - y_q|$$$.Let's say that three points $$$p$$$, $$$q$$$, $$$r$$$ form a bad triple if $$$d(p, r) = d(p, q) + d(q, r)$$$.Let's say that an array $$$b_1, b_2, \dots, b_m$$$ is good if it is impossible to choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that the points $$$(b_i, i)$$$, $$$(b_j, j)$$$ and $$$(b_k, k)$$$ form a bad triple.You are given an array $$$a_1, a_2, \dots, a_n$$$. Calculate the number of good subarrays of $$$a$$$. A subarray of the array $$$a$$$ is the array $$$a_l, a_{l + 1}, \dots, a_r$$$ for some $$$1 \le l \le r \le n$$$.Note that, according to the definition, subarrays of length $$$1$$$ and $$$2$$$ are good.

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();

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

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

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

        let mut a = Vec::with_capacity(n);
        a.extend(it);

        let mut ans = 0;

        ans += n as u64;
        ans += n as u64 - 1;

        for l in 3..5 {
            'outer: for w in a.windows(l) {
                for i in 0..w.len() {
                    for j in i + 1..w.len() {
                        for k in j + 1..w.len() {
                            if w[i] <= w[j] && w[j] <= w[k] || w[i] >= w[j] && w[j] >= w[k] {
                                continue 'outer;
                            }
                        }
                    }
                }

                ans += 1;
            }
        }

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


Every December, VK traditionally holds an event for its employees named "Secret Santa". Here's how it happens.$$$n$$$ employees numbered from $$$1$$$ to $$$n$$$ take part in the event. Each employee $$$i$$$ is assigned a different employee $$$b_i$$$, to which employee $$$i$$$ has to make a new year gift. Each employee is assigned to exactly one other employee, and nobody is assigned to themselves (but two employees may be assigned to each other). Formally, all $$$b_i$$$ must be distinct integers between $$$1$$$ and $$$n$$$, and for any $$$i$$$, $$$b_i \ne i$$$ must hold.The assignment is usually generated randomly. This year, as an experiment, all event participants have been asked who they wish to make a gift to. Each employee $$$i$$$ has said that they wish to make a gift to employee $$$a_i$$$.Find a valid assignment $$$b$$$ that maximizes the number of fulfilled wishes of the employees.

int solution() {
  int T;
  scanf("%d", &T);
  while (T--) {
    const int mx = 2e5 + 5;
    int T;
    int n;
    int m;
    int p[mx];
    int ans[mx];
    int tong[mx];
    int q[mx];
    scanf("%d", &n);
    m = 0;
    for (int i = 1; i <= n; i++) {
      tong[i] = ans[i] = 0;
    }
    for (int i = 1; i <= n; i++) {
      scanf("%d", &p[i]);
      if (!tong[p[i]]) {
        tong[p[i]] = i;
        ans[i] = p[i];
      } else {
        q[++m] = i;
      }
    }
    int k = 1;
    for (int i = 1; i <= n; i++) {
      if (!tong[i]) {
        ans[q[k++]] = i;
      }
    }
    for (int i = 1; i <= n; i++) {
      if (ans[i] == i) {
        int a = ans[i];
        int b = ans[tong[p[i]]];
        a = b + a;
        b = a - b;
        a = a - b;
        ans[i] = a;
        ans[tong[p[i]]] = b;
      }
    }
    printf("%d\n", n - m);
    for (int i = 1; i <= n; i++) {
      printf("%d ", ans[i]);
    }
    printf("\n");
  }
  return 0;
}

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();

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

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

        let mut a = Vec::with_capacity(n);

        let s = lines.next().unwrap();
        let it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());
        a.extend(it.map(|x| x - 1));

        let mut z = vec![Vec::new(); n];

        for (i, x) in a.into_iter().enumerate() {
            z[x].push(i);
        }

        let mut e = vec![None; n];
        let mut ans = 0u64;

        for (i, l) in z.iter().enumerate() {
            if let Some(x) = l.iter().min_by_key(|&&x| z[x].len()).cloned() {
                e[x] = Some(i);
                ans += 1;
            }
        }

        let mut i = 0;

        let mut s = Vec::new();
        let mut d = Vec::new();
        let mut b = Vec::new();

        while i < n && e[i].is_none() && z[i].is_empty() {
            i += 1;
        }

        for i in 0..n {
            match (e[i].is_some(), !z[i].is_empty()) {
                (false, false) => b.push(i),
                (false, true) => s.push(i),
                (true, false) => d.push(i),
                (true, true) => (),
            }
        }

        let s = s.into_iter().chain(b.iter().cloned());
        let d = d.into_iter().chain(b.iter().cloned()).cycle().skip(1);

        for (s, d) in s.zip(d) {
            e[s] = Some(d);
        }

        writeln!(&mut output, "{}", ans).unwrap();
        for x in e {
            let x = x.unwrap() + 1;
            write!(&mut output, "{} ", x).unwrap();
        }
        writeln!(&mut output).unwrap();
    }
}


Hooray! Polycarp turned $$$n$$$ years old! The Technocup Team sincerely congratulates Polycarp!Polycarp celebrated all of his $$$n$$$ birthdays: from the $$$1$$$-th to the $$$n$$$-th. At the moment, he is wondering: how many times he turned beautiful number of years?According to Polycarp, a positive integer is beautiful if it consists of only one digit repeated one or more times. For example, the following numbers are beautiful: $$$1$$$, $$$77$$$, $$$777$$$, $$$44$$$ and $$$999999$$$. The following numbers are not beautiful: $$$12$$$, $$$11110$$$, $$$6969$$$ and $$$987654321$$$.Of course, Polycarpus uses the decimal numeral system (i.e. radix is 10).Help Polycarpus to find the number of numbers from $$$1$$$ to $$$n$$$ (inclusive) that are beautiful.

fn solution() {
    let reader = &mut io::BufReader::new(io::stdin());
    let writer = &mut io::BufWriter::new(io::stdout());
    let mut buf = String::new();

    reader.read_line(&mut buf).unwrap();
    let t = buf.trim_end().parse::<usize>().unwrap();

    for _i in 0..t {
        buf.clear();
        reader.read_line(&mut buf).unwrap();
        let n = buf.trim_end();
        let n_num = n.parse::<i32>().unwrap();
        let n_len = n.len() as i32;
        let first_digit = (n.as_bytes()[0] - 48u8) as i32;

        let mut ret = (n_len - 1) * 9 + first_digit - 1;
        if first_digit
            .to_string()
            .repeat(n_len as usize)
            .parse::<i32>()
            .unwrap()
            <= n_num
        {
            ret += 1;
        }

        writeln!(writer, "{}", ret).unwrap();
    }
}


Score : <var>200</var> points

Problem Statement

You have <var>A</var> <var>500</var>-yen coins, <var>B</var> <var>100</var>-yen coins and <var>C</var> <var>50</var>-yen coins (yen is the currency of Japan).
In how many ways can we select some of these coins so that they are <var>X</var> yen in total?

Coins of the same kind cannot be distinguished. Two ways to select coins are distinguished when, for some kind of coin, the numbers of that coin are different.

Constraints

<var>0 \leq A, B, C \leq 50</var>

<var>A + B + C \geq 1</var>

<var>50 \leq X \leq 20</var> <var>000</var>

<var>A</var>, <var>B</var> and <var>C</var> are integers.

<var>X</var> is a multiple of <var>50</var>.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of ways to select coins.

Sample Input 1

2
2
2
100

Sample Output 1

2

There are two ways to satisfy the condition:

Select zero <var>500</var>-yen coins, one <var>100</var>-yen coin and zero <var>50</var>-yen coins.

Select zero <var>500</var>-yen coins, zero <var>100</var>-yen coins and two <var>50</var>-yen coins.

Sample Input 2

5
1
0
150

Sample Output 2

0

Note that the total must be exactly <var>X</var> yen.

Sample Input 3

30
40
50
6000

Sample Output 3

213

int solution() {
  int a = 0;
  int b = 0;
  int c = 0;
  int x = 0;
  int count = 0;
  scanf("%d %d %d %d", &a, &b, &c, &x);

  for (int i = 0; i <= a; i++) {
    for (int j = 0; j <= b; j++) {
      for (int k = 0; k <= c; k++) {
        if (x == 500 * i + 100 * j + 50 * k) {
          count++;
        }
      }
    }
  }

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

  return 0;
}

fn solution() {
    let mut nums: Vec<i32> = Vec::with_capacity(4);
    for _ in 0..4 {
        let mut buf: String = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        nums.push(buf.trim().parse::<i32>().unwrap());
    }
    let x = nums[3];
    let mut a = min(x / 500, nums[0]);
    let mut cnt = 0;
    while a >= 0 {
        let mut b = min((x - a * 500) / 100, nums[1]);
        while b >= 0 {
            let c = (x - a * 500 - b * 100) / 50;
            if c > nums[2] {
                break;
            }
            cnt += 1;
            b -= 1;
        }
        a -= 1;
    }
    println!("{}", cnt);
}


Score : <var>400</var> points

Problem Statement

There is a grid with <var>N</var> rows and <var>N</var> columns of squares. Let <var>(i,j)</var> be the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left.

These squares have to be painted in one of the <var>C</var> colors from Color <var>1</var> to Color <var>C</var>. Initially, <var>(i,j)</var> is painted in Color <var>c_{i,j}</var>.

We say the grid is a good grid when the following condition is met for all <var>i,j,x,y</var> satisfying <var>1 \leq i,j,x,y \leq N</var>:

If <var>(i+j) \% 3=(x+y) \% 3</var>, the color of <var>(i,j)</var> and the color of <var>(x,y)</var> are the same.

If <var>(i+j) \%  3 \neq (x+y) \% 3</var>, the color of <var>(i,j)</var> and the color of <var>(x,y)</var> are different.

Here, <var>X \% Y</var> represents <var>X</var> modulo <var>Y</var>.

We will repaint zero or more squares so that the grid will be a good grid.

For a square, the wrongness when the color of the square is <var>X</var> before repainting and <var>Y</var> after repainting, is <var>D_{X,Y}</var>.

Find the minimum possible sum of the wrongness of all the squares.

Constraints

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

<var>3 \leq C \leq 30</var>

<var>1 \leq D_{i,j} \leq 1000 (i \neq j),D_{i,j}=0 (i=j)</var>

<var>1 \leq c_{i,j} \leq C</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>C</var>
<var>D_{1,1}</var> <var>...</var> <var>D_{1,C}</var>
<var>:</var>
<var>D_{C,1}</var> <var>...</var> <var>D_{C,C}</var>
<var>c_{1,1}</var> <var>...</var> <var>c_{1,N}</var>
<var>:</var>
<var>c_{N,1}</var> <var>...</var> <var>c_{N,N}</var>

Output

If the minimum possible sum of the wrongness of all the squares is <var>x</var>, print <var>x</var>.

Sample Input 1

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

Sample Output 1

3

Repaint <var>(1,1)</var> to Color <var>2</var>. The wrongness of <var>(1,1)</var> becomes <var>D_{1,2}=1</var>.

Repaint <var>(1,2)</var> to Color <var>3</var>. The wrongness of <var>(1,2)</var> becomes <var>D_{2,3}=1</var>.

Repaint <var>(2,2)</var> to Color <var>1</var>. The wrongness of <var>(2,2)</var> becomes <var>D_{3,1}=1</var>.

In this case, the sum of the wrongness of all the squares is <var>3</var>.

Note that <var>D_{i,j} \neq D_{j,i}</var> is possible.

Sample Input 2

4 3
0 12 71
81 0 53
14 92 0
1 1 2 1
2 1 1 2
2 2 1 3
1 1 2 2

Sample Output 2

428

fn solution() {
    input! {
        N: usize,
        C: usize,
        D: [[usize; C]; C],
        c: [[usize1; N]; N],
    }

    let mut counts = vec![vec![0; 3]; C];
    for x in 0..N {
        for y in 0..N {
            counts[c[x][y]][(x + y + 2) % 3] += 1;
        }
    }

    let mut min = std::usize::MAX;
    for c0 in 0..C {
        for c1 in 0..C {
            if c1 == c0 {
                continue;
            }
            for c2 in 0..C {
                if c2 == c1 || c2 == c0 {
                    continue;
                }
                let mut sum = 0;
                let cc = [c0, c1, c2];
                for ind in 0..3 {
                    for c3 in 0..C {
                        sum += D[c3][cc[ind]] * counts[c3][ind];
                    }
                }
                min = cmp::min(min, sum);
            }
        }
    }

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


Ezzat has an array of $$$n$$$ integers (maybe negative). He wants to split it into two non-empty subsequences $$$a$$$ and $$$b$$$, such that every element from the array belongs to exactly one subsequence, and the value of $$$f(a) + f(b)$$$ is the maximum possible value, where $$$f(x)$$$ is the average of the subsequence $$$x$$$. A sequence $$$x$$$ is a subsequence of a sequence $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) elements.The average of a subsequence is the sum of the numbers of this subsequence divided by the size of the subsequence.For example, the average of $$$[1,5,6]$$$ is $$$(1+5+6)/3 = 12/3 = 4$$$, so $$$f([1,5,6]) = 4$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int max = -1000000001;
    long long int sum = 0;
    double avg = 0.0;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      if (arr[i] > max) {
        max = arr[i];
      }
      sum += arr[i];
    }
    sum = sum - max;
    avg = (sum * 1.0) / (n - 1) + (max * 1.0);
    printf("%0.9f\n", avg);
  }

  return 0;
}

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

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

    let test_count: usize = input.trim().parse().unwrap();

    for _test in 0..test_count {
        input.clear();
        std::io::stdin().read_line(&mut input).unwrap();

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

        let mut max: f64 = f64::NEG_INFINITY;
        let mut sum: f64 = 0.0;
        let mut count: usize = 0;
        input
            .split_ascii_whitespace()
            .map(str::parse)
            .map(Result::unwrap)
            .for_each(|x| {
                if x > max {
                    max = x
                }
                sum += x;
                count += 1;
            });
        let average = (sum - max) / (count - 1) as f64;
        println!("{}", average + max);
    }
}


Score: <var>100</var> points

Problem Statement

We have two distinct integers <var>A</var> and <var>B</var>.

Print the integer <var>K</var> such that <var>|A - K| = |B - K|</var>.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

<var>0 \leq A,\ B \leq 10^9</var>

<var>A</var> and <var>B</var> are distinct.

Input

Input is given from Standard Input in the following format:

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

Output

Print the integer <var>K</var> satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

<var>|2 - 9| = 7</var> and <var>|16 - 9| = 7</var>, so <var>9</var> satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394

int solution(void) {
  long A = 0;
  long B = 0;
  long sa = 0;
  scanf("%ld %ld", &A, &B);
  sa = A + B;
  if (sa < 0) {
    sa *= -1;
  }
  if (sa % 2 != 0) {
    printf("IMPOSSIBLE\n");
    return 0;
  }
  printf("%ld\n", sa / 2);

  return 0;
}

fn solution() {
    let mut ab = String::new();
    stdin().read_line(&mut ab).unwrap();
    let mut ab: Vec<isize> = ab.split_whitespace().flat_map(str::parse).collect();
    ab.sort();
    let (a, b) = (ab[0], ab[1]);

    if (b - a) % 2 == 0 {
        println!("{}", a + (b - a) / 2);
    } else {
        println!("IMPOSSIBLE");
    }
}


Maximum Sum Sequence

Given a sequence of numbers <var>a1</var>, <var>a2</var>, <var>a3</var>, ..., <var>an</var>, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence.

Input

The input consists of multiple datasets. Each data set consists of:

<var>n</var>
<var>a1</var>
<var>a2</var>
.
.
<var>an</var>

You can assume that 1 ≤ <var>n</var> ≤ 5000 and -100000 ≤ <var>ai</var> ≤ 100000.

The input end with a line consisting of a single 0.

Output

For each dataset, print the maximum sum in a line.

Sample Input

7
-5
-1
6
4
9
-6
-7
13
1
2
3
2
-2
-1
1
2
3
2
1
-2
1
3
1000
-200
201
0

Output for the Sample Input

19
14
1001

int solution(void) {

  int max = -25000000;
  int n = 0;
  int sum = 0;
  int i = 0;
  int j = 0;
  int k = 0;

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

    for (i = 0; i < n; i++) {
      for (j = i; j < n; j++) {
        sum = sum + a[j];
        if (max < sum) {
          max = sum;
        }
      }
      sum = 0;
    }
    printf("%d\n", max);
    max = -25000000;
  }
  return 0;
}

fn solution() {
    loop {
        let mut row = String::new();
        io::stdin().read_line(&mut row).ok();
        let row: usize = row.trim().parse().unwrap();
        if row == 0 {
            break;
        }

        let mut v: Vec<isize> = Vec::new();
        for _ in 0..row {
            let mut input = String::new();
            io::stdin().read_line(&mut input).ok();
            let input: isize = input.trim().parse().unwrap();
            v.push(input);
        }

        let mut sum = 0;
        let mut min = 0;
        let mut max = -99999999;
        for z in 0..row {
            sum += v[z];
            max = cmp::max(max, sum - min);
            min = cmp::min(min, sum);
        }

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


You are given an array $$$a[0 \ldots n-1]$$$ of length $$$n$$$ which consists of non-negative integers. Note that array indices start from zero.An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all $$$i$$$ ($$$0 \le i \le n - 1$$$) the equality $$$i \bmod 2 = a[i] \bmod 2$$$ holds, where $$$x \bmod 2$$$ is the remainder of dividing $$$x$$$ by 2.For example, the arrays [$$$0, 5, 2, 1$$$] and [$$$0, 17, 0, 3$$$] are good, and the array [$$$2, 4, 6, 7$$$] is bad, because for $$$i=1$$$, the parities of $$$i$$$ and $$$a[i]$$$ are different: $$$i \bmod 2 = 1 \bmod 2 = 1$$$, but $$$a[i] \bmod 2 = 4 \bmod 2 = 0$$$.In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).Find the minimum number of moves in which you can make the array $$$a$$$ good, or say that this is not possible.

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

    int odd = 0;
    int eve = 0;
    for (int i = 0; i < n; i++) {
      if (i % 2 != arr[i] % 2) {
        if (arr[i] % 2 == 0) {
          eve++;
        } else {
          odd++;
        }
      }
    }
    int sub = 0;
    if (odd == eve) {
      if (odd > 0 && eve > 0) {
        sub = odd;
      }
    } else {
      sub = -1;
    }
    printf("%d\n", sub);
  }
}

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

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

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

        let mut count = [0, 0];
        for i in 0..n {
            if i % 2 != a[i] % 2 {
                count[i % 2] += 1;
            }
        }

        if count[0] == count[1] {
            println!("{}", count[0]);
        } else {
            println!("-1");
        }
    }
}


ソーシャルゲーム (Social Game)

 問題文

JOI 君は明日から新たにソーシャルゲームを始めることにした．

このソーシャルゲームでは，<var>1</var> 日につき <var>1</var> 回までログインすることができ，ログインするたびに <var>A</var> 枚のコインが得られる．

また，月曜日から日曜日まで <var>7</var> 日連続でログインすると，そのたびに，追加で <var>B</var> 枚のコインが得られる．

これ以外にコインがもらえることはない．

明日は月曜日である．JOI 君が少なくとも <var>C</var> 枚のコインを得るためにログインしなければならない回数の最小値を求めよ．

 制約

<var>1 ≦ A ≦ 1000</var>

<var>0 ≦ B ≦ 1000</var>

<var>1 ≦ C ≦ 1000000 (= 10^6)</var>

  入力・出力

入力

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

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

出力

JOI 君が少なくとも <var>C</var> 枚のコインを得るためにログインしなければならない回数の最小値を出力せよ．

 入出力例

入力例 1

3 0 10

出力例 1

4

<var>1</var> 回のログインあたり <var>3</var> 枚のコインが得られ，<var>10</var> 枚のコインを集めたい．

JOI 君は，月曜日から連続 <var>4</var> 日間ログインすることで <var>12</var> 枚のコインが得られる．

<var>3</var> 回以下のログインで <var>10</var> 枚以上のコインを得ることはできないので，JOI 君がログインしなければならない回数の最小値は <var>4</var> である．従って，<var>4</var> を出力する．

入力例 2

1 2 10

出力例 2

8

<var>1</var> 回のログインあたり <var>1</var> 枚のコインが得られる．それとは別に，1 週間連続でログインすることで <var>2</var> 枚のコインが得られる．<var>10</var> 枚のコインを集めたい．

月曜日から日曜日まで連続でログインすると，日々のコイン <var>7</var> 枚に加えて，<var>2</var> 枚のコインが得られるため，合計 <var>9</var> 枚のコインが得られる．従って，更にもう <var>1</var> 回ログインすることにより，<var>10</var> 枚のコインが得られる．

<var>7</var> 回以下のログインで <var>10</var> 枚以上のコインを得ることはできないので，JOI 君がログインしなければならない回数の最小値は <var>8</var> である．従って，<var>8</var> を出力する．

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

int solution() {
  int a = 0;
  int b = 0;
  int c = 0;
  int sum = 0;
  int i = 0;

  scanf("%d %d %d", &a, &b, &c);

  while (sum < c) {
    i++;
    sum += a;
    if ((i % 7) == 0) {
      sum += b;
    }
  }

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

  return 0;
}

fn solution() {
    let nums: Vec<i32> = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.trim_end()
            .to_owned()
            .split(' ')
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };
    let check1: i32 = nums[2] % (7 * nums[0] + nums[1]);
    let check2: i32 = check1 / nums[0];
    let mut ans: i32 = 7 * (nums[2] / (7 * nums[0] + nums[1]));
    if check1 != 0 {
        if check2 >= 7 {
            ans += 7;
        } else {
            if check1 % nums[0] == 0 {
                ans += check2;
            } else {
                ans = ans + check2 + 1;
            }
        }
    }

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


Score : <var>300</var> points

Problem Statement

You are given a string <var>S</var>.

Takahashi can insert the character A at any position in this string any number of times.

Can he change <var>S</var> into AKIHABARA?

Constraints

<var>1 \leq |S| \leq 50</var>

<var>S</var> consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If it is possible to change <var>S</var> into AKIHABARA, print YES; otherwise, print NO.

Sample Input 1

KIHBR

Sample Output 1

YES

Insert one A at each of the four positions: the beginning, immediately after H, immediately after B and the end.

Sample Input 2

AKIBAHARA

Sample Output 2

NO

The correct spell is AKIHABARA.

Sample Input 3

AAKIAHBAARA

Sample Output 3

NO

int solution() {
  char s[51];
  scanf("%s", s);
  int l = strlen(s);
  if (l >= 10) {
    printf("NO");
    return 0;
  }
  if (l == 9 && strcmp(s, "AKIHABARA") == 0) {
    printf("YES");
    return 0;
  }
  if (l == 8 && (strcmp(s, "AKIHABAR") == 0 || strcmp(s, "AKIHABRA") == 0 ||
                 strcmp(s, "AKIHBARA") == 0 || strcmp(s, "KIHABARA") == 0)) {
    printf("YES");
    return 0;
  }
  if (l == 7 && (strcmp(s, "AKIHABR") == 0 || strcmp(s, "AKIHBAR") == 0 ||
                 strcmp(s, "KIHABAR") == 0 || strcmp(s, "AKIHBRA") == 0 ||
                 strcmp(s, "KIHABRA") == 0 || strcmp(s, "KIHBARA") == 0)) {
    printf("YES");
    return 0;
  }
  if (l == 6 && (strcmp(s, "KIHBRA") == 0 || strcmp(s, "KIHBAR") == 0 ||
                 strcmp(s, "KIHABR") == 0 || strcmp(s, "AKIHBR") == 0)) {
    printf("YES");
    return 0;
  }
  if (l == 5 && strcmp(s, "KIHBR") == 0) {
    printf("YES");
    return 0;
  }
  printf("NO");

  return 0;
}

fn solution() {
    input!(s: String);
    let vs = vec![
        "AKIHABARA",
        "KIHABARA",
        "AKIHBARA",
        "KIHBARA",
        "AKIHABRA",
        "KIHABRA",
        "AKIHBRA",
        "KIHBRA",
        "AKIHABAR",
        "KIHABAR",
        "AKIHBAR",
        "KIHBAR",
        "AKIHABR",
        "KIHABR",
        "AKIHBR",
        "KIHBR",
    ];

    let s: &str = &s;
    let ok = vs.contains(&s);

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