Artem is building a new robot. He has a matrix $$$a$$$ consisting of $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{i,j}$$$ written in it. If two adjacent cells contain the same value, the robot will break. A matrix is called good if no two adjacent cells contain the same value, where two cells are called adjacent if they share a side. Artem wants to increment the values in some cells by one to make $$$a$$$ good.More formally, find a good matrix $$$b$$$ that satisfies the following condition —   For all valid ($$$i,j$$$), either $$$b_{i,j} = a_{i,j}$$$ or $$$b_{i,j} = a_{i,j}+1$$$. For the constraints of this problem, it can be shown that such a matrix $$$b$$$ always exists. If there are several such tables, you can output any of them. Please note that you do not have to minimize the number of increments.

int solution() {
  int tc;
  scanf("%d", &tc);
  while (tc--) {
    int n;
    int m;
    scanf("%d%d", &n, &m);
    int mat[n][m];

    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        scanf("%d", &mat[i][j]);
        if (mat[i][j] % 2 != (i + j) % 2) {
          ++mat[i][j];
        }
      }
    }

    for (int i = 0; i < n; ++i) {
      for (int j = 0; j < m; ++j) {
        printf("%d ", mat[i][j]);
      }
      printf("\n");
    }
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let t = s.trim().parse::<i32>().unwrap();
    for _ in 0..t {
        s.clear();
        std::io::stdin().read_line(&mut s).unwrap();
        let mut nums = s.split_whitespace();
        let row: u32 = nums.next().unwrap().parse().unwrap();
        let _col: u32 = nums.next().unwrap().parse().unwrap();
        for i in 0..row {
            s.clear();
            std::io::stdin().read_line(&mut s).unwrap();
            for (j, n) in s.split_whitespace().enumerate() {
                let mut value = n.parse::<u32>().unwrap();
                if ((j as u32 ^ i ^ value) & 1u32) == 1 {
                    value += 1;
                }
                print!("{} ", value);
            }
            println!();
        }
    }
}


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \le |p_i - p_{i+1}| \le 4$$$ for each $$$i$$$ ($$$1 \le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.

int solution() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int n;
    scanf("%d", &n);
    if (n < 4) {
      printf("-1\n");
    } else {
      for (int i = n; i >= 1; i--) {
        if (i & 1) {
          printf("%d ", i);
        }
      }
      printf("4 2 ");
      for (int i = 6; i <= n; i++) {
        if (!(i & 1)) {
          printf("%d ", i);
        }
      }
      printf("\n");
    }
  }
  return 0;
}

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();
        if n < 4 {
            println!("-1");
            continue;
        }
        let k = (n - 3) / 2;
        for i in 0..k {
            print!("{} ", (k - i - 1) * 2 + 5);
        }
        print!("2 4 1 3 ");
        for i in 0..((n - 4) / 2) {
            print!("{} ", i * 2 + 6);
        }
        println!();
    }
}


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence $$$s$$$ and an integer number $$$k$$$. Your task is to find a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$.It is guaranteed that such sequence always exists.

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 k = get!(usize);
    if n == k {
        let ans = get!(String);
        println!("{}", ans);
        return;
    }
    let s = get().as_bytes();

    let mut flag = vec![true; n];
    let mut stack = vec![];
    let mut len = n;
    for i in 0..n {
        if s[i] == b')' {
            flag[i] = false;
            if let Some(j) = stack.pop() {
                flag[j] = false;
            }
            len -= 2;
            if len == k {
                break;
            }
        } else {
            stack.push(i);
        }
    }
    let mut ans = vec![];
    for i in 0..n {
        if flag[i] {
            ans.push(s[i]);
        }
    }
    let ans = String::from_utf8(ans).unwrap();
    println!("{}", ans);
}


A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as: +-        -++- -+    |+- -++- -+||   |||   ||   |||   ||+- -++- -+||   |+-        -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.

fn solution() {
    let mut input_str = String::new();
    let mut input_str2 = String::new();
    std::io::stdin()
        .read_line(&mut input_str)
        .expect("read_error");
    std::io::stdin()
        .read_line(&mut input_str2)
        .expect("read_error");
    let brackets: &str = input_str2.trim();

    let mut state = [[' '; 300]; 300];
    let mut cur = 0;
    let mut max = 0;
    for ch in brackets.chars() {
        if ch == '[' {
            cur += 1;
            if max < cur {
                max = cur;
            }
        } else if ch == ']' {
            cur -= 1;
        }
    }

    cur = 0;
    let mut cl = 0;
    let mut is_left = false;
    for ch in brackets.chars() {
        if ch == '[' {
            for row in cur..(max + max - cur) {
                state[row][cl] = '|';
            }
            state[cur][cl] = '+';
            state[cur][cl + 1] = '-';
            state[max + max - cur][cl] = '+';
            state[max + max - cur][cl + 1] = '-';
            cur += 1;
            cl += 1;
            is_left = true;
        } else if ch == ']' {
            if is_left {
                cl += 3;
                is_left = false;
            }
            cur -= 1;
            for row in cur..(max + max - cur) {
                state[row][cl] = '|';
            }
            state[cur][cl] = '+';
            state[cur][cl - 1] = '-';
            state[max + max - cur][cl] = '+';
            state[max + max - cur][cl - 1] = '-';
            cl += 1;
        }
    }

    for i in 0..(max + max + 1) {
        for j in 0..cl {
            print!("{}", state[i][j]);
        }
        println!()
    }
}


Mark is asked to take a group photo of $$$2n$$$ people. The $$$i$$$-th person has height $$$h_i$$$ units.To do so, he ordered these people into two rows, the front row and the back row, each consisting of $$$n$$$ people. However, to ensure that everyone is seen properly, the $$$j$$$-th person of the back row must be at least $$$x$$$ units taller than the $$$j$$$-th person of the front row for each $$$j$$$ between $$$1$$$ and $$$n$$$, inclusive.Help Mark determine if this is possible.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int x;
    scanf("%d %d", &n, &x);
    int ara[2 * n];
    for (int i = 0; i < 2 * n; i++) {
      scanf("%d", &ara[i]);
    }
    for (int i = 0; i < 2 * n - 1; i++) {
      for (int j = 0; j < 2 * n - i - 1; j++) {
        if (ara[j] > ara[j + 1]) {
          int temp = ara[j];
          ara[j] = ara[j + 1];
          ara[j + 1] = temp;
        }
      }
    }

    int flag = 1;
    for (int i = 0; i < n; i++) {
      if (ara[n + i] - ara[i] < x) {
        flag = 0;
        break;
      }
    }
    if (flag == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    input! {
        name = reader,
        tests: usize
    }
    for _ in 0..tests {
        input! {
            use reader,
            n: usize,
            x: u32,
            mut h: [u32; 2 * n]
        }
        h.sort_unstable();
        if (0..n).all(|i| h[i] + x <= h[i + n]) {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


There is a frog staying to the left of the string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ characters (to be more precise, the frog initially stays at the cell $$$0$$$). Each character of $$$s$$$ is either 'L' or 'R'. It means that if the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $$$0$$$.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the $$$n+1$$$-th cell. The frog chooses some positive integer value $$$d$$$ before the first jump (and cannot change it later) and jumps by no more than $$$d$$$ cells at once. I.e. if the $$$i$$$-th character is 'L' then the frog can jump to any cell in a range $$$[max(0, i - d); i - 1]$$$, and if the $$$i$$$-th character is 'R' then the frog can jump to any cell in a range $$$[i + 1; min(n + 1; i + d)]$$$.The frog doesn't want to jump far, so your task is to find the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it can jump by no more than $$$d$$$ cells at once. It is guaranteed that it is always possible to reach $$$n+1$$$ from $$$0$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int test;
  scanf("%d", &test);
  while (test--) {
    char s[200002];
    scanf("%s", s);
    int max = 1;
    int i = 0;
    int l = 1;
    while (s[i]) {
      if (s[i] == 'L') {
        l++;
      } else {
        l = 1;
      }
      if (max < l) {
        max = l;
      }
      i++;
    }
    printf("%d\n", max);
  }
  return 0;
}

fn solution() {
    use std::io::{self, BufRead};
    let reader = io::stdin();
    let test_cases = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<usize>()
        .unwrap();
    for _ in 0..test_cases {
        let path: String = format!("R{}R", reader.lock().lines().next().unwrap().unwrap());
        let mut max_d = usize::min_value();
        let mut last_r = usize::min_value();
        for (index, chars) in path.chars().enumerate() {
            if chars == 'R' {
                let distance = index - last_r;
                if distance > max_d {
                    max_d = distance;
                }
                last_r = index;
            }
        }
        println!("{}", max_d);
    }
}


Problem A: ICPC Score Totalizer Software

The International Clown and Pierrot Competition (ICPC), is one of the
most distinguished and also the most popular events on earth in the
show business.

One of the unique features of this contest is the great number of
judges that sometimes counts up to one hundred.  The number of judges
may differ from one contestant to another, because judges with any
relationship whatsoever with a specific contestant are temporarily
excluded for scoring his/her performance.

Basically, scores given to a contestant's performance by the judges
are averaged to decide his/her score.  To avoid letting judges with
eccentric viewpoints too much influence the score, the highest and the
lowest scores are set aside in this calculation.  If the same highest
score is marked by two or more judges, only one of them is ignored.
The same is with the lowest score.  The average, which may contain
fractions, are truncated down to obtain final score as an integer.

You are asked to write a program that computes the scores of
performances, given the scores of all the judges, to speed up the event
to be suited for a TV program.

Input

The input consists of a number of datasets, each corresponding to a
contestant's performance.  There are no more than 20 datasets in the input.

A dataset begins with a line with an integer n, the number of
judges participated in scoring the performance (3 ≤ n ≤
100).  Each of the n lines following it has an integral
score s (0 ≤ s ≤ 1000) marked by a judge.  No
other characters except for digits to express these numbers are in the
input.  Judges' names are kept secret.

The end of the input is indicated by a line with a single zero in it.

Output

For each dataset, a line containing a single decimal integer
indicating the score for the corresponding performance should be
output.  No other characters should be on the output line.

Sample Input

3
1000
342
0
5
2
2
9
11
932
5
300
1000
0
200
400
8
353
242
402
274
283
132
402
523
0

Output for the Sample Input

342
7
300
326

int solution(void) {
  int n;

  while (1) {
    scanf("%d", &n);
    if (!n) {
      break;
    }

    int point[128] = {0};
    int max = 0;
    int min = 1000;
    int i = 0;
    int j = 0;
    int k = 0;
    int x = 0;
    i = n;
    while (i-- > 0) {
      scanf("%d", &x);

      if (x > max) {
        point[j] = max;
        max = x;
        j++;
      } else if (x < min) {
        point[j] = min;
        min = x;
        j++;
      }

      else {
        point[j] = x;
        j++;
      }
    }
    int sum = 0;
    for (j = 0; j < n + 2; j++) {
      sum = sum + point[j];
    }
    if (min == 1000) {
      sum = sum - point[1];
    } else {
      sum = sum - 1000;
    }
    printf("%d\n", sum / (n - 2));
  }

  return 0;
}

fn solution() {
    loop {
        let n = {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).unwrap();
            let s = s.trim_end().to_owned();
            s.parse::<usize>().unwrap()
        };
        if n == 0 {
            std::process::exit(0);
        }
        let mut a = (0..n)
            .map(|_| {
                let mut s = String::new();
                std::io::stdin().read_line(&mut s).unwrap();
                let s = s.trim_end().to_owned();
                s.parse::<u32>().unwrap()
            })
            .collect::<Vec<_>>();
        a.sort();
        println!("{}", a[1..a.len() - 1].iter().sum::<u32>() / (n - 2) as u32);
    }
}


You are given a positive integer $$$n$$$. In one move, you can increase $$$n$$$ by one (i.e. make $$$n := n + 1$$$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  long long int n;
  long long int s;
  long long int k;
  long long int ans;
  long long int cnt;
  for (; t > 0; t--) {
    scanf("%lld %lld", &n, &s);
    ans = 0;
    for (;;) {
      k = 1;
      while (n / k > 9) {
        k *= 10;
      }
      cnt = 0;
      while (k > 0) {
        cnt += n / k % 10;
        if (cnt > s) {
          break;
        }
        k /= 10;
      }
      if (cnt <= s) {
        break;
      }
      ans += n / (10 * k) * 10 * k + 10 * k - n;
      n = n / (10 * k) * 10 * k + 10 * k;
    }
    printf("%lld\n", ans);
  }
  return 0;
}

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

    for _ in 0..t {
        let (mut n, s): (i64, i64) = {
            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(),
            )
        };

        let digit_sum = |n: i64| -> i64 {
            n.to_string()
                .chars()
                .fold(0, |acc, c| acc + c.to_digit(10).unwrap()) as i64
        };

        let (mut ans, mut p) = (0, 1);
        while digit_sum(n) > s {
            ans += (10 - n % 10) % 10 * p;
            n = n / 10 + if n % 10 > 0 { 1 } else { 0 };
            p *= 10;
        }
        println!("{}", ans);
    }
}


In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be a1, a2, ..., an. He remembered that he calculated gcd(ai, ai + 1, ..., aj) for every 1 ≤ i ≤ j ≤ n and put it into a set S. gcd here means the greatest common divisor.Note that even if a number is put into the set S twice or more, it only appears once in the set.Now Marco gives you the set S and asks you to help him figure out the initial sequence. If there are many solutions, print any of them. It is also possible that there are no sequences that produce the set S, in this case print -1.

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

  return 0;
}

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

    for i in 1..N {
        if !arr[i].is_multiple_of(arr[0]) {
            println!("-1");
            process::exit(0);
        }
    }

    println!("{}", (N - 1) * 2 + 1);
    print!("{} ", arr[0]);
    for i in 1..N {
        print!("{} {} ", arr[i], arr[0]);
    }
    println!();
}


Score : <var>400</var> points

Problem Statement

There is a bar of chocolate with a height of <var>H</var> blocks and a width of <var>W</var> blocks.
Snuke is dividing this bar into exactly three pieces.
He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.

Snuke is trying to divide the bar as evenly as possible.
More specifically, he is trying to minimize <var>S_{max}</var> - <var>S_{min}</var>, where <var>S_{max}</var> is the area (the number of blocks contained) of the largest piece, and <var>S_{min}</var> is the area of the smallest piece.
Find the minimum possible value of <var>S_{max} - S_{min}</var>.

Constraints

<var>2 ≤ H, W ≤ 10^5</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum possible value of <var>S_{max} - S_{min}</var>.

Sample Input 1

3 5

Sample Output 1

0

In the division below, <var>S_{max} - S_{min} = 5 - 5 = 0</var>.

Sample Input 2

4 5

Sample Output 2

2

In the division below, <var>S_{max} - S_{min} = 8 - 6 = 2</var>.

Sample Input 3

5 5

Sample Output 3

4

In the division below, <var>S_{max} - S_{min} = 10 - 6 = 4</var>.

Sample Input 4

100000 2

Sample Output 4

1

Sample Input 5

100000 100000

Sample Output 5

50000

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

    for _ in 0..2 {
        for i in 1..v[0] / 2 + 1 {
            let x = i * v[1];

            let mut y = ((v[0] - i) / 2) * v[1];
            let mut z = ((v[0] - i) / 2 + (v[0] - i) % 2) * v[1];
            d = cmp::min(d, cmp::max(x, cmp::max(y, z)) - cmp::min(x, cmp::min(x, y)));

            y = v[1] / 2 * (v[0] - i);
            z = (v[1] / 2 + v[1] % 2) * (v[0] - i);
            d = cmp::min(d, cmp::max(x, cmp::max(y, z)) - cmp::min(x, cmp::min(x, y)));
        }
        v.reverse();
    }
    println!("{}", d);
}


You and your friends live in $$$n$$$ houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with integer coordinates), so that the summary distance from all the houses to the exhibition is minimal. The exhibition can be built in the same point as some house. The distance between two points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$, where $$$|x|$$$ is the absolute value of $$$x$$$.

int solution() {
  unsigned long long int l;
  unsigned long long int k;
  unsigned long long int j;
  unsigned long long int i;
  unsigned long long int m;
  unsigned long long int n;
  unsigned long long int item;
  unsigned long long int x;
  unsigned long long int y;
  unsigned long long int sum;
  scanf("%llu", &l);
  for (k = 0; k < l; k++) {
    scanf("%llu", &n);
    unsigned long long int a[n];
    unsigned long long int b[n];
    for (i = 0; i < n; i++) {
      scanf("%llu %llu", &a[i], &b[i]);
    }
    if (n % 2 == 1) {
      printf("%d\n", 1);
    } else {
      for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
          if (a[i] > a[j]) {
            item = a[i];
            a[i] = a[j];
            a[j] = item;
          }
        }
      }
      for (i = 0; i < n - 1; i++) {
        for (j = i + 1; j < n; j++) {
          if (b[i] > b[j]) {
            item = b[i];
            b[i] = b[j];
            b[j] = item;
          }
        }
      }
      x = a[n / 2] - a[(n / 2) - 1] + 1;
      y = b[n / 2] - b[(n / 2) - 1] + 1;
      sum = x * y;
      printf("%llu\n", sum);
    }
  }
  return 0;
}

fn solution() {
    let stdin = stdin();
    let mut lines = stdin.lock().lines().map(|line| line.unwrap());
    let _n = lines.next().unwrap();
    while let Some(case_len) = lines.next() {
        let case_len: usize = case_len.parse().unwrap();
        let mut xs = Vec::<i64>::new();
        let mut ys = Vec::<i64>::new();
        for _ in 0..case_len {
            let xy: Vec<i64> = lines
                .next()
                .unwrap()
                .split(" ")
                .map(|x| x.parse().unwrap())
                .collect();
            xs.push(xy[0]);
            ys.push(xy[1]);
        }
        if case_len % 2 == 1 {
            println!("1");
            continue;
        }
        xs.sort();
        ys.sort();
        let out = (xs[case_len / 2] - xs[case_len / 2 - 1] + 1)
            * (ys[case_len / 2] - ys[case_len / 2 - 1] + 1);
        println!("{}", out);
    }
}


Score : <var>100</var> points

Problem Statement

You are given four digits <var>N_1, N_2, N_3</var> and <var>N_4</var>. Determine if these can be arranged into the sequence of digits "<var>1974</var>".

Constraints

<var>0 \leq N_1, N_2, N_3, N_4 \leq 9</var>

<var>N_1, N_2, N_3</var> and <var>N_4</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>N_1</var> <var>N_2</var> <var>N_3</var> <var>N_4</var>

Output

If <var>N_1, N_2, N_3</var> and <var>N_4</var> can be arranged into the sequence of digits "<var>1974</var>", print YES; if they cannot, print NO.

Sample Input 1

1 7 9 4

Sample Output 1

YES

We can get <var>1974</var> by swapping <var>N_2</var> and <var>N_3</var>.

Sample Input 2

1 9 7 4

Sample Output 2

YES

We already have <var>1974</var> before doing anything.

Sample Input 3

1 2 9 1

Sample Output 3

NO

Sample Input 4

4 9 0 8

Sample Output 4

NO

fn solution() {
    let mut buf = String::new();
    let handle = std::io::stdin();

    let mut ns: Vec<usize> = {
        handle.read_line(&mut buf).unwrap();
        let tmp = buf.split_whitespace().map(|a| a.parse().unwrap()).collect();
        buf.clear();
        tmp
    };
    ns.sort();
    if ns.binary_search(&1).is_ok()
        && ns.binary_search(&9).is_ok()
        && ns.binary_search(&7).is_ok()
        && ns.binary_search(&4).is_ok()
    {
        println!("YES");
    } else {
        println!("NO");
    }
}


Score : <var>300</var> points

Problem Statement

Snuke and Raccoon have a heap of <var>N</var> cards. The <var>i</var>-th card from the top has the integer <var>a_i</var> written on it.

They will share these cards.
First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards.
Here, both Snuke and Raccoon have to take at least one card.

Let the sum of the integers on Snuke's cards and Raccoon's cards be <var>x</var> and <var>y</var>, respectively.
They would like to minimize <var>|x-y|</var>.
Find the minimum possible value of <var>|x-y|</var>.

Constraints

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

<var>-10^{9} \leq a_i \leq 10^{9}</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_{N}</var>

Output

Print the answer.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

1

If Snuke takes four cards from the top, and Raccoon takes the remaining two cards, <var>x=10</var>, <var>y=11</var>, and thus <var>|x-y|=1</var>. This is the minimum possible value.

Sample Input 2

2
10 -10

Sample Output 2

20

Snuke can only take one card from the top, and Raccoon can only take the remaining one card. In this case, <var>x=10</var>, <var>y=-10</var>, and thus <var>|x-y|=20</var>.

int solution(void) {
  long long int n;
  long long int a[200000] = {0};
  long long int sum = 0;
  long long int sunuke = 0;
  long long int araiguma = 0;
  long long int min = 10000000000;
  scanf("%lld", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
  }
  for (int j = 0; j < n - 1; j++) {
    sunuke += a[j];
    araiguma = sum - sunuke;

    if (min > sunuke - araiguma && sunuke - araiguma > 0) {
      min = sunuke - araiguma;
    } else if (min > araiguma - sunuke && araiguma - sunuke > 0) {
      min = araiguma - sunuke;
    } else if (sunuke == araiguma) {
      min = 0;
      break;
    }
  }
  if (min == 10000000000) {
    min = 0;
  }
  printf("%lld", min);
  return 0;
}

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

    let mut sums: Vec<isize> = Vec::with_capacity(n);
    let total: isize = ls.iter().fold(0, |a, b| {
        let sum = a + b;
        sums.push(sum);
        sum
    });
    sums.pop();
    let mut min_x = std::isize::MAX;
    for i in sums {
        if (total - 2 * i).abs() < min_x {
            min_x = (total - 2 * i).abs();
        }
    }
    println!("{}", min_x);
}


Vlad went into his appartment house entrance, now he is on the $$$1$$$-th floor. He was going to call the elevator to go up to his apartment.There are only two elevators in his house. Vlad knows for sure that:  the first elevator is currently on the floor $$$a$$$ (it is currently motionless),  the second elevator is located on floor $$$b$$$ and goes to floor $$$c$$$ ($$$b \ne c$$$). Please note, if $$$b=1$$$, then the elevator is already leaving the floor $$$1$$$ and Vlad does not have time to enter it. If you call the first elevator, it will immediately start to go to the floor $$$1$$$. If you call the second one, then first it will reach the floor $$$c$$$ and only then it will go to the floor $$$1$$$. It takes $$$|x - y|$$$ seconds for each elevator to move from floor $$$x$$$ to floor $$$y$$$.Vlad wants to call an elevator that will come to him faster. Help him choose such an elevator.

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

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

    io::stdin().read_line(&mut tc).expect("");

    let tc: u32 = tc.trim().parse().expect("");

    for _ in 0..tc {
        let mut line = String::new();
        io::stdin()
            .read_line(&mut line)
            .expect("Failed to read line");

        let inputs: Vec<i64> = line
            .split_whitespace()
            .map(|x| x.parse().expect("Not an integer!"))
            .collect();

        let [a, b, c] = <[i64; 3]>::try_from(inputs).ok().unwrap();

        let time1 = a - 1;
        let time2 = cmp::max(b - c, c - b) + c - 1;

        if time1 < time2 {
            println!("1");
        } else if time1 > time2 {
            println!("2");
        } else {
            println!("3");
        }
    }
}


On the way to school, Karen became fixated on the puzzle game on her phone!  The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

int solution() {
  int n;
  int m;
  scanf("%d%d", &n, &m);
  int a[n][m];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      scanf("%d", &a[i][j]);
    }
  }
  int min0[n];
  int min1[m];
  int count = 0;
  if (n <= m) {
    for (int i = 0; i < n; i++) {
      int min = 501;
      for (int j = 0; j < m; j++) {
        if (a[i][j] < min) {
          min = a[i][j];
        }
      }
      min0[i] = min;
      count += min;
      for (int j = 0; j < m; j++) {
        a[i][j] -= min;
      }
    }

    for (int i = 0; i < m; i++) {
      int min = 501;
      for (int j = 0; j < n; j++) {
        if (a[j][i] < min) {
          min = a[j][i];
        }
      }
      min1[i] = min;
      count += min;
      for (int j = 0; j < n; j++) {
        a[j][i] -= min;
      }
    }
  } else {
    for (int i = 0; i < m; i++) {
      int min = 501;
      for (int j = 0; j < n; j++) {
        if (a[j][i] < min) {
          min = a[j][i];
        }
      }
      min1[i] = min;
      count += min;
      for (int j = 0; j < n; j++) {
        a[j][i] -= min;
      }
    }

    for (int i = 0; i < n; i++) {
      int min = 501;
      for (int j = 0; j < m; j++) {
        if (a[i][j] < min) {
          min = a[i][j];
        }
      }
      min0[i] = min;
      count += min;
      for (int j = 0; j < m; j++) {
        a[i][j] -= min;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] != 0) {
        printf("-1");
        return 0;
      }
    }
  }
  printf("%d\n", count);
  for (int i = 0; i < n; i++) {
    for (int j = 1; j <= min0[i]; j++) {
      printf("row %d\n", i + 1);
    }
  }
  for (int i = 0; i < m; i++) {
    for (int j = 1; j <= min1[i]; j++) {
      printf("col %d\n", i + 1);
    }
  }
}

fn solution() {
    let mut a = [[0; 100]; 100];
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let v = s.split_whitespace().collect::<Vec<&str>>();
    let n = v[0].parse::<usize>().unwrap();
    let m = v[1].parse::<usize>().unwrap();
    for i in 0..n {
        let mut s = String::new();
        let mut j: usize = 0;
        io::stdin().read_line(&mut s).unwrap();
        for x in s.split_whitespace() {
            a[i][j] = x.parse::<i32>().unwrap();
            j += 1;
        }
    }
    let mut b = a;
    let mut ans = 0;
    for i in 0..n {
        let mut mi = i32::max_value();
        for j in 0..m {
            mi = cmp::min(mi, b[i][j]);
        }
        for j in 0..m {
            b[i][j] -= mi;
        }
        ans += mi;
    }
    for j in 0..m {
        let mut mi = i32::max_value();
        for i in 0..n {
            mi = cmp::min(mi, b[i][j]);
        }
        for i in 0..n {
            b[i][j] -= mi;
        }
        ans += mi;
    }
    for i in 0..n {
        for j in 0..m {
            if b[i][j] > 0 {
                println!("-1");
                return;
            }
        }
    }
    let mut ans2 = 0;
    let mut b = a;
    for j in 0..m {
        let mut mi = i32::max_value();
        for i in 0..n {
            mi = cmp::min(mi, b[i][j]);
        }
        for i in 0..n {
            b[i][j] -= mi;
        }
        ans2 += mi;
    }
    for i in 0..n {
        let mut mi = i32::max_value();
        for j in 0..m {
            mi = cmp::min(mi, b[i][j]);
        }
        for j in 0..m {
            b[i][j] -= mi;
        }
        ans2 += mi;
    }
    if ans < ans2 {
        println!("{}", ans);
        for i in 0..n {
            let mut mi = i32::max_value();
            for j in 0..m {
                mi = cmp::min(mi, a[i][j]);
            }
            for j in 0..m {
                a[i][j] -= mi;
            }
            while mi > 0 {
                println!("row {}", i + 1);
                mi -= 1;
            }
        }
        for j in 0..m {
            let mut mi = i32::max_value();
            for i in 0..n {
                mi = cmp::min(mi, a[i][j]);
            }
            for i in 0..n {
                a[i][j] -= mi;
            }
            while mi > 0 {
                println!("col {}", j + 1);
                mi -= 1;
            }
        }
    } else {
        println!("{}", ans2);
        for j in 0..m {
            let mut mi = i32::max_value();
            for i in 0..n {
                mi = cmp::min(mi, a[i][j]);
            }
            for i in 0..n {
                a[i][j] -= mi;
            }
            while mi > 0 {
                println!("col {}", j + 1);
                mi -= 1;
            }
        }
        for i in 0..n {
            let mut mi = i32::max_value();
            for j in 0..m {
                mi = cmp::min(mi, a[i][j]);
            }
            for j in 0..m {
                a[i][j] -= mi;
            }
            while mi > 0 {
                println!("row {}", i + 1);
                mi -= 1;
            }
        }
    }
}


残り物には福がある

<var>K</var> 個の石から、<var>P</var> 人が順番に１つずつ石を取るゲームがあります。<var>P</var> 人目が石を取った時点で、まだ石が残っていれば、また１人目から順番に１つずつ石を取っていきます。このゲームでは、最後の石を取った人が勝ちとなります。<var>K</var> と<var>P</var> が与えられたとき、何人目が勝つか判定するプログラムを作成してください。

入力

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

<var>N</var>
<var>K</var>1 <var>P</var>1</var>
<var>K</var>2 <var>P</var>2</var>
:
<var>KN</var> <var>PN</var>

１行目にはゲームを行う回数 <var>N</var> (1 ≤ <var>N</var> ≤ 100) が与えられる。続く <var>N</var> 行に、<var>i</var> 回目のゲームにおける石の個数 <var>Ki</var> (2 ≤ <var>Ki</var> ≤ 1000) と、ゲームに参加する人数 <var>Pi</var> (2 ≤ <var>Pi</var> ≤ 1000) が与えられる。

出力

それぞれのゲームについて、何人目が勝つかを１行に出力する。

入出力例

入力例

3
10 3
2 10
4 2

 出力例

1
2
2

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

  int value[times];
  int headCount[times];
  int i;

  for (i = 0; i < times; i++) {

    scanf("%d %d", &value[i], &headCount[i]);
  }

  for (i = 0; i < times; i++) {
    if ((value[i] % headCount[i]) == 0) {
      printf("%d\n", headCount[i]);
    } else {
      printf("%d\n", value[i] % headCount[i]);
    }
  }

  return 0;
}

fn solution() {
    let input = {
        let mut buf = vec![];
        stdin().read_to_end(&mut buf);
        unsafe { String::from_utf8_unchecked(buf) }
    };
    let mut lines = input.split('\n');

    let n = lines.next().unwrap().parse().unwrap();

    for line in lines.take(n) {
        let (k, p) = {
            let mut iter = line.split(' ').map(|s| s.parse::<u32>().unwrap());
            (iter.next().unwrap(), iter.next().unwrap())
        };

        println!("{}", (k - 1) % p + 1);
    }
}


Score : <var>100</var> points

Problem Statement

You are given a grid with <var>2</var> rows and <var>3</var> columns of squares.
The color of the square at the <var>i</var>-th row and <var>j</var>-th column is represented by the character <var>C_{ij}</var>.

Write a program that prints YES if this grid remains the same when rotated <var>180</var> degrees, and prints NO otherwise.

Constraints

<var>C_{i,j}(1 \leq i \leq 2, 1 \leq j \leq 3)</var> is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

<var>C_{11}C_{12}C_{13}</var>
<var>C_{21}C_{22}C_{23}</var>

Output

Print YES if this grid remains the same when rotated <var>180</var> degrees; print NO otherwise.

Sample Input 1

pot
top

Sample Output 1

YES

This grid remains the same when rotated <var>180</var> degrees.

Sample Input 2

tab
bet

Sample Output 2

NO

This grid does not remain the same when rotated <var>180</var> degrees.

Sample Input 3

eye
eel

Sample Output 3

NO

int solution() {
  char *a = (char *)malloc(4);
  char *b = (char *)malloc(4);

  scanf("%s", a);
  scanf("%s", b);
  char c = b[0];
  b[0] = b[2];
  b[2] = c;
  if (strcmp(a, b) != 0) {
    printf("NO\n");
  } else {
    printf("YES\n");
  }

  free(a);
  free(b);

  return 0;
}

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

    let mut ans = true;
    for i in 0..3 {
        if s.chars().nth(i) != t.chars().nth(2 - i) {
            ans = false;
            break;
        }
    }
    if ans {
        println!("YES");
    } else {
        println!("NO");
    }
}


As you could know there are no male planes nor female planes. However, each plane on Earth likes some other plane. There are n planes on Earth, numbered from 1 to n, and the plane with number i likes the plane with number fi, where 1 ≤ fi ≤ n and fi ≠ i.We call a love triangle a situation in which plane A likes plane B, plane B likes plane C and plane C likes plane A. Find out if there is any love triangle on Earth.

fn solution() {
    let stdin = io::stdin();
    let mut input = String::new();
    stdin.read_line(&mut input).unwrap();
    input.clear();
    stdin.read_line(&mut input).unwrap();
    let arr: Vec<usize> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let mut ok = false;
    for &n in &arr {
        let a = n;
        let b = arr[a - 1];
        let c = arr[b - 1];
        if arr[c - 1] == a && a != b && b != c && c != a {
            ok = true;
            break;
        }
    }
    println!("{}", if ok { "Yes" } else { "No" });
}


Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 < p_2 < \ldots < p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.

fn solution() {
    let stdin_handle = std::io::stdin();
    let stdin = stdin_handle.lock();
    let mut it = stdin.lines().skip(1);
    let (a, b) = (it.next().unwrap().unwrap(), it.next().unwrap().unwrap());
    let (ab, bb) = (a.as_bytes(), b.as_bytes());
    let mut mls = Vec::<u32>::with_capacity(b.len());
    let mut mrs = Vec::<u32>::with_capacity(b.len());
    for i in 0..a.len() {
        if mls.len() >= b.len() {
            break;
        }
        if bb[mls.len()] == ab[i] {
            mls.push(i as u32);
        }
    }
    for i in (0..a.len()).rev() {
        if mrs.len() >= b.len() {
            break;
        }
        if bb[b.len() - mrs.len() - 1] == ab[i] {
            mrs.push(i as u32);
        }
    }
    mrs.reverse();
    let mut ans = 1;
    for i in 0..b.len() - 1 {
        ans = std::cmp::max(ans, mrs[i + 1] - mls[i]);
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between <var>1</var> and <var>9</var> (inclusive) together. He cannot do any other calculation.

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

If Takahashi can calculate <var>A \times B</var>, print the result; if he cannot, print -1 instead.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If Takahashi can calculate <var>A \times B</var>, print the result; if he cannot, print -1.

Sample Input 1

2 5

Sample Output 1

10

<var>2 \times 5 = 10</var>.

Sample Input 2

5 10

Sample Output 2

-1

<var>5\times 10 = 50</var>, but Takahashi cannot do this calculation, so print -1 instead.

Sample Input 3

9 9

Sample Output 3

81

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    println!(
        "{}",
        if s.trim().len() == 3 {
            s.chars()
                .filter_map(|t| str::parse::<i8>(&t.to_string()).ok())
                .product::<i8>()
        } else {
            -1
        }
    );
}


Finding a Word

Write a program which reads a word <var>W</var> and a text <var>T</var>, and prints the number of word <var>W</var> which appears in text <var>T</var>

  <var>T</var> consists of string <var>Ti</var> separated by space characters and newlines. Count the number of <var>Ti</var> which equals to <var>W</var>. The word and text are case insensitive.

Constraints

The length of <var>W</var> ≤ 10

<var>W</var> consists of lower case letters

The length of <var>T</var> in a line ≤ 1000

Input

  In the first line, the word <var>W</var> is given. In the following lines, the text <var>T</var> is given separated by space characters and newlines.

"END_OF_TEXT" indicates the end of the text.

Output

  Print the number of <var>W</var> in the text.

Sample Input

computer
Nurtures computer scientists and highly-skilled computer engineers
who will create and exploit "knowledge" for the new era.
Provides an outstanding computer environment.
END_OF_TEXT

Sample Output

3

fn solution() {
    let mut w = String::new();
    let mut s = String::new();
    stdin().read_line(&mut w).unwrap();
    let w = w.trim().to_lowercase();
    stdin().read_to_string(&mut s).unwrap();
    println!(
        "{}",
        s.split_whitespace().fold(0, |a, e| {
            if e.to_lowercase() == w {
                a + 1
            } else {
                a
            }
        })
    );
}


Score: <var>300</var> points

Problem Statement

M-kun is a student in Aoki High School, where a year is divided into <var>N</var> terms.

There is an exam at the end of each term. According to the scores in those exams, a student is given a grade for each term, as follows:

For the first through <var>(K-1)</var>-th terms: not given.

For each of the <var>K</var>-th through <var>N</var>-th terms: the multiplication of the scores in the last <var>K</var> exams, including the exam in the graded term.

M-kun scored <var>A_i</var> in the exam at the end of the <var>i</var>-th term.

For each <var>i</var> such that <var>K+1 \leq i \leq N</var>, determine whether his grade for the <var>i</var>-th term is strictly greater than the grade for the <var>(i-1)</var>-th term.

Constraints

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

<var>1 \leq K \leq N-1</var>

<var>1 \leq A_i \leq 10^{9}</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>A_1</var> <var>A_2</var> <var>A_3</var> <var>\ldots</var> <var>A_N</var>

Output

Print the answer in <var>N-K</var> lines.

The <var>i</var>-th line should contain Yes if the grade for the <var>(K+i)</var>-th term is greater than the grade for the <var>(K+i-1)</var>-th term, and No otherwise.

Sample Input 1

5 3
96 98 95 100 20

Sample Output 1

Yes
No

His grade for each term is computed as follows:

<var>3</var>-rd term: <var>(96 \times 98 \times 95) = 893760</var>

<var>4</var>-th term: <var>(98 \times 95 \times 100) = 931000</var>

<var>5</var>-th term: <var>(95 \times 100 \times 20) = 190000</var>

Sample Input 2

3 2
1001 869120 1001

Sample Output 2

No

Note that the output should be No if the grade for the <var>3</var>-rd term is equal to the grade for the <var>2</var>-nd term.

Sample Input 3

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

Sample Output 3

Yes
Yes
No
Yes
Yes
No
Yes
Yes

fn solution() {
    let (n, k): (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(),
        )
    };
    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()
    };

    for i in k..n {
        if a[i - k] < a[i] {
            println!("Yes");
        } else {
            println!("No");
        }
    }
}


The girl named Masha was walking in the forest and found a complete binary tree of height $$$n$$$ and a permutation $$$p$$$ of length $$$m=2^n$$$.A complete binary tree of height $$$n$$$ is a rooted tree such that every vertex except the leaves has exactly two sons, and the length of the path from the root to any of the leaves is $$$n$$$. The picture below shows the complete binary tree for $$$n=2$$$.A permutation is an array consisting of $$$n$$$ different integers from $$$1$$$ to $$$n$$$. For example, [$$$2,3,1,5,4$$$] is a permutation, but [$$$1,2,2$$$] is not ($$$2$$$ occurs twice), and [$$$1,3,4$$$] is also not a permutation ($$$n=3$$$, but there is $$$4$$$ in the array).Let's enumerate $$$m$$$ leaves of this tree from left to right. The leaf with the number $$$i$$$ contains the value $$$p_i$$$ ($$$1 \le i \le m$$$).For example, if $$$n = 2$$$, $$$p = [3, 1, 4, 2]$$$, the tree will look like this:  Masha considers a tree beautiful if the values in its leaves are ordered from left to right in increasing order.In one operation, Masha can choose any non-leaf vertex of the tree and swap its left and right sons (along with their subtrees).For example, if Masha applies this operation to the root of the tree discussed above, it will take the following form:  Help Masha understand if she can make a tree beautiful in a certain number of operations. If she can, then output the minimum number of operations to make the tree beautiful.

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

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

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

        let mut interval = 1;
        let mut ans = 0;
        let mut ansflag = 1;

        for _i in 0..32 {
            if interval == n {
                break;
            }
            if ansflag == 0 {
                break;
            }

            let mut now = 0;
            while now < n {
                if p[now] > p[now + interval] {
                    ans += 1;
                    p.swap(now, now + interval);
                }
                if p[now + interval] - p[now] != interval {
                    ansflag = 0;
                    break;
                }

                now += interval * 2;
            }
            interval *= 2;
        }

        if ansflag == 0 {
            println!("{}", -1);
        } else {
            println!("{}", ans);
        }
    }
}


A sequence of non-negative integers $$$a_1, a_2, \dots, a_n$$$ is called growing if for all $$$i$$$ from $$$1$$$ to $$$n - 1$$$ all ones (of binary representation) in $$$a_i$$$ are in the places of ones (of binary representation) in $$$a_{i + 1}$$$ (in other words, $$$a_i \:\&\: a_{i + 1} = a_i$$$, where $$$\&$$$ denotes bitwise AND). If $$$n = 1$$$ then the sequence is considered growing as well.For example, the following four sequences are growing:   $$$[2, 3, 15, 175]$$$ — in binary it's $$$[10_2, 11_2, 1111_2, 10101111_2]$$$;  $$$[5]$$$ — in binary it's $$$[101_2]$$$;  $$$[1, 3, 7, 15]$$$ — in binary it's $$$[1_2, 11_2, 111_2, 1111_2]$$$;  $$$[0, 0, 0]$$$ — in binary it's $$$[0_2, 0_2, 0_2]$$$. The following three sequences are non-growing:   $$$[3, 4, 5]$$$ — in binary it's $$$[11_2, 100_2, 101_2]$$$;  $$$[5, 4, 3]$$$ — in binary it's $$$[101_2, 100_2, 011_2]$$$;  $$$[1, 2, 4, 8]$$$ — in binary it's $$$[0001_2, 0010_2, 0100_2, 1000_2]$$$. Consider two sequences of non-negative integers $$$x_1, x_2, \dots, x_n$$$ and $$$y_1, y_2, \dots, y_n$$$. Let's call this pair of sequences co-growing if the sequence $$$x_1 \oplus y_1, x_2 \oplus y_2, \dots, x_n \oplus y_n$$$ is growing where $$$\oplus$$$ denotes bitwise XOR.You are given a sequence of integers $$$x_1, x_2, \dots, x_n$$$. Find the lexicographically minimal sequence $$$y_1, y_2, \dots, y_n$$$ such that sequences $$$x_i$$$ and $$$y_i$$$ are co-growing.The sequence $$$a_1, a_2, \dots, a_n$$$ is lexicographically smaller than the sequence $$$b_1, b_2, \dots, b_n$$$ if there exists $$$1 \le k \le n$$$ such that $$$a_i = b_i$$$ for any $$$1 \le i < k$$$ but $$$a_k < b_k$$$.

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 mut it = s.split_whitespace().map(|s| s.parse::<u32>().unwrap());

        let mut px = it.next().unwrap();
        let mut py = 0;
        write!(&mut output, "0 ").unwrap();

        for x in it {
            let y = !x & (px ^ py);
            write!(&mut output, "{} ", y).unwrap();

            px = x;
            py = y;
        }

        writeln!(&mut output).unwrap();
    }
}


Score : <var>400</var> points

Problem Statement

Given is a string <var>S</var> consisting of digits from 1 through 9.

Find the number of pairs of integers <var>(i,j)</var> (<var>1 ≤ i ≤ j ≤ |S|</var>) that satisfy the following condition:

Condition: In base ten, the <var>i</var>-th through <var>j</var>-th characters of <var>S</var> form an integer that is a multiple of <var>2019</var>.

Constraints

<var>1 ≤ |S| ≤ 200000</var>

<var>S</var> is a string consisting of digits from 1 through 9.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the number of pairs of integers <var>(i,j)</var> (<var>1 ≤ i ≤ j ≤ |S|</var>) that satisfy the condition.

Sample Input 1

1817181712114

Sample Output 1

3

Three pairs - <var>(1,5)</var>, <var>(5,9)</var>, and <var>(9,13)</var> - satisfy the condition.

Sample Input 2

14282668646

Sample Output 2

2

Sample Input 3

2119

Sample Output 3

0

No pairs satisfy the condition.

int solution(void) {
  long long dp[2020] = {0};
  long long result = 0;
  char s[200010];
  scanf("%s", s);
  int n = strlen(s);

  long long tmp = 1;
  long long sum = 0;
  for (int i = n - 1; i >= 0; i--) {
    sum += (tmp * (long long)(s[i] - '0')) % 2019;
    sum %= 2019;
    dp[sum]++;
    tmp = (tmp * 10) % 2019;
  }
  result = dp[0];
  for (int i = 0; i < 2019; i++) {
    result += dp[i] * (dp[i] - 1) / 2;
  }
  printf("%lld", result);

  return 0;
}

fn solution() {
    let mut s: String = String::new();
    stdin().read_line(&mut s).ok();
    let s: Vec<char> = s.trim().chars().collect();

    let mut counts: Vec<usize> = vec![0; 2019];
    counts[0] += 1;

    let mut base = 1;
    let mut temp_mod = 0;
    for &s_i in s.iter().rev() {
        temp_mod = (temp_mod + (s_i as usize - 48) * base) % 2019;
        base = (base * 10) % 2019;
        if s_i != '0' {
            counts[temp_mod] += 1;
        }
    }

    let mut res = 0;
    for counts_i in counts {
        if counts_i > 1 {
            res += counts_i * (counts_i - 1) / 2;
        }
    }
    println!("{}", res);
}


Score : <var>300</var> points

Problem Statement

You are given an integer <var>N</var>. Among the integers between <var>1</var> and <var>N</var> (inclusive), how many Shichi-Go-San numbers (literally "Seven-Five-Three numbers") are there?

Here, a Shichi-Go-San number is a positive integer that satisfies the following condition:

When the number is written in base ten, each of the digits 7, 5 and 3 appears at least once, and the other digits never appear.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of the Shichi-Go-San numbers between <var>1</var> and <var>N</var> (inclusive).

Sample Input 1

575

Sample Output 1

4

There are four Shichi-Go-San numbers not greater than <var>575</var>: <var>357, 375, 537</var> and <var>573</var>.

Sample Input 2

3600

Sample Output 2

13

There are <var>13</var> Shichi-Go-San numbers not greater than <var>3600</var>: the above four numbers, <var>735, 753, 3357, 3375, 3537, 3557, 3573, 3575</var> and <var>3577</var>.

Sample Input 3

999999999

Sample Output 3

26484

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

    let mut ans = 0;
    let mut q = std::collections::VecDeque::new();
    q.push_back(3usize);
    q.push_back(5);
    q.push_back(7);

    while let Some(v) = q.pop_front() {
        if v > n {
            break;
        }

        let mut c3 = false;
        let mut c5 = false;
        let mut c7 = false;
        let mut t = v;
        while t > 0 {
            match t % 10 {
                3 => c3 = true,
                5 => c5 = true,
                7 => c7 = true,
                _ => continue,
            }
            t /= 10;
        }
        if c3 && c5 && c7 {
            ans += 1;
        }
        q.push_back(v * 10 + 3);
        q.push_back(v * 10 + 5);
        q.push_back(v * 10 + 7);
    }

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


Score : <var>500</var> points

Problem Statement

You have a string <var>A = A_1 A_2 ... A_n</var> consisting of lowercase English letters.

You can choose any two indices <var>i</var> and <var>j</var> such that <var>1 \leq i \leq j \leq n</var> and reverse substring <var>A_i A_{i+1} ... A_j</var>.

You can perform this operation at most once.

How many different strings can you obtain?

Constraints

<var>1 \leq |A| \leq 200,000</var>

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

Input

Input is given from Standard Input in the following format:

<var>A</var>

Output

Print the number of different strings you can obtain by reversing any substring in <var>A</var> at most once.

Sample Input 1

aatt

Sample Output 1

5

You can obtain aatt (don't do anything), atat (reverse <var>A[2..3]</var>), atta (reverse <var>A[2..4]</var>), ttaa (reverse <var>A[1..4]</var>) and taat (reverse <var>A[1..3]</var>).

Sample Input 2

xxxxxxxxxx

Sample Output 2

1

Whatever substring you reverse, you'll always get xxxxxxxxxx.

Sample Input 3

abracadabra

Sample Output 3

44

int solution(void) {
  char str[200000];
  scanf("%s", str);
  long long length = strlen(str);
  char abc[26] = "abcdefghijklmnopqrstuvwxyz";
  long long count[26];
  long long temp = 0;
  for (int i = 0; i < 26; i++) {
    for (int j = 0; j < length; j++) {
      if (str[j] == abc[i]) {
        temp++;
      }
    }
    count[i] = temp;
    temp = 0;
  }
  long long sum = 0;
  for (int i = 0; i < 26; i++) {
    if (count[i] > 1) {
      sum += count[i] * (count[i] - 1) / 2;
    }
  }

  printf("%lld", (length * (length - 1) / 2) + 1 - sum);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut buf_it = buf.split_whitespace();
    let A = buf_it.next().unwrap().chars().collect::<Vec<_>>();

    let N = A.len();
    let mut cnt = HashMap::new();
    let mut ans = 1;

    cnt.insert(A[0], 1);
    for i in 1..N {
        let n = *cnt.get(&A[i]).unwrap_or(&0);
        ans += i - n;
        cnt.insert(A[i], n + 1);
    }
    println!("{}", ans);
}


Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j < i)

int solution(int argc, char const *argv[]) {
  int olegi[26];
  int igori[26];
  int iter;
  for (iter = 0; iter < 26; iter++) {
    olegi[iter] = 0;
    igori[iter] = 0;
  }

  int oleg[300000];
  int igor[300000];
  int len = 0;
  char ch;
  scanf("%c", &ch);
  while (ch != '\n' && ch != '\0') {
    len++;
    oleg[len - 1] = ch;
    olegi[(int)ch - 97]++;
    scanf("%c", &ch);
  }

  len = 0;
  scanf("%c", &ch);
  while (ch != '\n' && ch != '\0') {
    len++;
    igor[len - 1] = ch;
    igori[(int)ch - 97]++;
    scanf("%c", &ch);
  }

  int i = 0;
  int j = 1;
  int k = 0;
  while (olegi[k] == 0 && k < 26) {
    k++;
  }
  int m = 25;
  while (igori[m] == 0 && m >= 0) {
    m--;
  }
  int turn = 0;
  int name[300000];
  int flag = 0;
  while (i < len) {
    if (j >= len) {
      if (turn == 0) {
        name[i] = k;
        olegi[k]--;
        while (olegi[k] == 0 && k < 26) {
          k++;
        }
      } else {
        name[i] = m;
        igori[m]--;
        while (igori[m] == 0 && m >= 0) {
          m--;
        }
      }
      i = j;
    }
    if (turn == 0) {
      if (k < m) {
        name[i] = k;
        olegi[k]--;
        while (olegi[k] == 0 && k < 26) {
          k++;
        }
        i = j;
      } else {
        if ((len - j) % 2 == 0) {
          flag = 1;
        } else {
          flag = 2;
        }
        break;
      }
      turn = 1;
    } else {
      if (m > k) {
        name[i] = m;
        igori[m]--;
        while (igori[m] == 0 && m >= 0) {
          m--;
        }
        i = j;
      } else {
        if ((len - j) % 2 == 0) {
          flag = 2;
        } else {
          flag = 1;
        }
        break;
      }
      turn = 0;
    }
    j++;
  }
  if (flag == 1) {
    while (i < len) {
      name[i] = k;
      olegi[k]--;
      name[j] = m;
      igori[m]--;
      while (olegi[k] == 0 && k < 26) {
        k++;
      }
      while (igori[m] == 0 && m >= 0) {
        m--;
      }
      i = j;
      j++;
      i = j;
      j++;
    }
  }
  if (flag == 2) {
    while (i < len) {
      name[i] = m;
      olegi[k]--;
      name[j] = k;
      igori[m]--;
      while (olegi[k] == 0 && k < 26) {
        k++;
      }
      while (igori[m] == 0 && m >= 0) {
        m--;
      }
      i = j;
      j++;
      i = j;
      j++;
    }
  }
  i = 0;
  while (i < len) {
    printf("%c", name[i] + 'a');
    i++;
  }
  printf("\n");
  return 0;
}

fn solution() {
    let mut s: Vec<char> = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().chars().collect()
    };

    let mut t: Vec<char> = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().chars().collect()
    };

    let n = s.len();

    s.sort();
    t.sort();

    let q = n.div_ceil(2);

    s.truncate(q);

    t.reverse();
    t.truncate(n / 2);

    let mut s = VecDeque::from(s);
    let mut t = VecDeque::from(t);

    let mut ans = vec!['a'; n];

    let mut i = 0;
    let mut j = n - 1;

    for k in 0..n {
        let cc = match (s.front(), t.front()) {
            (Some(s), Some(t)) if s >= t => true,
            _ => false,
        };

        let r = match k % 2 {
            0 => &mut s,
            1 => &mut t,
            _ => &mut s,
        };

        if cc {
            ans[j] = r.pop_back().unwrap();
            j -= 1;
        } else {
            ans[i] = r.pop_front().unwrap();
            i += 1;
        }
    }

    for c in ans {
        print!("{}", c);
    }

    println!();
}


You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room.The building consists of n towers, h floors each, where the towers are labeled from 1 to n, the floors are labeled from 1 to h. There is a passage between any two adjacent towers (two towers i and i + 1 for all i: 1 ≤ i ≤ n - 1) on every floor x, where a ≤ x ≤ b. It takes exactly one minute to walk between any two adjacent floors of a tower, as well as between any two adjacent towers, provided that there is a passage on that floor. It is not permitted to leave the building. The picture illustrates the first example. You have given k pairs of locations (ta, fa), (tb, fb): floor fa of tower ta and floor fb of tower tb. For each pair you need to determine the minimum walking time between these locations.

int solution() {
  int n;
  int h;
  int a;
  int b;
  int k;
  int ta[10005];
  int ha[10005];
  int tb[10005];
  int hb[10005];
  int i;
  scanf("%d%d%d%d%d", &n, &h, &a, &b, &k);
  for (i = 0; i < k; i++) {
    scanf("%d%d%d%d", &ta[i], &ha[i], &tb[i], &hb[i]);
  }
  for (i = 0; i < k; i++) {
    if (ta[i] == tb[i]) {
      if (ha[i] > hb[i]) {
        printf("%d\n", ha[i] - hb[i]);
      } else {
        printf("%d\n", hb[i] - ha[i]);
      }
    }
    if (ta[i] != tb[i] && ha[i] >= a && ha[i] <= b) {
      if (ta[i] > tb[i]) {
        if (ha[i] > hb[i]) {
          printf("%d\n", ta[i] - tb[i] + ha[i] - hb[i]);
        } else {
          printf("%d\n", ta[i] - tb[i] + hb[i] - ha[i]);
        }
      } else {
        if (ha[i] > hb[i]) {
          printf("%d\n", tb[i] - ta[i] + ha[i] - hb[i]);
        } else {
          printf("%d\n", tb[i] - ta[i] + hb[i] - ha[i]);
        }
      }
    }
    if (ta[i] != tb[i] && ha[i] < a) {
      if (ta[i] > tb[i]) {
        if (a > hb[i]) {
          printf("%d\n", a - ha[i] + ta[i] - tb[i] + a - hb[i]);
        } else {
          printf("%d\n", a - ha[i] + ta[i] - tb[i] + hb[i] - a);
        }
      } else {
        if (hb[i] > a) {
          printf("%d\n", a - ha[i] + tb[i] - ta[i] - a + hb[i]);
        } else {
          printf("%d\n", a - ha[i] + tb[i] - ta[i] - hb[i] + a);
        }
      }
    }
    if (ta[i] != tb[i] && ha[i] > b) {
      if (ta[i] > tb[i]) {
        if (b > hb[i]) {
          printf("%d\n", -b + ha[i] + ta[i] - tb[i] + b - hb[i]);
        } else {
          printf("%d\n", -b + ha[i] + ta[i] - tb[i] - b + hb[i]);
        }
      } else {
        if (b < hb[i]) {
          printf("%d\n", -b + ha[i] + tb[i] - ta[i] - b + hb[i]);
        } else {
          printf("%d\n", -b + ha[i] + tb[i] - ta[i] - hb[i] + b);
        }
      }
    }
  }
  return 0;
}

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

    io::stdin().read_line(&mut line).unwrap();
    let mut line_words = line.split_whitespace();
    let _n: i32 = line_words.next().unwrap().parse().unwrap();
    let _h: i32 = line_words.next().unwrap().parse().unwrap();
    let a: i32 = line_words.next().unwrap().parse().unwrap();
    let b: i32 = line_words.next().unwrap().parse().unwrap();
    let k: i32 = line_words.next().unwrap().parse().unwrap();
    for _ in 0..k {
        let mut res;
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let mut line_words = line.split_whitespace();
        let ta: i32 = line_words.next().unwrap().parse().unwrap();
        let fa: i32 = line_words.next().unwrap().parse().unwrap();
        let tb: i32 = line_words.next().unwrap().parse().unwrap();
        let fb: i32 = line_words.next().unwrap().parse().unwrap();

        if ta == tb {
            res = (fa - fb).abs();
        } else {
            res = (ta - tb).abs();
            if fa < a && fb < a {
                res += 2 * a - fa - fb;
            } else if fa > b && fb > b {
                res += fa + fb - 2 * b;
            } else {
                res += (fa - fb).abs();
            }
        }
        println!("{}", res);
    }
}


There are $$$n$$$ piranhas with sizes $$$a_1, a_2, \ldots, a_n$$$ in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the aquarium (except itself, of course). Other piranhas will do nothing while the dominant piranha will eat them.Because the aquarium is pretty narrow and long, the piranha can eat only one of the adjacent piranhas during one move. Piranha can do as many moves as it needs (or as it can). More precisely:   The piranha $$$i$$$ can eat the piranha $$$i-1$$$ if the piranha $$$i-1$$$ exists and $$$a_{i - 1} < a_i$$$.  The piranha $$$i$$$ can eat the piranha $$$i+1$$$ if the piranha $$$i+1$$$ exists and $$$a_{i + 1} < a_i$$$. When the piranha $$$i$$$ eats some piranha, its size increases by one ($$$a_i$$$ becomes $$$a_i + 1$$$).Your task is to find any dominant piranha in the aquarium or determine if there are no such piranhas.Note that you have to find any (exactly one) dominant piranha, you don't have to find all of them.For example, if $$$a = [5, 3, 4, 4, 5]$$$, then the third piranha can be dominant. Consider the sequence of its moves:   The piranha eats the second piranha and $$$a$$$ becomes $$$[5, \underline{5}, 4, 5]$$$ (the underlined piranha is our candidate).  The piranha eats the third piranha and $$$a$$$ becomes $$$[5, \underline{6}, 5]$$$.  The piranha eats the first piranha and $$$a$$$ becomes $$$[\underline{7}, 5]$$$.  The piranha eats the second piranha and $$$a$$$ becomes $$$[\underline{8}]$$$. You have to answer $$$t$$$ independent test cases.

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

  for (int i = 0; i < t; i++) {
    int n;
    scanf("%i", &n);

    int size[n];
    int max = 0;

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

      if (size[j] > max) {
        max = size[j];
      }
    }

    int yes = 0;
    for (int j = 0; j < n; j++) {
      if (size[j] == max) {
        if ((j == 0 && size[j] > size[j + 1]) ||
            (j == n - 1 && size[j] > size[j - 1]) ||
            ((j != 0 && j != n - 1) &&
             (size[j] > size[j - 1] || size[j] > size[j + 1]))) {
          printf("%i\n", j + 1);
          yes++;
          break;
        }
      }
    }

    if (yes == 0) {
      printf("-1\n");
    }
  }

  return 0;
}

fn solution() {
    let mut input = "".split_ascii_whitespace();
    let mut read = || loop {
        if let Some(word) = input.next() {
            break word;
        }
        input = {
            let mut input = "".to_owned();
            io::stdin().read_line(&mut input).unwrap();
            if input.is_empty() {
                panic!("reached EOF");
            }
            Box::leak(input.into_boxed_str()).split_ascii_whitespace()
        };
    };

    let t = read!(usize);
    for _ in 0..t {
        let n = read!(usize);
        let mut a = vec![0; n];
        for i in 0..n {
            a[i] = read!(usize);
        }

        let mut r = n + 1;
        let mut m = 0;
        for i in 0..n {
            let c = a[i];
            if c < m {
                continue;
            }
            m = c;
            if i > 0 && a[i - 1] < c {
                r = i + 1;
            } else if i < n - 1 && a[i + 1] < c {
                r = i + 1;
            }
        }

        println!("{}", if r > n { -1 } else { r as i64 });
    }
}


Alexey is travelling on a train. Unfortunately, due to the bad weather, the train moves slower that it should!Alexey took the train at the railroad terminal. Let's say that the train starts from the terminal at the moment $$$0$$$. Also, let's say that the train will visit $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$ along its way, and that Alexey destination is the station $$$n$$$.Alexey learned from the train schedule $$$n$$$ integer pairs $$$(a_i, b_i)$$$ where $$$a_i$$$ is the expected time of train's arrival at the $$$i$$$-th station and $$$b_i$$$ is the expected time of departure.Also, using all information he has, Alexey was able to calculate $$$n$$$ integers $$$tm_1, tm_2, \dots, tm_n$$$ where $$$tm_i$$$ is the extra time the train need to travel from the station $$$i - 1$$$ to the station $$$i$$$. Formally, the train needs exactly $$$a_i - b_{i-1} + tm_i$$$ time to travel from station $$$i - 1$$$ to station $$$i$$$ (if $$$i = 1$$$ then $$$b_0$$$ is the moment the train leave the terminal, and it's equal to $$$0$$$).The train leaves the station $$$i$$$, if both conditions are met:   it's on the station for at least $$$\left\lceil \frac{b_i - a_i}{2} \right\rceil$$$ units of time (division with ceiling);  current time $$$\ge b_i$$$. Since Alexey spent all his energy on prediction of time delays, help him to calculate the time of arrival at the station $$$n$$$.

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 z = Vec::with_capacity(n);

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

            z.push((a, b, 0));
        }

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

        for (p, x) in z.iter_mut().zip(it) {
            p.2 = x;
        }

        let mut sch = 0;
        let mut act = 0;
        let mut arr = 0;
        for (a, b, tm) in z {
            arr = act + a - sch + tm;
            let l = std::cmp::max(b, arr + (b - a).div_ceil(2));

            act = l;
            sch = b;
        }

        let ans = arr;

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


You are given a permutation $$$a$$$ consisting of $$$n$$$ numbers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array in which each element from $$$1$$$ to $$$n$$$ occurs exactly once).You can perform the following operation: choose some subarray (contiguous subsegment) of $$$a$$$ and rearrange the elements in it in any way you want. But this operation cannot be applied to the whole array.For example, if $$$a = [2, 1, 4, 5, 3]$$$ and we want to apply the operation to the subarray $$$a[2, 4]$$$ (the subarray containing all elements from the $$$2$$$-nd to the $$$4$$$-th), then after the operation, the array can become $$$a = [2, 5, 1, 4, 3]$$$ or, for example, $$$a = [2, 1, 5, 4, 3]$$$.Your task is to calculate the minimum number of operations described above to sort the permutation $$$a$$$ in ascending order.

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 r = 0;

    for (int i = 0; i < n; i++) {
      if (arr[i] != i + 1) {
        r = -1;
        break;
      }
    }

    if (r < 0) {
      if (arr[0] == 1 || arr[n - 1] == n) {
        printf("%d\n", 1);
      } else if (arr[0] == n && arr[n - 1] == 1) {
        printf("%d\n", 3);
      } else {
        printf("%d\n", 2);
      }
    } else {
      printf("%d\n", 0);
    }
  }

  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(|x| x.unwrap());

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

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

        let s = lines.next().unwrap();
        let a = s
            .split_whitespace()
            .map(|s| s.parse::<usize>().unwrap())
            .collect::<Vec<_>>();

        let ans = if (0..n - 1).all(|i| a[i] < a[i + 1]) {
            0
        } else if a[0] == 1 || a[n - 1] == n {
            1
        } else if a[0] == n && a[n - 1] == 1 {
            3
        } else {
            2
        };

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


Recall that a permutation of length $$$n$$$ is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once.For a fixed positive integer $$$d$$$, let's define the cost of the permutation $$$p$$$ of length $$$n$$$ as the number of indices $$$i$$$ $$$(1 \le i < n)$$$ such that $$$p_i \cdot d = p_{i + 1}$$$.For example, if $$$d = 3$$$ and $$$p = [5, 2, 6, 7, 1, 3, 4]$$$, then the cost of such a permutation is $$$2$$$, because $$$p_2 \cdot 3 = p_3$$$ and $$$p_5 \cdot 3 = p_6$$$.Your task is the following one: for a given value $$$n$$$, find the permutation of length $$$n$$$ and the value $$$d$$$ with maximum possible cost (over all ways to choose the permutation and $$$d$$$). If there are multiple answers, then print any of them.

int solution() {
  int t = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int n = 0;
    scanf("%d", &n);
    printf("2\n");
    int a[n + 1];
    memset(a, 0, sizeof(a) + 1);
    int res[n + 1];
    int index = 0;
    int next = 1;
    while (1) {
      int j = next;
      int isfirst = 1;
      int ok = 1;
      while (j <= n) {
        if (a[j] == 0) {
          if (isfirst) {
            isfirst = 0;
            next = j;
          }
          a[j] = 1;
          res[index++] = j;
          j = j * 2;
          ok = 0;
        } else {
          j++;
        }
      }
      if (ok) {
        break;
      }
    }
    for (int j = 0; j < n; j++) {
      printf("%d ", res[j]);
    }
    printf("\n");
  }
}

fn solution() {
    input! {
        name = reader,
        tests: usize
    }
    for _ in 0..tests {
        input! {
            use reader,
            n: usize
        }
        println!("2");
        let mut a = vec![];
        for mut i in 1..=n {
            if i % 2 == 1 {
                while i <= n {
                    a.push(i);
                    i *= 2;
                }
            }
        }
        for i in a {
            print!("{} ", i);
        }
        println!();
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi has <var>N</var> blue cards and <var>M</var> red cards.
A string is written on each card. The string written on the <var>i</var>-th blue card is <var>s_i</var>, and the string written on the <var>i</var>-th red card is <var>t_i</var>.

Takahashi will now announce a string, and then check every card. Each time he finds a blue card with the string announced by him, he will earn <var>1</var> yen (the currency of Japan); each time he finds a red card with that string, he will lose <var>1</var> yen.

Here, we only consider the case where the string announced by Takahashi and the string on the card are exactly the same. For example, if he announces atcoder, he will not earn money even if there are blue cards with atcoderr, atcode, btcoder, and so on. (On the other hand, he will not lose money even if there are red cards with such strings, either.)

At most how much can he earn on balance?

Note that the same string may be written on multiple cards.

Constraints

<var>N</var> and <var>M</var> are integers.

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

<var>s_1, s_2, ..., s_N, t_1, t_2, ..., t_M</var> are all strings of lengths between <var>1</var> and <var>10</var> (inclusive) consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>s_1</var>
<var>s_2</var>
<var>:</var>
<var>s_N</var>
<var>M</var>
<var>t_1</var>
<var>t_2</var>
<var>:</var>
<var>t_M</var>

Output

If Takahashi can earn at most <var>X</var> yen on balance, print <var>X</var>.

Sample Input 1

3
apple
orange
apple
1
grape

Sample Output 1

2

He can earn <var>2</var> yen by announcing apple.

Sample Input 2

3
apple
orange
apple
5
apple
apple
apple
apple
apple

Sample Output 2

1

If he announces apple, he will lose <var>3</var> yen. If he announces orange, he can earn <var>1</var> yen.

Sample Input 3

1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort

Sample Output 3

0

If he announces voldemort, he will lose <var>9</var> yen. If he announces orange, for example, he can avoid losing a yen.

Sample Input 4

6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue

Sample Output 4

1

int solution(void) {

  static int n;
  static int m;
  static int ans = 0;
  static int tmp = 0;
  static char s[120][15];
  static char t[120][15];

  scanf("%d", &n);

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

    scanf("%s", s[i]);
  }

  scanf("%d", &m);

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

    scanf("%s", t[i]);
  }

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

    tmp = 0;

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

      if (strcmp(s[i], s[j]) == 0) {

        tmp++;
      }
    }

    for (int j = 0; j < m; j++) {

      if (strcmp(s[i], t[j]) == 0) {

        tmp--;
      }
    }

    if (ans < tmp) {

      ans = tmp;
    }
  }

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

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let n: usize = s.trim().parse().unwrap();
    let mut h: HashMap<String, isize> = HashMap::new();
    for _ in 0..n {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let x = match h.get(&s) {
            Some(x) => *x,
            None => 0,
        };
        h.insert(s, x + 1);
    }

    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let m: usize = s.trim().parse().unwrap();
    for _ in 0..m {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let x = match h.get(&s) {
            Some(x) => *x,
            None => 0,
        };
        h.insert(s, std::cmp::max(-1, x - 1));
    }

    println!("{:?}", std::cmp::max(h.values().max().unwrap(), &0));
}


Score : <var>400</var> points

Problem Statement

On a two-dimensional plane, there are <var>N</var> red points and <var>N</var> blue points.
The coordinates of the <var>i</var>-th red point are <var>(a_i, b_i)</var>, and the coordinates of the <var>i</var>-th blue point are <var>(c_i, d_i)</var>.

A red point and a blue point can form a friendly pair when, the <var>x</var>-coordinate of the red point is smaller than that of the blue point, and the <var>y</var>-coordinate of the red point is also smaller than that of the blue point.

At most how many friendly pairs can you form? Note that a point cannot belong to multiple pairs.

Constraints

All input values are integers.

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

<var>0 \leq a_i, b_i, c_i, d_i < 2N</var>

<var>a_1, a_2, ..., a_N, c_1, c_2, ..., c_N</var> are all different.

<var>b_1, b_2, ..., b_N, d_1, d_2, ..., d_N</var> are all different.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>b_1</var>
<var>a_2</var> <var>b_2</var>
<var>:</var>
<var>a_N</var> <var>b_N</var>
<var>c_1</var> <var>d_1</var>
<var>c_2</var> <var>d_2</var>
<var>:</var>
<var>c_N</var> <var>d_N</var>

Output

Print the maximum number of friendly pairs.

Sample Input 1

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

Sample Output 1

2

For example, you can pair <var>(2, 0)</var> and <var>(4, 2)</var>, then <var>(3, 1)</var> and <var>(5, 5)</var>.

Sample Input 2

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

Sample Output 2

2

For example, you can pair <var>(0, 0)</var> and <var>(2, 3)</var>, then <var>(1, 1)</var> and <var>(3, 4)</var>.

Sample Input 3

2
2 2
3 3
0 0
1 1

Sample Output 3

0

It is possible that no pair can be formed.

Sample Input 4

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

Sample Output 4

5

Sample Input 5

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

Sample Output 5

4

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let mut r: Vec<(i16, i16)> = (0..n)
        .map(|_| {
            (
                s.next().unwrap().parse().unwrap(),
                s.next().unwrap().parse().unwrap(),
            )
        })
        .collect();
    let mut b: Vec<(i16, i16)> = (0..n)
        .map(|_| {
            (
                s.next().unwrap().parse().unwrap(),
                s.next().unwrap().parse().unwrap(),
            )
        })
        .collect();
    r.sort();
    b.sort();
    let mut ans = 0;
    for (x, y) in b {
        let mut maxy = -1;
        let mut j = 0;
        for (i, r) in r.iter().take_while(|r| r.0 < x).enumerate() {
            if r.1 < y && r.1 > maxy {
                maxy = r.1;
                j = i;
            }
        }
        if maxy >= 0 {
            r[j].1 = std::i16::MAX;
            ans += 1;
        }
    }
    println!("{}", ans);
}


Timur likes his name. As a spelling of his name, he allows any permutation of the letters of the name. For example, the following strings are valid spellings of his name: Timur, miurT, Trumi, mriTu. Note that the correct spelling must have uppercased T and lowercased other letters.Today he wrote string $$$s$$$ of length $$$n$$$ consisting only of uppercase or lowercase Latin letters. He asks you to check if $$$s$$$ is the correct spelling of his name.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    char str[101];
    int n;
    scanf("%d", &n);
    int cnt1 = 0;
    int cnt2 = 0;
    int cnt3 = 0;
    int cnt4 = 0;
    int cnt5 = 0;
    int cnt6 = 0;
    scanf("%s", str);
    for (int i = 0; i < n; i++) {
      if (str[i] == 'T') {
        cnt1++;
      } else if (str[i] == 'i') {
        cnt2++;
      } else if (str[i] == 'm') {
        cnt3++;
      } else if (str[i] == 'u') {
        cnt4++;
      } else if (str[i] == 'r') {
        cnt5++;
      } else {
        cnt6++;
      }
    }

    if ((cnt1 + cnt2 + cnt3 + cnt4 + cnt5 + cnt6) == 5 && (cnt1 == 1) &&
        (cnt2 == 1) && (cnt3 == 1) && (cnt4 == 1) && (cnt6 == 0) &&
        (cnt5 == 1)) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }

  return 0;
}

fn solution() {
    let mut number_of_names = String::new();
    io::stdin()
        .read_line(&mut number_of_names)
        .expect("Не получилось прочитать строку");
    let number_of_names: usize = number_of_names
        .trim()
        .parse()
        .expect("Пожалуйста, наберите число!");

    let mut names_vec: Vec<String> = Vec::new();
    let mut names_length_vec: Vec<usize> = Vec::new();
    for _i in 0usize..number_of_names {
        let mut length_of_name = String::new();
        io::stdin()
            .read_line(&mut length_of_name)
            .expect("Не получилось прочитать строку");
        let length_of_name: usize = length_of_name
            .trim()
            .parse()
            .expect("Пожалуйста, наберите число!");
        names_length_vec.push(length_of_name);

        let mut name = String::new();
        io::stdin()
            .read_line(&mut name)
            .expect("Не получилось прочитать строку");
        names_vec.push(name);
    }

    for _i in 0usize..number_of_names {
        let timur_name: String = String::from("Timur");
        if names_length_vec[_i] != 5 {
            println!("NO")
        } else {
            for character in timur_name.chars() {
                names_vec[_i] = names_vec[_i].replacen(character, "", 1);
            }
            if names_vec[_i].len() == 2 {
                println!("YES");
            } else {
                println!("NO");
            }
        }
    }
}


There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?

int solution() {
  int a = 0;
  int d = 0;
  int b = 0;
  int c[300] = {0};

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

  if (flag >= a || c[0] == 25) {
    printf("I become the guy.");
  } else {
    printf("Oh, my keyboard!");
  }

  return 0;
}

fn solution() {
    let mut b = String::new();
    let _ = stdin().read_line(&mut b);
    let n = b.trim_end().parse::<i32>().unwrap();

    b.clear();
    let _ = stdin().read_line(&mut b);
    let mut x = b
        .clone()
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .collect::<Vec<i32>>();
    x.remove(0);

    b.clear();
    let _ = stdin().read_line(&mut b);
    let mut y = b
        .clone()
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .collect::<Vec<i32>>();
    y.remove(0);

    let mut s = HashSet::new();
    for i in 1..n + 1 {
        s.insert(i);
    }
    for i in &x {
        s.remove(i);
    }
    for i in &y {
        s.remove(i);
    }
    if s.is_empty() {
        println!("I become the guy.");
    } else {
        println!("Oh, my keyboard!");
    }
}


Score : <var>600</var> points

Problem Statement

You are given a string <var>s</var> consisting of A, B and C.

Snuke wants to perform the following operation on <var>s</var> as many times as possible:

Choose a contiguous substring of <var>s</var> that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

<var>1 \leq |s| \leq 200000</var>

Each character of <var>s</var> is A, B and C.

Input

Input is given from Standard Input in the following format:

<var>s</var>

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6

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() < 3 {
        println!("{}", 0);
        return;
    }

    let mut ans = 0_i64;
    let mut i = 0;
    let mut cnt = 0;
    while i < s.len() - 1 {
        if s[i] == b'A' {
            cnt += 1;
            i += 1;
        } else if cnt > 0 && s[i] == b'B' && s[i + 1] == b'C' {
            ans += cnt;
            i += 2;
        } else {
            cnt = 0;
            i += 1;
        }
    }

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


Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?

int solution() {
  int nkids = 0;
  int fhight = 0;
  int swidth = 0;
  int hkids[1000] = {0};

  scanf("%d", &nkids);

  scanf("%d", &fhight);

  for (int i = 1; i <= nkids; i++) {
    scanf("%d", &hkids[i]);
  }
  for (int i = 1; i <= nkids; i++) {
    if ((hkids[i] <= fhight) && (hkids[i] >= 1)) {
      swidth += 1;
    } else if ((hkids[i] > fhight) && (hkids[i] <= (2 * fhight))) {
      swidth += 2;
    } else if (hkids[i] > (2 * fhight)) {
      printf("he is very high and this is wrong");
      break;
    }
  }
  printf("%d", swidth);
  return 0;
}

fn solution() {
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };

    let h = v[1];
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };
    println!(
        "{:?}",
        v.iter()
            .fold(0, |total, &i| if i > h { total + 2 } else { total + 1 })
    );
}


void solution(int arr[], int lo, int hi) {
  while (lo < hi) {

    int pivot = hi;

    int i = lo;
    int j = hi - 1;

    while (1) {
      while (arr[i] < arr[pivot]) {
        i++;
      }

      while (j > lo && arr[j] > arr[pivot]) {
        j--;
      }

      if (i >= j) {
        break;
      }
      if (arr[i] == arr[j]) {
        i++;
        j--;
      } else {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
      }
    }

    int temp = arr[i];
    arr[i] = arr[pivot];
    arr[pivot] = temp;

    int pivotIndex = i;

    if ((pivotIndex - lo) < (hi - pivotIndex)) {
      if (pivotIndex > lo) {
        quickSort(arr, lo, pivotIndex - 1);
      }

      lo = pivotIndex + 1;
    } else {
      quickSort(arr, pivotIndex + 1, hi);

      hi = pivotIndex - 1;
    }
  }
}

fn solution<T: Ord>(arr: &mut [T]) {
    if arr.len() <= 1 {
        return;
    }

    fn sort<T: Ord>(arr: &mut [T], mut lo: usize, mut hi: usize) {
        while lo < hi {
            let pivot = hi;
            let mut i = lo;
            let mut j = hi - 1;

            loop {
                while arr[i] < arr[pivot] {
                    i += 1;
                }

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

                if j == 0 || i >= j {
                    break;
                } else if arr[i] == arr[j] {
                    i += 1;
                    j -= 1;
                } else {
                    arr.swap(i, j);
                }
            }

            arr.swap(i, pivot);
            let pivot_idx = i;

            if pivot_idx - lo < hi - pivot_idx {
                if pivot_idx > 0 {
                    sort(arr, lo, pivot_idx - 1);
                }
                lo = pivot_idx + 1;
            } else {
                sort(arr, pivot_idx + 1, hi);
                hi = pivot_idx.saturating_sub(1);
            }
        }
    }

    sort(arr, 0, arr.len() - 1);
}


Score : <var>300</var> points

Problem Statement

<var>2N</var> players are running a competitive table tennis training on <var>N</var> tables numbered from <var>1</var> to <var>N</var>.

The training consists of rounds.
In each round, the players form <var>N</var> pairs, one pair per table.
In each pair, competitors play a match against each other.
As a result, one of them wins and the other one loses.

The winner of the match on table <var>X</var> plays on table <var>X-1</var> in the next round,
except for the winner of the match on table <var>1</var> who stays at table <var>1</var>.

Similarly, the loser of the match on table <var>X</var> plays on table <var>X+1</var> in the next round,
except for the loser of the match on table <var>N</var> who stays at table <var>N</var>.

Two friends are playing their first round matches on distinct tables <var>A</var> and <var>B</var>.
Let's assume that the friends are strong enough to win or lose any match at will.
What is the smallest number of rounds after which the friends can get to play a match against each other?

Constraints

<var>2 \leq N \leq 10^{18}</var>

<var>1 \leq A < B \leq N</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the smallest number of rounds after which the friends can get to play a match against each other.

Sample Input 1

5 2 4

Sample Output 1

1

If the first friend loses their match and the second friend wins their match, they will both move to table <var>3</var> and play each other in the next round.

Sample Input 2

5 2 3

Sample Output 2

2

If both friends win two matches in a row, they will both move to table <var>1</var>.

int solution(void) {
  long long int n = 0;
  long long int a = 0;
  long long int b = 0;
  long long int ans = 0;

  scanf("%lld %lld %lld", &n, &a, &b);

  if (a > b) {
    ans = a;
    a = b;
    b = ans;
  }

  if ((b - a) % 2 == 0) {
    ans = (b - a) / 2;
  } else if ((a + b - 1) <= n) {
    ans = (a + b - 1) / 2;
  } else {
    ans = (n - a + n - b + 1) / 2;
  }

  printf("%lld\n", ans);
  return 0;
}

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

    let c = b - a;
    if c.is_multiple_of(2) {
        println!("{}", c / 2);
    } else {
        let d = a + (b - a - 1) / 2;
        let e = (n - b) + 1 + (b - a - 1) / 2;
        println!("{}", min(d, e));
    }
}