Given a positive integer $$$n$$$. Find three distinct positive integers $$$a$$$, $$$b$$$, $$$c$$$ such that $$$a + b + c = n$$$ and $$$\operatorname{gcd}(a, b) = c$$$, where $$$\operatorname{gcd}(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.

fn solution() {
    use std::io::Write;
    let mut handle = std::io::BufWriter::new(std::io::stdout());
    let mut test_no = String::new();
    std::io::stdin().read_line(&mut test_no).unwrap();
    let test_no: u32 = test_no.trim().parse().unwrap();
    for _ in 0..test_no {
        let mut integer = String::new();
        std::io::stdin().read_line(&mut integer).unwrap();
        let integer: u32 = integer.trim().parse().unwrap();
        if (integer & 1) == 0 {
            let a = integer / 2;
            let b = a - 1;
            writeln!(handle, "{} {} {}", a, b, 1).ok();
        } else {
            let mut a = (integer - 1) / 2 + 1;
            let mut b = (integer - 1) / 2 - 1;
            if (a & 1) == 0 {
                a += 1;
                b -= 1;
            }
            writeln!(handle, "{} {} {}", a, b, 1).ok();
        }
    }
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>s</var> consisting of lowercase English letters. Extract all the characters in the odd-indexed positions and print the string obtained by concatenating them. Here, the leftmost character is assigned the index <var>1</var>.

Constraints

Each character in <var>s</var> is a lowercase English letter.

<var>1≤|s|≤10^5</var>

Input

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

<var>s</var>

Output

Print the string obtained by concatenating all the characters in the odd-numbered positions.

Sample Input 1

atcoder

Sample Output 1

acdr

Extract the first character a, the third character c, the fifth character d and the seventh character r to obtain acdr.

Sample Input 2

aaaa

Sample Output 2

aa

Sample Input 3

z

Sample Output 3

z

Sample Input 4

fukuokayamaguchi

Sample Output 4

fkoaaauh

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    println!(
        "{}",
        s.char_indices()
            .filter(|&(i, _)| i % 2 == 0)
            .map(|(_, c)| c)
            .collect::<String>()
    );
}


A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int len = 0;
    scanf("%d", &len);
    char number[len + 1];
    scanf("%s", number);
    number[len] = '\0';
    int spotted = 0;
    char result1[len + 1];
    char result2[len + 1];
    for (int j = 0; j < len; j++) {
      if (spotted == 1) {
        if (number[j] == '0') {
          result1[j] = '0';
          result2[j] = '0';
        } else if (number[j] == '1') {
          result1[j] = '0';
          result2[j] = '1';
        } else {
          result1[j] = '0';
          result2[j] = '2';
        }
      } else {
        if (number[j] == '0') {
          result1[j] = '0';
          result2[j] = '0';
        } else if (number[j] == '1') {
          spotted = 1;
          result1[j] = '1';
          result2[j] = '0';
        } else {
          result1[j] = '1';
          result2[j] = '1';
        }
      }
    }
    result1[len] = '\0';
    result2[len] = '\0';
    printf("%s\n%s\n", result1, result2);
  }
}

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

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

        let mut line = String::new();
        lock.read_line(&mut line).unwrap();

        let mut x: Vec<usize> = Vec::with_capacity(n);
        for i in line.trim().split("") {
            if !i.is_empty() {
                x.push(i.parse().unwrap());
            }
        }

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

        let mut first = false;
        for e in x {
            match e {
                2 => {
                    if !first {
                        a.push(1);
                        b.push(1);
                    } else {
                        a.push(0);
                        b.push(2);
                    }
                }
                0 => {
                    a.push(0);
                    b.push(0);
                }
                1 => {
                    if !first {
                        a.push(1);
                        b.push(0);
                    } else {
                        a.push(0);
                        b.push(1);
                    }

                    first = true;
                }
                _ => panic!(),
            }
        }

        println!(
            "{}",
            a.iter()
                .fold(String::new(), |acc, &x| { acc + &x.to_string() })
        );
        println!(
            "{}",
            b.iter()
                .fold(String::new(), |acc, &x| { acc + &x.to_string() })
        );
    }
}


A binary string is a string that consists of characters $$$0$$$ and $$$1$$$. A bi-table is a table that has exactly two rows of equal length, each being a binary string.Let $$$\operatorname{MEX}$$$ of a bi-table be the smallest digit among $$$0$$$, $$$1$$$, or $$$2$$$ that does not occur in the bi-table. For example, $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 0011\\ 1010 \end{bmatrix}$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ occur in the bi-table at least once. $$$\operatorname{MEX}$$$ for $$$\begin{bmatrix} 111\\ 111 \end{bmatrix}$$$ is $$$0$$$, because $$$0$$$ and $$$2$$$ do not occur in the bi-table, and $$$0 < 2$$$.You are given a bi-table with $$$n$$$ columns. You should cut it into any number of bi-tables (each consisting of consecutive columns) so that each column is in exactly one bi-table. It is possible to cut the bi-table into a single bi-table — the whole bi-table.What is the maximal sum of $$$\operatorname{MEX}$$$ of all resulting bi-tables can be?

fn solution() {
    let stdin = std::io::stdin();
    let mut string = String::new();
    stdin.read_line(&mut string).unwrap();
    for _ in 0..string.trim().parse::<usize>().unwrap() {
        string.clear();
        stdin.read_line(&mut string).unwrap();
        string.clear();
        stdin.read_line(&mut string).unwrap();
        let v1 = string
            .trim()
            .chars()
            .map(|f| f.to_digit(10).unwrap())
            .collect::<Vec<u32>>();
        string.clear();
        stdin.read_line(&mut string).unwrap();
        let v2 = string
            .trim()
            .chars()
            .map(|f| f.to_digit(10).unwrap())
            .collect::<Vec<u32>>();
        let mut prev = 3;
        let mut count = 0;
        for i in 0..v1.len() {
            if v1[i] != v2[i] {
                if prev == 0 {
                    count += 1
                }
                count += 2;
                prev = 3;
            } else {
                if v1[i] == 0 && prev == 0 {
                    count += 1;
                    prev = v1[i]
                } else if v1[i] != prev && prev != 3 {
                    count += 2;
                    prev = 3
                } else {
                    prev = v1[i];
                }
            }
        }
        if prev == 0 {
            count += 1;
        }
        println!("{}", &count);
    }
}


You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft $$$k$$$ torches. One torch can be crafted using one stick and one coal.Hopefully, you've met a very handsome wandering trader who has two trade offers:  exchange $$$1$$$ stick for $$$x$$$ sticks (you lose $$$1$$$ stick and gain $$$x$$$ sticks).  exchange $$$y$$$ sticks for $$$1$$$ coal (you lose $$$y$$$ sticks and gain $$$1$$$ coal). During one trade, you can use only one of these two trade offers. You can use each trade offer any number of times you want to, in any order.Your task is to find the minimum number of trades you need to craft at least $$$k$$$ torches. The answer always exists under the given constraints.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  long long int n;
  scanf("%d", &t);
  long long int arr[t][3];
  for (int i = 0; i < t; i++) {
    scanf("%lld %lld %lld", &arr[i][0], &arr[i][1], &arr[i][2]);
  }
  for (int i = 0; i < t; i++) {
    n = (arr[i][2] + arr[i][2] * arr[i][1] - 3 + arr[i][0]) / (arr[i][0] - 1);
    printf("%lld\n", n + arr[i][2]);
  }

  return 0;
}

fn solution() {
    let mut input_line = String::new();
    stdin().read_line(&mut input_line).unwrap();
    let mut cases = input_line.trim().parse::<i32>().unwrap_or(-1);
    while cases > 0 {
        cases -= 1;
        input_line.clear();
        stdin().read_line(&mut input_line).unwrap();
        let inputs = input_line.trim().split(' ').collect::<Vec<&str>>();
        let [x, y, k] = [
            inputs[0].parse::<i64>().unwrap_or(-1),
            inputs[1].parse::<i64>().unwrap_or(-1),
            inputs[2].parse::<i64>().unwrap_or(-1),
        ];
        let total_sticks_needed = k + k * y;
        let trade_times_to_get_enough_sticks = (total_sticks_needed + x - 3) / (x - 1);
        println!("{}", k + trade_times_to_get_enough_sticks);
    }
}


Recently, your friend discovered one special operation on an integer array $$$a$$$:   Choose two indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$);  Set $$$a_i = a_j = |a_i - a_j|$$$. After playing with this operation for a while, he came to the next conclusion:   For every array $$$a$$$ of $$$n$$$ integers, where $$$1 \le a_i \le 10^9$$$, you can find a pair of indices $$$(i, j)$$$ such that the total sum of $$$a$$$ will decrease after performing the operation. This statement sounds fishy to you, so you want to find a counterexample for a given integer $$$n$$$. Can you find such counterexample and prove him wrong?In other words, find an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) such that for all pairs of indices $$$(i, j)$$$ performing the operation won't decrease the total sum (it will increase or not change the sum).

int solution(void) {
  int t;
  scanf("%d", &t);
  for (int o = 0; o < t; o++) {
    int n = 0;
    scanf("%d", &n);
    int array[n];
    for (int k = 0; k < n; k++) {
      array[k] = pow(3, k);
    }
    if (pow(3, n - 1) < pow(10, 9)) {
      printf("YES\n");
      for (int x = 0; x < n; x++) {
        printf("%d ", array[x]);
      }
      printf("\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let mut n = String::new();
    io::stdin().read_line(&mut n).unwrap();
    let n: u32 = n.trim().parse().unwrap();
    for _ in 0..n {
        let mut l = String::new();
        io::stdin().read_line(&mut l).unwrap();
        let l: u32 = l.trim().parse().unwrap();
        if l <= 19 {
            println!("YES");
            for i in 0..l {
                print!("{} ", u32::pow(3, i));
            }
            println!()
        } else {
            println!("NO");
        }
    }
}


Score : <var>300</var> points

Problem Statement

Find the price of a product before tax such that, when the consumption tax rate is <var>8</var> percent and <var>10</var> percent, the amount of consumption tax levied on it is <var>A</var> yen and <var>B</var> yen, respectively. (Yen is the currency of Japan.)

Here, the price before tax must be a positive integer, and the amount of consumption tax is rounded down to the nearest integer.

If multiple prices satisfy the condition, print the lowest such price; if no price satisfies the condition, print -1.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

If there is a price that satisfies the condition, print an integer representing the lowest such price; otherwise, print -1.

Sample Input 1

2 2

Sample Output 1

25

If the price of a product before tax is <var>25</var> yen, the amount of consumption tax levied on it is:

When the consumption tax rate is <var>8</var> percent: <var>\lfloor 25 \times 0.08 \rfloor = \lfloor 2 \rfloor = 2</var> yen.

When the consumption tax rate is <var>10</var> percent: <var>\lfloor 25 \times 0.1 \rfloor = \lfloor 2.5 \rfloor = 2</var> yen.

Thus, the price of <var>25</var> yen satisfies the condition. There are other possible prices, such as <var>26</var> yen, but print the minimum such price, <var>25</var>.

Sample Input 2

8 10

Sample Output 2

100

If the price of a product before tax is <var>100</var> yen, the amount of consumption tax levied on it is:

When the consumption tax rate is <var>8</var> percent: <var>\lfloor 100 \times 0.08 \rfloor = 8</var> yen.

When the consumption tax rate is <var>10</var> percent: <var>\lfloor 100 \times 0.1 \rfloor = 10</var> yen.

Sample Input 3

19 99

Sample Output 3

-1

There is no price before tax satisfying this condition, so print -1.

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let mut iter = buf.split_whitespace();
    let a: i32 = match iter.next().unwrap().parse() {
        Ok(n) => n,
        Err(_) => panic!(""),
    };
    let b: i32 = match iter.next().unwrap().parse() {
        Ok(n) => n,
        Err(_) => panic!(""),
    };
    let mut tax: HashMap<(i32, i32), Vec<i32>> = HashMap::new();
    for i in 1..1010 {
        let m = tax.insert((i * 8 / 100, i * 10 / 100), vec![]);
        if m.is_none() {
            let v = vec![i];
            tax.insert((i * 8 / 100, i * 10 / 100), v);
        } else {
            let mut v = m.unwrap();
            v.push(i);
            tax.insert((i * 8 / 100, i * 10 / 100), v);
        }
    }
    match tax.get(&(a, b)) {
        None => println!("-1"),
        Some(v) => println!("{}", v[0]),
    };
}


You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

int solution() {
  int n;
  scanf("%d", &n);
  char str[n][101];
  int i;
  int j;
  for (i = 0; i < n; i++) {
    scanf("%s", str[i]);
  }
  int len[n];
  int pos[n];
  for (i = 0; i < n; i++) {
    len[i] = strlen(str[i]);
    pos[i] = i;
  }
  int templen;
  int temppos;
  for (i = 0; i < n - 1; i++) {
    for (j = i + 1; j < n; j++) {
      if (len[j] < len[i]) {
        templen = len[i];
        len[i] = len[j];
        len[j] = templen;
        temppos = pos[i];
        pos[i] = pos[j];
        pos[j] = temppos;
      }
    }
  }

  int count = 0;
  int k;
  for (i = 0; i < n - 1; i++) {
    for (j = 0; j <= len[i + 1] - len[i]; j++) {
      for (k = 0; k < len[i]; k++) {
        if (str[pos[i + 1]][j + k] != str[pos[i]][k]) {
          break;
        }
      }
      if (k == len[i]) {
        count++;
        break;
      }
    }
  }
  if (count == n - 1) {
    printf("YES\n");
    for (i = 0; i < n; i++) {
      printf("%s\n", str[pos[i]]);
    }
  } else {
    printf("NO\n");
  }
  return 0;
}

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

    io::stdin().read_line(&mut input).unwrap();
    let n = input.trim().parse::<i32>().unwrap();
    input.clear();

    for _i in 0..n {
        io::stdin().read_line(&mut input).unwrap();
    }
    let mut strs: Vec<&str> = input.split_whitespace().collect();

    strs.sort_by(|a, b| {
        if a.contains(b) || a == b {
            Ordering::Greater
        } else if b.contains(a) {
            Ordering::Less
        } else {
            Ordering::Equal
        }
    });

    let mut flag = true;
    for window in strs.windows(2) {
        if !window[1].contains(window[0]) {
            flag = false;
            break;
        }
    }

    if flag {
        println!("YES");
        for output in &strs {
            println!("{}", output);
        }
    } else {
        println!("NO");
    }
}


Score : <var>300</var> points

Problem Statement

There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive <var>N</var> rows and <var>M</var> columns, and a card is placed in each square in this region.
The front and back sides of these cards can be distinguished, and initially every card faces up.

We will perform the following operation once for each square contains a card:

For each of the following nine squares, flip the card in it if it exists: the target square itself and the eight squares that shares a corner or a side with the target square.

It can be proved that, whether each card faces up or down after all the operations does not depend on the order the operations are performed.
Find the number of cards that face down after all the operations.

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>

Output

Print the number of cards that face down after all the operations.

Sample Input 1

2 2

Sample Output 1

0

We will flip every card in any of the four operations. Thus, after all the operations, all cards face up.

Sample Input 2

1 7

Sample Output 2

5

After all the operations, all cards except at both ends face down.

Sample Input 3

314 1592

Sample Output 3

496080

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

  if (m == 1 && n != 1) {
    printf("%lld\n", n - 2);
  } else if (n == 1 && m != 1) {
    printf("%lld\n", m - 2);
  } else if (m == 1 && n == 1) {
    printf("1\n");
  } else {
    printf("%lld\n", (n * m) - ((n + m) * 2) + 4);
  }

  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 mut n: u64 = itr.next().unwrap().parse().unwrap();
    let mut k: u64 = itr.next().unwrap().parse().unwrap();
    if n > k {
        std::mem::swap(&mut n, &mut k);
    }
    if n <= 1 {
        if k == 1 {
            println!("{}", 1);
        } else {
            println!("{}", k - 2);
        }
    } else if n <= 2 {
        println!("{}", 0);
    } else {
        println!("{}", n * k - (n * 2 + (k - 2) * 2));
    }
}


Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.Mishka can put a box i into another box j if the following conditions are met:  i-th box is not put into another box;  j-th box doesn't contain any other boxes;  box i is smaller than box j (ai < aj). Mishka can put boxes into each other an arbitrary number of times. He wants to minimize the number of visible boxes. A box is called visible iff it is not put into some another box.Help Mishka to determine the minimum possible number of visible boxes!

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

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

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

    let a: Vec<u32> = it.take(n).map(|x| x.parse().unwrap()).collect();

    let mut hm = std::collections::HashMap::new();

    for a in a {
        *hm.entry(a).or_insert(0) += 1;
    }

    let ans = hm.values().max().unwrap();

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


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of <var>S</var>.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

A substring of a string <var>T</var> is a string obtained by removing zero or more characters from the beginning and the end of <var>T</var>.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

Constraints

<var>S</var> is a string of length between <var>1</var> and <var>10</var> (inclusive).

Each character in <var>S</var> is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the length of the longest ACGT string that is a substring of <var>S</var>.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is  (the empty string).

int solution() {
  int ans = 0;
  int tmp = 0;
  while (1) {
    char c = getchar();
    if (c == 'A' || c == 'G' || c == 'T' || c == 'C') {
      tmp++;
      if (ans < tmp) {
        ans = tmp;
      }
    } else if (c >= 'A' && c <= 'Z') {
      tmp = 0;
    } else {
      break;
    }
  }
  printf("%d\n", ans);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let s: Vec<char> = buf.trim().chars().collect();
    let mut flag = false;
    let mut p = 0;
    for i in 1..(s.len() + 1) {
        let mut j = 0;
        while j + i <= s.len() {
            let ps = &s[j..(j + i)];
            for k in ps {
                if !(*k == 'A' || *k == 'T' || *k == 'G' || *k == 'C') {
                    flag = true;
                    break;
                }
            }
            if flag {
                flag = false;
            } else {
                p = i;
                break;
            }
            j += 1;
        }
        flag = false;
    }
    println!("{}", p);
}


You are given a positive integer $$$x$$$. Find any such $$$2$$$ positive integers $$$a$$$ and $$$b$$$ such that $$$GCD(a,b)+LCM(a,b)=x$$$.As a reminder, $$$GCD(a,b)$$$ is the greatest integer that divides both $$$a$$$ and $$$b$$$. Similarly, $$$LCM(a,b)$$$ is the smallest integer such that both $$$a$$$ and $$$b$$$ divide it.It's guaranteed that the solution always exists. If there are several such pairs $$$(a, b)$$$, you can output any of them.

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

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

    bih.read_line(&mut line).unwrap();

    for _ in 0..line.trim().parse::<u32>().unwrap() {
        line.clear();
        bih.read_line(&mut line).unwrap();

        writeln!(boh, "1 {}", line.trim().parse::<u32>().unwrap() - 1).unwrap();
    }
}


Score : <var>300</var> points

Problem Statement

"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are <var>A</var> yen, <var>B</var> yen and <var>C</var> yen (yen is the currency of Japan), respectively.

Nakahashi needs to prepare <var>X</var> A-pizzas and <var>Y</var> B-pizzas for a party tonight. He can only obtain these pizzas by directly buying A-pizzas and B-pizzas, or buying two AB-pizzas and then rearrange them into one A-pizza and one B-pizza. At least how much money does he need for this? It is fine to have more pizzas than necessary by rearranging pizzas.

Constraints

<var>1 ≤ A, B, C ≤ 5000</var>

<var>1 ≤ X, Y ≤ 10^5</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum amount of money required to prepare <var>X</var> A-pizzas and <var>Y</var> B-pizzas.

Sample Input 1

1500 2000 1600 3 2

Sample Output 1

7900

It is optimal to buy four AB-pizzas and rearrange them into two A-pizzas and two B-pizzas, then buy additional one A-pizza.

Sample Input 2

1500 2000 1900 3 2

Sample Output 2

8500

It is optimal to directly buy three A-pizzas and two B-pizzas.

Sample Input 3

1500 2000 500 90000 100000

Sample Output 3

100000000

It is optimal to buy <var>200000</var> AB-pizzas and rearrange them into <var>100000</var> A-pizzas and <var>100000</var> B-pizzas. We will have <var>10000</var> more A-pizzas than necessary, but that is fine.

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

  if (x >= y) {
    if (a + b <= 2 * c) {
      s = 1;
    } else if (2 * c > a) {
      s = 2;
    } else if (a >= 2 * c) {
      s = 3;
    }
  } else {
    if (a + b <= 2 * c) {
      s = 1;
    } else if (2 * c > b) {
      s = 4;
    } else if (b >= 2 * c) {
      s = 5;
    }
  }

  switch (s) {
  case 1:
    z = a * x + b * y;
    break;
  case 2:
    z = a * (x - y) + 2 * c * y;
    break;
  case 3:
    z = 2 * c * x;
    break;
  case 4:
    z = b * (y - x) + 2 * c * x;
    break;
  case 5:
    z = 2 * c * y;
    break;
  }

  printf("%d", z);

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.trim().split(" ");
    let a = iter.next().unwrap().parse::<i64>().unwrap();
    let b = iter.next().unwrap().parse::<i64>().unwrap();
    let c = iter.next().unwrap().parse::<i64>().unwrap();
    let x = iter.next().unwrap().parse::<i64>().unwrap();
    let y = iter.next().unwrap().parse::<i64>().unwrap();

    if a > 2 * c {
        if b > 2 * c {
            println!("{}", 2 * max(x, y) * c);
        } else {
            println!("{}", 2 * x * c + max(0, y - x) * b);
        }
    } else if b > 2 * c {
        println!("{}", 2 * y * c + max(0, x - y) * a);
    } else if a + b > 2 * c {
        println!(
            "{}",
            c * 2 * min(x, y) + if x > y { a * (x - y) } else { b * (y - x) }
        );
    } else {
        println!("{}", a * x + b * y);
    }
}


Score : <var>500</var> points

Problem Statement

Alice and Brown loves games. Today, they will play the following game.

In this game, there are two piles initially consisting of <var>X</var> and <var>Y</var> stones, respectively.
Alice and Bob alternately perform the following operation, starting from Alice:

Take <var>2i</var> stones from one of the piles. Then, throw away <var>i</var> of them, and put the remaining <var>i</var> in the other pile. Here, the integer <var>i</var> <var>(1≤i)</var> can be freely chosen as long as there is a sufficient number of stones in the pile.

The player who becomes unable to perform the operation, loses the game.

Given <var>X</var> and <var>Y</var>, determine the winner of the game, assuming that both players play optimally.

Constraints

<var>0 ≤ X, Y ≤ 10^{18}</var>

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>Y</var>

Output

Print the winner: either Alice or Brown.

Sample Input 1

2 1

Sample Output 1

Brown

Alice can do nothing but taking two stones from the pile containing two stones. As a result, the piles consist of zero and two stones, respectively. Then, Brown will take the two stones, and the piles will consist of one and zero stones, respectively. Alice will be unable to perform the operation anymore, which means Brown's victory.

Sample Input 2

5 0

Sample Output 2

Alice

Sample Input 3

0 0

Sample Output 3

Brown

Sample Input 4

4 8

Sample Output 4

Alice

int solution(void) {
  long long x;
  long long y;
  scanf("%lld%lld", &x, &y);
  if (llabs(x - y) > 1) {
    printf("Alice\n");
  } else {
    printf("Brown\n");
  }
  return 0;
}

fn solution() {
    input! {
        x: i64,
        y: i64
    }

    println!("{}", if (x - y).abs() <= 1 { "Brown" } else { "Alice" });
}


Score : <var>100</var> points

Problem Statement

We have two bottles for holding water.

Bottle <var>1</var> can hold up to <var>A</var> milliliters of water, and now it contains <var>B</var> milliliters of water.

Bottle <var>2</var> contains <var>C</var> milliliters of water.

We will transfer water from Bottle <var>2</var> to Bottle <var>1</var> as much as possible.

How much amount of water will remain in Bottle <var>2</var>?

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle <var>2</var>.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle <var>2</var> to Bottle <var>1</var>, and one milliliter of water will remain in Bottle <var>2</var>.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0

int solution() {
  int A = 0;
  int B = 0;
  int C = 0;

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

  while (C > 0 && A > B) {
    B++;
    C--;
  }

  printf("%d", C);

  return 0;
}

fn solution() {
    let max = |a, b| if a < b { b } else { a };
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    let line: Vec<isize> = line.split_whitespace().flat_map(str::parse).collect();
    let (a, b, c) = (line[0], line[1], line[2]);

    println!("{}", max(0, c - a + b));
}


Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction  as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1.

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

    let mut iter = input_str.split_whitespace();
    let i: u64 = iter.next().unwrap().parse().unwrap();

    match i {
        1 => println!("{}", -1),
        _ => println!("{} {} {}", i, i + 1, i * (i + 1)),
    };
}


You are given some Tetris field consisting of $$$n$$$ columns. The initial height of the $$$i$$$-th column of the field is $$$a_i$$$ blocks. On top of these columns you can place only figures of size $$$2 \times 1$$$ (i.e. the height of this figure is $$$2$$$ blocks and the width of this figure is $$$1$$$ block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one $$$a_i$$$ is greater than $$$0$$$:  You place one figure $$$2 \times 1$$$ (choose some $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with $$$a_i + 2$$$);  then, while all $$$a_i$$$ are greater than zero, replace each $$$a_i$$$ with $$$a_i - 1$$$. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer $$$t$$$ independent test cases.

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 _ = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .parse::<usize>()
            .unwrap();
        let initial: Vec<usize> = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|s| s.trim())
            .filter(|s| !s.is_empty())
            .map(|s| s.parse().unwrap())
            .collect();
        let min = initial.iter().min().unwrap();
        let subtract: Vec<usize> = initial.iter().map(|x| x - min).collect();
        let all_divisible = subtract.iter().all(|x| x % 2 == 0);
        if all_divisible {
            println!("YES")
        } else {
            println!("NO")
        }
    }
}


Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.Vladik knows n airports. All the airports are located on a straight line. Each airport has unique id from 1 to n, Vladik's house is situated next to the airport with id a, and the place of the olympiad is situated next to the airport with id b. It is possible that Vladik's house and the place of the olympiad are located near the same airport. To get to the olympiad, Vladik can fly between any pair of airports any number of times, but he has to start his route at the airport a and finish it at the airport b.Each airport belongs to one of two companies. The cost of flight from the airport i to the airport j is zero if both airports belong to the same company, and |i - j| if they belong to different companies.Print the minimum cost Vladik has to pay to get to the olympiad.

int solution() {
  int n;
  int a;
  int b;
  char c[100010];
  scanf("%d%d%d", &n, &a, &b);
  scanf("%s", c);
  a--;
  b--;
  if (c[a] == c[b]) {
    printf("0\n");
  } else {
    printf("1\n");
  }
  return 0;
}

fn solution() {
    let mut input_str = String::new();
    io::stdin().read_line(&mut input_str).unwrap();
    let mut iter = input_str.split_whitespace();
    let airport_count = iter.next().unwrap().parse::<usize>().unwrap();
    let start = iter.next().unwrap().parse::<usize>().unwrap() - 1;
    let end = iter.next().unwrap().parse::<usize>().unwrap() - 1;

    let mut airports = Vec::with_capacity(airport_count);

    let mut input_str = String::new();
    io::stdin().read_line(&mut input_str).unwrap();
    for ch in input_str.chars() {
        if ch == '1' {
            airports.push(true);
        } else {
            airports.push(false);
        }
    }

    if airports[start] == airports[end] {
        println!("{}", 0);
    } else {
        println!("{}", 1);
    }
}


Score: <var>200</var> points

Problem Statement

Takahashi, who works at DISCO, is standing before an iron bar.
The bar has <var>N-1</var> notches, which divide the bar into <var>N</var> sections. The <var>i</var>-th section from the left has a length of <var>A_i</var> millimeters.

Takahashi wanted to choose a notch and cut the bar at that point into two parts with the same length.
However, this may not be possible as is, so he will do the following operations some number of times before he does the cut:

Choose one section and expand it, increasing its length by <var>1</var> millimeter. Doing this operation once costs <var>1</var> yen (the currency of Japan).

Choose one section of length at least <var>2</var> millimeters and shrink it, decreasing its length by <var>1</var> millimeter. Doing this operation once costs <var>1</var> yen.

Find the minimum amount of money needed before cutting the bar into two parts with the same length.

Constraints

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

<var>1 \leq A_i \leq 2020202020</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print an integer representing the minimum amount of money needed before cutting the bar into two parts with the same length.

Sample Input 1

3
2 4 3

Sample Output 1

3

The initial lengths of the sections are <var>[2, 4, 3]</var> (in millimeters). Takahashi can cut the bar equally after doing the following operations for <var>3</var> yen:

Shrink the second section from the left. The lengths of the sections are now <var>[2, 3, 3]</var>.

Shrink the first section from the left. The lengths of the sections are now <var>[1, 3, 3]</var>.

Shrink the second section from the left. The lengths of the sections are now <var>[1, 2, 3]</var>, and we can cut the bar at the second notch from the left into two parts of length <var>3</var> each.

Sample Input 2

12
100 104 102 105 103 103 101 105 104 102 104 101

Sample Output 2

0

int solution(void) {
  int N;
  scanf("%d", &N);
  long long int A[200000];
  long long int min = 2020202020;
  long long int sum = 0;
  long long int sum2 = 0;
  for (int i = 0; i < N; i++) {
    scanf("%lld", &A[i]);
    sum += A[i];
  }
  for (int i = 0; i < N; i++) {
    sum2 += A[i];
    if (labs(sum - (2 * sum2)) < min) {
      min = labs(sum - (2 * sum2));
    }
  }
  printf("%lld", min);

  return 0;
}

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

    let mut acc = vec![0; N];
    acc[0] = A[0];
    for i in 1..N {
        acc[i] = acc[i - 1] + A[i];
    }
    let ans = (1..N)
        .map(|i| (acc[i - 1] - (acc[N - 1] - acc[i - 1])).abs())
        .min()
        .unwrap();

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


Score : <var>100</var> points

Problem Statement

Snuke has a grid consisting of three squares numbered <var>1</var>, <var>2</var> and <var>3</var>.
In each square, either 0 or 1 is written. The number written in Square <var>i</var> is <var>s_i</var>.

Snuke will place a marble on each square that says 1.
Find the number of squares on which Snuke will place a marble.

Constraints

Each of <var>s_1</var>, <var>s_2</var> and <var>s_3</var> is either 1 or 0.

Input

Input is given from Standard Input in the following format:

<var>s_{1}s_{2}s_{3}</var>

Output

Print the answer.

Sample Input 1

101

Sample Output 1

2

A marble will be placed on Square <var>1</var> and <var>3</var>.

Sample Input 2

000

Sample Output 2

0

No marble will be placed on any square.

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    println!("{}", s.trim().chars().filter(|&c| c == '1').count());
}


void solution(int *arr, int n) {
  int curr_size;
  int i;
  int maxElementIdx;
  int temp;
  int start;

  for (curr_size = n; curr_size > 1; --curr_size) {

    maxElementIdx = 0;

    for (i = 1; i < curr_size; ++i) {
      if (arr[i] > arr[maxElementIdx]) {
        maxElementIdx = i;
      }
    }

    if (maxElementIdx != curr_size - 1) {

      start = 0;
      i = maxElementIdx;

      while (start < i) {
        temp = arr[start];
        arr[start] = arr[i];
        arr[i] = temp;

        start++;
        i--;
      }

      start = 0;
      i = curr_size - 1;

      while (start < i) {
        temp = arr[start];
        arr[start] = arr[i];
        arr[i] = temp;

        start++;
        i--;
      }
    }
  }
}

fn solution<T>(arr: &mut [T]) -> Vec<T>
where
    T: cmp::PartialEq + cmp::Ord + cmp::PartialOrd + Clone,
{
    let len = arr.len();
    if len < 2 {
        arr.to_vec();
    }
    for i in (0..len).rev() {
        let max_index = arr
            .iter()
            .take(i + 1)
            .enumerate()
            .max_by_key(|&(_, elem)| elem)
            .map(|(idx, _)| idx)
            .unwrap();
        if max_index != i {
            arr[0..=max_index].reverse();
            arr[0..=i].reverse();
        }
    }
    arr.to_vec()
}


The problem statement looms below, filling you with determination.Consider a grid in which some cells are empty and some cells are filled. Call a cell in this grid exitable if, starting at that cell, you can exit the grid by moving up and left through only empty cells. This includes the cell itself, so all filled in cells are not exitable. Note that you can exit the grid from any leftmost empty cell (cell in the first column) by going left, and from any topmost empty cell (cell in the first row) by going up.Let's call a grid determinable if, given only which cells are exitable, we can exactly determine which cells are filled in and which aren't.You are given a grid $$$a$$$ of dimensions $$$n \times m$$$ , i. e. a grid with $$$n$$$ rows and $$$m$$$ columns. You need to answer $$$q$$$ queries ($$$1 \leq q \leq 2 \cdot 10^5$$$). Each query gives two integers $$$x_1, x_2$$$ ($$$1 \leq x_1 \leq x_2 \leq m$$$) and asks whether the subgrid of $$$a$$$ consisting of the columns $$$x_1, x_1 + 1, \ldots, x_2 - 1, x_2$$$ is determinable.

int solution() {
  int n;
  int m;
  scanf("%d%d", &n, &m);
  char str[n][m];
  for (int i = 0; i < n; i++) {
    scanf("%s", str[i]);
  }
  int q;
  int arr[1000000] = {0};
  scanf("%d", &q);
  for (int i = 1; i <= m - 1; i++) {
    for (int j = 1; j <= n - 1; j++) {
      if (str[j][i - 1] == 'X' && str[j - 1][i] == 'X') {
        arr[i] = 1;
        break;
      }
    }
  }
  for (int i = 1; i < m; i++) {
    arr[i] += arr[i - 1];
  }
  for (int j = 1; j <= q; j++) {
    int x;
    int y;
    int temp = 0;
    scanf("%d%d", &x, &y);
    x--;
    y--;
    if (arr[x] == arr[y]) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() -> io::Result<()> {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s)?;
    let mut it = s.split_whitespace().map(|s| s.to_string());
    let mut out = String::new();
    let R: usize = it.next().unwrap().parse().unwrap();
    let C: usize = it.next().unwrap().parse().unwrap();
    let mut grid = vec![];
    for _ in 0..R {
        let s: String = it.next().unwrap().parse().unwrap();
        let row: Vec<bool> = s.chars().map(|x| x == 'X').collect();
        grid.push(row);
    }
    let mut pfx = vec![0; C];
    for j in 1..C {
        let mut ok = true;
        for i in 0..R - 1 {
            if grid[i][j] && grid[i + 1][j - 1] {
                ok = false;
                break;
            }
        }
        if ok {
            pfx[j] = pfx[j - 1];
        } else {
            pfx[j] = pfx[j - 1] + 1;
        }
    }

    let Q: usize = it.next().unwrap().parse().unwrap();
    for _ in 0..Q {
        let mut x1: usize = it.next().unwrap().parse().unwrap();
        let mut x2: usize = it.next().unwrap().parse().unwrap();
        x1 -= 1;
        x2 -= 1;
        if x1 == x2 || pfx[x1] == pfx[x2] {
            out.push_str("yes\n");
        } else {
            out.push_str("no\n");
        }
    }
    print!("{}", out);
    Ok(())
}


Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it.

int solution() {
  int n;
  scanf("%d\n", &n);
  char word[n];
  int par = (n - 1) / 2;
  int sign = n & 1 ? 1 : -1;
  for (int i = 0; i < n; i++) {
    par += sign * i;
    sign *= -1;
    word[par] = getchar();
  }
  for (int i = 0; i < n; i++) {
    putchar(word[i]);
  }
  return 0;
}

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

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

    let mut v: VecDeque<char> = VecDeque::new();
    let mut i = if n % 2 == 0 { 1 } else { 0 };
    for ch in line.chars() {
        if i % 2 == 0 {
            v.push_back(ch);
        } else {
            v.push_front(ch);
        }
        i += 1;
    }
    let word: String = v.into_iter().collect();
    println!("{}", word);
    Ok(())
}


Mark is cleaning a row of $$$n$$$ rooms. The $$$i$$$-th room has a nonnegative dust level $$$a_i$$$. He has a magical cleaning machine that can do the following three-step operation.   Select two indices $$$i<j$$$ such that the dust levels $$$a_i$$$, $$$a_{i+1}$$$, $$$\dots$$$, $$$a_{j-1}$$$ are all strictly greater than $$$0$$$.  Set $$$a_i$$$ to $$$a_i-1$$$.  Set $$$a_j$$$ to $$$a_j+1$$$.  Mark's goal is to make $$$a_1 = a_2 = \ldots = a_{n-1} = 0$$$ so that he can nicely sweep the $$$n$$$-th room. Determine the minimum number of operations needed to reach his goal.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int flag = 0;
    long long count = 0;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      if (flag == 0 && arr[i] != 0 && i < n - 1) {
        count += arr[i];
        flag = 1;
      } else if (flag == 1 && i < n - 1) {
        if (arr[i] != 0) {
          count += arr[i];
        } else {
          count++;
        }
      }
    }
    printf("%lld\n", count);
  }
  return 0;
}

fn solution() {
    input! {
        name = reader,
        tests: usize
    }
    use std::io::*;
    let stdout = stdout();
    let mut writer = BufWriter::new(stdout.lock());

    for _ in 0..tests {
        input! {
            use reader,
            n: usize,
            mut a: [u64; n]
        }
        let mut zeros = (0..n - 1).rev().filter(|i| a[*i] == 0).collect::<Vec<_>>();
        let mut ans = 0;
        for i in 0..n - 1 {
            while let Some(x) = zeros.last() {
                if *x <= i {
                    zeros.pop();
                } else {
                    break;
                }
            }
            while a[i] > 0 {
                if let Some(x) = zeros.pop() {
                    a[i] -= 1;
                    a[x] += 1;
                    ans += 1;
                } else {
                    break;
                }
            }
            ans += a[i];
        }
        println!("{}", ans);
    }

    <BufWriter<StdoutLock> as Write>::flush(&mut writer).unwrap();
}


Everybody knows that the $$$m$$$-coder Tournament will happen soon. $$$m$$$ schools participate in the tournament, and only one student from each school participates.There are a total of $$$n$$$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $$$k$$$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

int solution() {
  int n;
  int m;
  int k;
  int x = 0;
  scanf("%i %i %i", &n, &m, &k);
  int a[n];
  int b[n];
  int c[k];
  for (int i = 0; i < n; i++) {
    scanf("%i", &a[i]);
  }
  for (int i = 0; i < n; i++) {
    scanf("%i", &b[i]);
  }
  for (int i = 0; i < k; i++) {
    scanf("%i", &c[i]);
  }
  for (int i = 0; i < k; i++) {
    for (int j = 0; j < n; j++) {
      if (a[c[i] - 1] < a[j] && b[c[i] - 1] == b[j]) {
        x++;
        break;
      }
    }
  }
  printf("%i", x);
  return 0;
}

fn solution() {
    let (n, m, _) = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut line = line.split_whitespace();
        (
            line.next().unwrap().trim().parse::<usize>().unwrap(),
            line.next().unwrap().trim().parse::<usize>().unwrap(),
            line.next().unwrap().trim().parse::<usize>().unwrap(),
        )
    };

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

    let s: Vec<usize> = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|it| it.trim().parse().unwrap())
            .collect()
    };

    let c: Vec<usize> = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        line.split_whitespace()
            .map(|it| it.trim().parse().unwrap())
            .collect()
    };

    let mut bests = vec![0; m];
    for i in 0..n {
        let school = s[i] - 1;

        if bests[school] == 0 || p[i] > p[bests[school] - 1] {
            bests[school] = i + 1;
        }
    }

    let mut res = c.len();
    for i in c {
        if bests.contains(&i) {
            res -= 1
        }
    }

    println!("{}", res)
}


Score : <var>100</var> points

Problem Statement

There is a directed graph <var>G</var> with <var>N</var> vertices and <var>M</var> edges.
The vertices are numbered <var>1, 2, \ldots, N</var>, and for each <var>i</var> (<var>1 \leq i \leq M</var>), the <var>i</var>-th directed edge goes from Vertex <var>x_i</var> to <var>y_i</var>.
<var>G</var> does not contain directed cycles.

Find the length of the longest directed path in <var>G</var>.
Here, the length of a directed path is the number of edges in it.

Constraints

All values in input are integers.

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

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

<var>1 \leq x_i, y_i \leq N</var>

All pairs <var>(x_i, y_i)</var> are distinct.

<var>G</var> does not contain directed cycles.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>x_1</var> <var>y_1</var>
<var>x_2</var> <var>y_2</var>
<var>:</var>
<var>x_M</var> <var>y_M</var>

Output

Print the length of the longest directed path in <var>G</var>.

Sample Input 1

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

Sample Output 1

3

The red directed path in the following figure is the longest:

Sample Input 2

6 3
2 3
4 5
5 6

Sample Output 2

2

The red directed path in the following figure is the longest:

Sample Input 3

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

Sample Output 3

3

The red directed path in the following figure is one of the longest:

int solution() {
  int i;
  int N;
  int M;
  int u;
  int w;
  int deg[100001] = {};
  list *adj[100001] = {};
  list e[100001];
  list *p;
  scanf("%d %d", &N, &M);
  for (i = 0; i < M; i++) {
    scanf("%d %d", &u, &w);
    e[i].v = w;
    e[i].next = adj[u];
    adj[u] = &(e[i]);
    deg[w]++;
  }

  int dist[100001] = {};
  int q[100001];
  int head;
  int tail;
  for (i = 1, tail = 0; i <= N; i++) {
    if (deg[i] == 0) {
      q[tail++] = i;
    }
  }
  for (head = 0; head < tail; head++) {
    u = q[head];
    for (p = adj[u]; p != NULL; p = p->next) {
      w = p->v;
      if (dist[u] + 1 > dist[w]) {
        dist[w] = dist[u] + 1;
      }
      deg[w]--;
      if (deg[w] == 0) {
        q[tail++] = w;
      }
    }
  }

  int max = 0;
  for (i = 1; i <= N; i++) {
    if (dist[i] > max) {
      max = dist[i];
    }
  }
  printf("%d\n", max);
  fflush(stdout);
  return 0;
}

fn solution() {
    input! {
        n: usize,
        m: usize,
        g: [(usize, usize); m]
    }
    let mut graph: Vec<Vec<usize>> = vec![vec![]; n];
    let mut in_degree: Vec<usize> = vec![0; n];
    for (f, t) in g {
        graph[f - 1].push(t - 1);
        in_degree[t - 1] += 1;
    }
    let mut graph_len: Vec<usize> = vec![0; n];
    let mut queue: VecDeque<usize> = VecDeque::new();
    for i in 0..n {
        if in_degree[i] == 0 {
            queue.push_front(i);
        }
    }
    let mut path_len = 0;
    while let Some(p) = queue.pop_back() {
        let nx_len = graph_len[p] + 1;
        path_len = cmp::max(path_len, graph_len[p]);
        for &i in &graph[p] {
            graph_len[i] = cmp::max(graph_len[i], nx_len);
            in_degree[i] -= 1;
            if in_degree[i] == 0 {
                queue.push_front(i);
            }
        }
    }
    println!("{}", path_len);
}


Yura is tasked to build a closed fence in shape of an arbitrary non-degenerate simple quadrilateral. He's already got three straight fence segments with known lengths $$$a$$$, $$$b$$$, and $$$c$$$. Now he needs to find out some possible integer length $$$d$$$ of the fourth straight fence segment so that he can build the fence using these four segments. In other words, the fence should have a quadrilateral shape with side lengths equal to $$$a$$$, $$$b$$$, $$$c$$$, and $$$d$$$. Help Yura, find any possible length of the fourth side.A non-degenerate simple quadrilateral is such a quadrilateral that no three of its corners lie on the same line, and it does not cross itself.

int solution(void) {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long ans = 0;
    for (int i = 0; i < 3; i++) {
      int temp;
      scanf("%d", &temp);
      ans += temp;
    }
    printf("%lld\n", ans - 1);
  }
}

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

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

    let t: u32 = s.trim().parse().expect("Oops");

    for _test in 1..t + 1 {
        let mut s: String = String::new();

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

        let mut s = s.split_whitespace();

        let mut a: i64 = s.next().expect("Oops").parse().expect("Oops");
        let mut b: i64 = s.next().expect("Oops").parse().expect("Oops");
        let mut c: i64 = s.next().expect("Oops").parse().expect("Oops");

        if a > b {
            mem::swap(&mut a, &mut b);
        }
        if a > c {
            mem::swap(&mut a, &mut c);
        }
        if b > c {
            mem::swap(&mut b, &mut c);
        }

        let d = c;
        println!("{}", d);
    }
}


Score : <var>600</var> points

Problem Statement

Construct a sequence <var>a</var> = {<var>a_1,\ a_2,\ ...,\ a_{2^{M + 1}}</var>} of length <var>2^{M + 1}</var> that satisfies the following conditions, if such a sequence exists.

Each integer between <var>0</var> and <var>2^M - 1</var> (inclusive) occurs twice in <var>a</var>.

For any <var>i</var> and <var>j</var> <var>(i < j)</var> such that <var>a_i = a_j</var>, the formula <var>a_i \ xor \ a_{i + 1} \ xor \ ... \ xor \ a_j = K</var> holds.

What is xor (bitwise exclusive or)?

The xor of integers <var>c_1, c_2, ..., c_n</var> is defined as follows:

When <var>c_1 \ xor \ c_2 \ xor \ ... \ xor \ c_n</var> is written in base two, the digit in the <var>2^k</var>'s place (<var>k \geq 0</var>) is <var>1</var> if the number of integers among <var>c_1, c_2, ...c_m</var> whose binary representations have <var>1</var> in the <var>2^k</var>'s place is odd, and <var>0</var> if that count is even.

For example, <var>3 \ xor \ 5 = 6</var>. (If we write it in base two: 011 <var>xor</var> 101 <var>=</var> 110.)

fn solution() {
    input! {
        m: usize,
        k: usize
    }
    if 1 << m < k + 1 {
        println!("-1");
        return;
    }
    let mut d = 0;
    while 1 << d <= k {
        d += 1;
    }
    if k == 0 {
        print!("0 0");
        for i in 1..1 << m {
            print!(" {} {}", i, i);
        }
        println!();
    } else if k == 1 && m < 2 {
        println!("-1");
    } else {
        print!("0");
        for i in 1..1 << m {
            if i == k {
                continue;
            }
            print!(" {}", i);
        }
        print!(" {}", k);
        for i in (1..1 << m).rev() {
            if i == k {
                continue;
            }
            print!(" {}", i);
        }
        println!(" 0 {}", k);
    }
}


Score : <var>300</var> points

Problem Statement

Takahashi loves the number <var>7</var> and multiples of <var>K</var>.

Where is the first occurrence of a multiple of <var>K</var> in the sequence <var>7,77,777,\ldots</var>? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of <var>K</var>, print -1 instead.

Constraints

<var>1 \leq K \leq 10^6</var>

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

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print an integer representing the position of the first occurrence of a multiple of <var>K</var>. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of <var>7</var>, <var>77</var>, and <var>777</var> is a multiple of <var>101</var>, but <var>7777</var> is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of <var>2</var>.

Sample Input 3

999983

Sample Output 3

999982

int solution(void) {
  long k;
  long num = 1;
  scanf("%ld", &k);

  long a = (k % 7 == 0) ? 9 * k / 7 : 9 * k;
  if (a % 2 == 0 || a % 5 == 0) {
    puts("-1");
    return 0;
  }
  long n = 10 % a;

  while (1) {
    if (n == 1) {
      break;
    }
    n = n * 10 % a;
    num++;
  }
  printf("%ld\n", num);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    let stdin = io::stdin();
    stdin.read_line(&mut buf).unwrap();
    let K: u64 = buf.trim_end().parse().unwrap();
    let mut acc = 0;
    for i in 0..10_000_000 {
        acc *= 10;
        acc += 7;
        acc %= K;
        if acc == 0 {
            println!("{}", i + 1);
            return;
        }
    }
    println!("-1");
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> mountains in a circle, called Mountain <var>1</var>, Mountain <var>2</var>, <var>...</var>, Mountain <var>N</var> in clockwise order. <var>N</var> is an odd number.

Between these mountains, there are <var>N</var> dams, called Dam <var>1</var>, Dam <var>2</var>, <var>...</var>, Dam <var>N</var>. Dam <var>i</var> (<var>1 \leq i \leq N</var>) is located between Mountain <var>i</var> and <var>i+1</var> (Mountain <var>N+1</var> is Mountain <var>1</var>).

When Mountain <var>i</var> (<var>1 \leq i \leq N</var>) receives <var>2x</var> liters of rain, Dam <var>i-1</var> and Dam <var>i</var> each accumulates <var>x</var> liters of water (Dam <var>0</var> is Dam <var>N</var>).

One day, each of the mountains received a non-negative even number of liters of rain.

As a result, Dam <var>i</var> (<var>1 \leq i \leq N</var>) accumulated a total of <var>A_i</var> liters of water.

Find the amount of rain each of the mountains received. We can prove that the solution is unique under the constraints of this problem.

Constraints

All values in input are integers.

<var>3 \leq N \leq 10^5-1</var>

<var>N</var> is an odd number.

<var>0 \leq A_i \leq 10^9</var>

The situation represented by input can occur when each of the mountains receives a non-negative even number of liters of rain.

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 <var>N</var> integers representing the number of liters of rain Mountain <var>1</var>, Mountain <var>2</var>, <var>...</var>, Mountain <var>N</var> received, in this order.

Sample Input 1

3
2 2 4

Sample Output 1

4 0 4

If we assume Mountain <var>1</var>, <var>2</var>, and <var>3</var> received <var>4</var>, <var>0</var>, and <var>4</var> liters of rain, respectively, it is consistent with this input, as follows:

Dam <var>1</var> should have accumulated <var>\frac{4}{2} + \frac{0}{2} = 2</var> liters of water.

Dam <var>2</var> should have accumulated <var>\frac{0}{2} + \frac{4}{2} = 2</var> liters of water.

Dam <var>3</var> should have accumulated <var>\frac{4}{2} + \frac{4}{2} = 4</var> liters of water.

Sample Input 2

5
3 8 7 5 5

Sample Output 2

2 4 12 2 8

Sample Input 3

3
1000000000 1000000000 0

Sample Output 3

0 2000000000 0

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

  int pro = sum;
  for (int i = 0; i < (n - 1) / 2; i++) {
    pro -= 2 * a[(2 * i + 1) % n];
  }
  printf("%d ", pro);
  for (int i = 0; i < n - 1; i++) {
    pro = 2 * a[i] - pro;
    printf("%d ", pro);
  }
  printf("\n");
  return 0;
}

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

    let mut res = vec![(0..N)
        .map(|i| if i % 2 == 0 { A[i] } else { -A[i] })
        .sum::<i64>()];
    for i in 0..(N - 1) {
        let x = res[i] / 2;
        res.push(2 * (A[i] - x));
    }
    let ans = res
        .iter()
        .map(|&x| x.to_string())
        .collect::<Vec<_>>()
        .join(" ");

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


You are given three strings $$$a$$$, $$$b$$$ and $$$c$$$ of the same length $$$n$$$. The strings consist of lowercase English letters only. The $$$i$$$-th letter of $$$a$$$ is $$$a_i$$$, the $$$i$$$-th letter of $$$b$$$ is $$$b_i$$$, the $$$i$$$-th letter of $$$c$$$ is $$$c_i$$$.For every $$$i$$$ ($$$1 \leq i \leq n$$$) you must swap (i.e. exchange) $$$c_i$$$ with either $$$a_i$$$ or $$$b_i$$$. So in total you'll perform exactly $$$n$$$ swap operations, each of them either $$$c_i \leftrightarrow a_i$$$ or $$$c_i \leftrightarrow b_i$$$ ($$$i$$$ iterates over all integers between $$$1$$$ and $$$n$$$, inclusive).For example, if $$$a$$$ is "code", $$$b$$$ is "true", and $$$c$$$ is "help", you can make $$$c$$$ equal to "crue" taking the $$$1$$$-st and the $$$4$$$-th letters from $$$a$$$ and the others from $$$b$$$. In this way $$$a$$$ becomes "hodp" and $$$b$$$ becomes "tele".Is it possible that after these swaps the string $$$a$$$ becomes exactly the same as the string $$$b$$$?

int solution(void) {
  int t;
  scanf("%d", &t);
  while (t--) {
    int i = 0;
    int n = 0;
    char a[101];
    char b[101];
    char c[101];
    scanf("%s", a);

    while (a[i] != '\0') {
      n++;
      i++;
    }
    scanf("%s", b);

    scanf("%s", c);

    int flag = 1;
    for (i = 0; i < n; i++) {
      if (a[i] == b[i] && a[i] != c[i]) {
        flag = 0;
        break;
      }
      if (a[i] != b[i] && b[i] != c[i] && c[i] != a[i]) {
        flag = 0;
        break;
      }
    }
    if (flag == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

fn solution() {
    let t = {
        let mut buf = String::new();
        stdin().read_line(&mut buf).expect("Failed to read line");
        buf.trim().parse::<i32>().unwrap()
    };
    'outer: for _ in 0..t {
        let strings = {
            let mut buf = String::new();
            stdin().read_line(&mut buf).expect("Failed to read");
            stdin().read_line(&mut buf).expect("Failed to read");
            stdin().read_line(&mut buf).expect("Failed to read");
            let strings: Vec<String> = buf.lines().map(|s| s.trim().to_string()).collect();
            strings
        };
        for ((a, b), c) in strings[0]
            .chars()
            .zip(strings[1].chars())
            .zip(strings[2].chars())
        {
            if c != a && c != b {
                println!("NO");
                continue 'outer;
            }
        }
        println!("YES");
    }
}


Score : <var>100</var> points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is <var>30</var> degrees Celsius or above.

The current temperature of the room is <var>X</var> degrees Celsius. Will you turn on the air conditioner?

Constraints

<var>-40 \leq X \leq 40</var>

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

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes

int solution(void) {
  int temp = 0;

  scanf("%d", &temp);

  if (temp > 29) {
    printf("Yes");
  } else {
    printf("No");
  }

  return 0;
}

fn solution() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => match input.trim_end().parse::<i32>() {
            Ok(x) => println!("{}", if x >= 30 { "Yes" } else { "No" }),
            Err(_) => eprintln!("not a number"),
        },
        Err(_) => eprintln!("can't read anything"),
    }
}


The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.

int solution() {

  char logs[50];
  char formato[1];
  char aux[2];
  int n;

  scanf("%d", &n);
  while (getchar() != '\n') {
    ;
  }

  int hora;
  int minuto;
  char format;

  int cant = 1;
  int limite = 1;
  unsigned short seguir = 1;
  int minutos1 = 0;
  int minutos2 = 0;

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

    fgets(logs, sizeof(logs), stdin);
    hora = atoi(strncpy(aux, logs + 1, 2));
    minuto = atoi(strncpy(aux, logs + 4, 2));
    strncpy(formato, logs + 7, 1);
    format = *formato;

    if (format == 'p' && hora == 12) {
      minutos2 = hora * 60 + minuto;
    } else {
      if (format == 'p') {
        minutos2 = hora * 60 + minuto + 12 * 60;
      } else {
        if (format == 'a' && hora == 12) {
          minutos2 = minuto;
        } else {
          minutos2 = hora * 60 + minuto;
        }
      }
    }

    if (minutos2 < minutos1) {
      limite = 1;
      seguir = 1;
      cant++;
    } else {
      if (minutos2 > minutos1) {
        limite = 1;
        seguir = 1;
      } else {
        if ((minutos2 == minutos1) && seguir == 1) {
          limite++;
          if (limite == 10) {
            limite = 1;
            seguir = 0;
          }
        } else {
          if (minutos2 == minutos1) {
            cant++;
            seguir = 1;
          }
        }
      }
    }

    minutos1 = minutos2;
  }

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

  return 0;
}

fn solution() {
    let mut len = String::new();
    io::stdin().read_line(&mut len).unwrap();
    let n = len.trim().parse().unwrap();
    let mut last = -1;
    let mut day = 1;
    let mut count = 1;
    for _i in 0..n {
        let mut curr = String::new();
        io::stdin().read_line(&mut curr).unwrap();
        let mut hour: i32 = curr[1..3].parse().unwrap();
        let mut minute: i32 = curr[4..6].parse().unwrap();
        if &curr[7..8] == "p" && hour != 12 {
            hour += 12;
        }
        if &curr[7..8] == "a" && hour == 12 {
            hour -= 12;
        }
        minute += hour * 60;
        if minute < last {
            count = 1;
            day += 1;
        } else if minute == last {
            count += 1;
            if count > 10 {
                count = 1;
                day += 1;
            }
        } else {
            count = 1;
        }
        last = minute;
    }
    print!("{}", day);
}


科目選択 (Selecting Subjects)

 問題

JOI 君は物理，化学，生物，地学，歴史，地理の 6 科目のテストを受けた．
それぞれのテストは 100 点満点で採点された．

JOI 君は物理，化学，生物，地学の 4 科目から 3 科目を選択し，歴史，地理の 2 科目から 1 科目を選択する．

テストの合計点が最も高くなるように科目を選ぶとき，
JOI 君の選んだ科目のテストの合計点を求めよ．

  入力

入力は 6 行からなり，1 行に 1 つずつ整数が書かれている．

1 行目には JOI 君の物理のテストの点数 A が書かれている．

2 行目には JOI 君の化学のテストの点数 B が書かれている．

3 行目には JOI 君の生物のテストの点数 C が書かれている．

4 行目には JOI 君の地学のテストの点数 D が書かれている．

5 行目には JOI 君の歴史のテストの点数 E が書かれている．

6 行目には JOI 君の地理のテストの点数 F が書かれている．

書かれている整数 A, B, C, D, E, F はすべて 0 以上 100 以下である．

  出力

JOI 君が選んだ科目のテストの合計点を 1 行で出力せよ．

 入出力例

入力例 1

100
34
76
42
10
0

出力例 1

228

入力例 2

15
21
15
42
15
62

出力例 2

140

入出力例 1 では，JOI 君が物理，生物，地学，歴史の 4 科目を選ぶとき，テストの合計点が最高になる．

物理，生物，地学，歴史の点数はそれぞれ 100, 76, 42, 10 なので，選んだ科目のテストの合計点は 228 である．

入出力例 2 では，JOI 君が化学，生物，地学，地理の 4 科目を選ぶとき，テストの合計点が最高になる．

化学，生物，地学，地理の点数はそれぞれ 21, 15, 42, 62 なので，選んだ科目のテストの合計点は 140 である．

入出力例 2 では，JOI 君が物理，化学，地学，地理の 4 科目を選ぶ場合でも，選んだテストの合計点は 140 である．

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

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

    let mut iter = lines.map(|l| l.parse::<u32>().unwrap());

    let (sum, min) = iter.by_ref().take(4).fold((0, 100), |(sum, min), n| {
        (sum + n, if n < min { n } else { min })
    });
    let max = iter.take(2).max().unwrap();

    println!("{}", sum - min + max);
}


You are given a integer $$$n$$$ ($$$n > 0$$$). Find any integer $$$s$$$ which satisfies these conditions, or report that there are no such numbers:In the decimal representation of $$$s$$$:   $$$s > 0$$$,  $$$s$$$ consists of $$$n$$$ digits,  no digit in $$$s$$$ equals $$$0$$$,  $$$s$$$ is not divisible by any of it's digits.

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

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

    let t: i32 = input.trim().parse().unwrap();

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

        let n: i32 = input2.trim().parse().unwrap();

        if n == 1 {
            println!("-1");
        } else {
            print!("2");
            for _i in 1..n {
                print!("3");
            }
            println!();
        }
    }
}


There's a chip in the point $$$(0, 0)$$$ of the coordinate plane. In one operation, you can move the chip from some point $$$(x_1, y_1)$$$ to some point $$$(x_2, y_2)$$$ if the Euclidean distance between these two points is an integer (i.e. $$$\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}$$$ is integer).Your task is to determine the minimum number of operations required to move the chip from the point $$$(0, 0)$$$ to the point $$$(x, y)$$$.

int solution() {
  int tc;
  scanf("%d", &tc);
  while (tc--) {
    int x;
    int y;
    int z = 0;
    int m = 1;
    scanf("%d%d", &x, &y);
    while (m * m <= (x * x + y * y)) {
      if (m * m == (x * x + y * y)) {
        z++;
        break;
      }
      m++;
    }
    if (x == 0 && y == 0) {
      printf("0\n");
    } else if (z > 0) {
      printf("1\n");
    } else {
      printf("2\n");
    }
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    stdin().read_line(&mut input).unwrap();
    let t: i64 = input.trim().parse().unwrap();
    for _ in 0..t {
        let mut tc = String::new();
        stdin().read_line(&mut tc).unwrap();
        let xy: Vec<_> = tc.split(' ').map(|a| a.trim()).collect();
        let x: i64 = xy[0].parse().unwrap();
        let y: i64 = xy[1].parse().unwrap();
        match (x, y) {
            (0, 0) => {
                println!("0");
            }
            (x, y) if (x * x + y * y == ((x * x + y * y) as f64).sqrt().floor().powi(2) as i64) => {
                println!("1");
            }
            (_, _) => {
                println!("2");
            }
        }
    }
}


Score : <var>200</var> points

Problem Statement

There is a square in the <var>xy</var>-plane. The coordinates of its four vertices are <var>(x_1,y_1),(x_2,y_2),(x_3,y_3)</var> and <var>(x_4,y_4)</var> in counter-clockwise order.
(Assume that the positive <var>x</var>-axis points right, and the positive <var>y</var>-axis points up.)

Takahashi remembers <var>(x_1,y_1)</var> and <var>(x_2,y_2)</var>, but he has forgot <var>(x_3,y_3)</var> and <var>(x_4,y_4)</var>.

Given <var>x_1,x_2,y_1,y_2</var>, restore <var>x_3,y_3,x_4,y_4</var>. It can be shown that <var>x_3,y_3,x_4</var> and <var>y_4</var> uniquely exist and have integer values.

Constraints

<var>|x_1|,|y_1|,|x_2|,|y_2| \leq 100</var>

<var>(x_1,y_1)</var> ≠ <var>(x_2,y_2)</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>x_1</var> <var>y_1</var> <var>x_2</var> <var>y_2</var>

Output

Print <var>x_3,y_3,x_4</var> and <var>y_4</var> as integers, in this order.

Sample Input 1

0 0 0 1

Sample Output 1

-1 1 -1 0

<var>(0,0),(0,1),(-1,1),(-1,0)</var> is the four vertices of a square in counter-clockwise order.
Note that <var>(x_3,y_3)=(1,1),(x_4,y_4)=(1,0)</var> is not accepted, as the vertices are in clockwise order.

Sample Input 2

2 3 6 6

Sample Output 2

3 10 -1 7

Sample Input 3

31 -41 -59 26

Sample Output 3

-126 -64 -36 -131

int solution() {
  int x1 = 0;
  int y1 = 0;
  int x2 = 0;
  int y2 = 0;
  scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
  int len1 = x2 - x1;
  int len2 = y2 - y1;
  printf("%d %d %d %d", x2 - len2, y2 + len1, x1 - len2, y1 + len1);
  return 0;
}

fn solution() {
    let reader = io::stdin();
    let mut reader = BufReader::new(reader.lock());

    let mut s = String::new();

    let _ = reader.read_line(&mut s);

    let xs: Vec<i32> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();

    let x1 = xs[0];
    let y1 = xs[1];
    let x2 = xs[2];
    let y2 = xs[3];

    let dis_x = x2 - x1;
    let dis_y = y2 - y1;

    println!(
        "{} {} {} {}",
        x2 - dis_y,
        y2 + dis_x,
        x1 - dis_y,
        y1 + dis_x
    );
}


Score : <var>500</var> points

Problem Statement

<var>N</var> players will participate in a tennis tournament. We will call them Player <var>1</var>, Player <var>2</var>, <var>\ldots</var>, Player <var>N</var>.

The tournament is round-robin format, and there will be <var>N(N-1)/2</var> matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player <var>i</var> <var>(1 \leq i \leq N)</var> plays one match against Player <var>A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1}</var> in this order.

Constraints

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

<var>1 \leq A_{i, j} \leq N</var>

<var>A_{i, j} \neq i</var>

<var>A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1}</var> are all different.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_{1, 1}</var> <var>A_{1, 2}</var> <var>\ldots</var> <var>A_{1, N-1}</var>
<var>A_{2, 1}</var> <var>A_{2, 2}</var> <var>\ldots</var> <var>A_{2, N-1}</var>
<var>:</var>
<var>A_{N, 1}</var> <var>A_{N, 2}</var> <var>\ldots</var> <var>A_{N, N-1}</var>

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day <var>1</var>: Player <var>1</var> vs Player <var>2</var>

Day <var>2</var>: Player <var>1</var> vs Player <var>3</var>

Day <var>3</var>: Player <var>2</var> vs Player <var>3</var>

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day <var>1</var>: Player <var>1</var> vs Player <var>2</var>, Player <var>3</var> vs Player <var>4</var>

Day <var>2</var>: Player <var>1</var> vs Player <var>3</var>

Day <var>3</var>: Player <var>1</var> vs Player <var>4</var>, Player <var>2</var> vs Player <var>3</var>

Day <var>4</var>: Player <var>2</var> vs Player <var>4</var>

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.

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

  int A[1001][1001];
  int *P[1001];

  for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= N - 1; j++) {
      (void)scanf("%d", &(A[i][j]));
    }
    A[i][0] = 0;
    A[i][N] = 0;
    P[i] = A[i] + 1;
  }

  int I = 1;
  int D = 1;
  while (I <= N) {
    if (*P[I] <= 0) {
      I++;
      continue;
    }

    int noMatch = 1;
    for (int i = I; i <= N; i++) {
      int *player1 = P[i];
      if (*player1 == 0) {
        continue;
      }
      int *player2 = P[*player1];

      if (*(player1 - 1) == -D) {
        continue;
      }
      if (*(player2 - 1) == -D) {
        continue;
      }

      if (*player2 == i) {
        P[i]++;
        P[*player1]++;

        *player1 = -D;
        *player2 = -D;

        noMatch = 0;
      }
    }

    if (noMatch) {
      printf("-1\n");
      return 0;
    }
    D++;
  }

  printf("%d\n", D - 1);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    let mut xss: Vec<Vec<usize>> = Vec::new();
    for _ in 0..n {
        let zs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse::<usize>().unwrap() - 1)
            .collect();
        xss.push(zs);
    }
    let mut ixs: Vec<usize> = vec![0; n];
    let mut ds: Vec<usize> = vec![0; n];
    let mut i: usize = 0;
    let mut updated = false;
    loop {
        if ixs[i] < xss[i].len() {
            let j = xss[i][ixs[i]];
            if ixs[j] < xss[j].len() {
                let k = xss[j][ixs[j]];
                if i == k {
                    updated = true;
                    ixs[i] += 1;
                    ixs[j] += 1;
                    let d = max(ds[i], ds[j]) + 1;
                    ds[i] = d;
                    ds[j] = d;
                }
            }
        }
        i += 1;
        if n <= i {
            if !updated {
                break;
            }
            i = 0;
            updated = false;
        }
    }
    let ok = (0..n).all(|i| xss[i].len() == ixs[i]);
    if ok {
        println!("{}", ds.iter().max().unwrap());
    } else {
        println!("-1");
    }
}


Change-Making Problem

You want to make change for $n$ cents. Assuming that you have infinite supply of coins of 1, 5, 10 and/or 25 cents coins respectively, find the minimum number of coins you need.

Input

$n$

The integer $n$ is given in a line.

出力

Print the minimum number of coins you need in a line.

Constraints

$1 \le n \le 10^9$

Sample Input 1

100

Sample Output 1

4

Sample Input 2

54321

Sample Output 2

2175

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

  int n = cent / 25;
  cent -= (cent / 25) * 25;
  n += cent / 10;
  cent -= (cent / 10) * 10;
  n += cent / 5;
  cent -= (cent / 5) * 5;
  n += cent;

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

  return 0;
}

fn solution() {
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect("Input error");
    let mut change = input.trim().parse::<u64>().expect("Parse error");
    let mut total_coin = 0;
    if change >= 25 {
        total_coin += change / 25;
        change %= 25;
    }
    if change >= 10 {
        total_coin += change / 10;
        change %= 10;
    }
    if change >= 5 {
        total_coin += change / 5;
        change %= 5;
    }
    total_coin += change;
    println!("{}", total_coin);
}


Score : <var>500</var> points

Problem Statement

Ibis is fighting with a monster.

The health of the monster is <var>H</var>.

Ibis can cast <var>N</var> kinds of spells. Casting the <var>i</var>-th spell decreases the monster's health by <var>A_i</var>, at the cost of <var>B_i</var> Magic Points.

The same spell can be cast multiple times. There is no way other than spells to decrease the monster's health.

Ibis wins when the health of the monster becomes <var>0</var> or below.

Find the minimum total Magic Points that have to be consumed before winning.

Constraints

<var>1 \leq H \leq 10^4</var>

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

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

<var>1 \leq B_i \leq 10^4</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>N</var>
<var>A_1</var> <var>B_1</var>
<var>:</var>
<var>A_N</var> <var>B_N</var>

Output

Print the minimum total Magic Points that have to be consumed before winning.

Sample Input 1

9 3
8 3
4 2
2 1

Sample Output 1

4

First, let us cast the first spell to decrease the monster's health by <var>8</var>, at the cost of <var>3</var> Magic Points. The monster's health is now <var>1</var>.

Then, cast the third spell to decrease the monster's health by <var>2</var>, at the cost of <var>1</var> Magic Point. The monster's health is now <var>-1</var>.

In this way, we can win at the total cost of <var>4</var> Magic Points.

Sample Input 2

100 6
1 1
2 3
3 9
4 27
5 81
6 243

Sample Output 2

100

It is optimal to cast the first spell <var>100</var> times.

Sample Input 3

9999 10
540 7550
691 9680
700 9790
510 7150
415 5818
551 7712
587 8227
619 8671
588 8228
176 2461

Sample Output 3

139815

int solution() {
  int h;
  int n;
  scanf("%d%d", &h, &n);
  int a[n];
  int b[n];
  for (int i = 0; i < n; i++) {
    scanf("%d%d", a + i, b + i);
  }
  int dp[h + 1];
  for (int i = 0; i < h + 1; i++) {
    dp[i] = INT_MAX;
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < h + 1; j++) {
      if (j - a[i] <= 0) {
        if (dp[j] < b[i]) {
          continue;
        }
        dp[j] = b[i];

      } else if (dp[j] < dp[j - a[i]] + b[i]) {
        continue;
      } else {
        dp[j] = dp[j - a[i]] + b[i];
      }
    }
  }
  printf("%d\n", dp[h]);
  return 0;
}

fn solution() {
    let (h, waza) = {
        let mut i = String::new();
        io::stdin().read_line(&mut i).unwrap();
        let mut it = i.split_whitespace();
        let (h, n): (usize, usize) = {
            (
                it.next().unwrap().parse().unwrap(),
                it.next().unwrap().parse().unwrap(),
            )
        };
        let mut waza: Vec<(usize, usize)> = Vec::new();
        for _ in 0..n {
            let mut i = String::new();
            io::stdin().read_line(&mut i).unwrap();
            let mut it = i.split_whitespace();
            waza.push((
                it.next().unwrap().parse().unwrap(),
                it.next().unwrap().parse().unwrap(),
            ))
        }
        (h, waza)
    };

    let mut dp: Vec<usize> = Vec::new();
    dp.push(0);
    for i in 1..h + 1 {
        let mut min_mp = std::usize::MAX;
        for m in &waza {
            let tmp_mp = if i > m.0 { dp[i - m.0] + m.1 } else { m.1 };

            min_mp = std::cmp::min(min_mp, tmp_mp);
        }

        dp.push(min_mp);
    }
    println!("{}", dp[h]);
}


Nastia has $$$2$$$ positive integers $$$A$$$ and $$$B$$$. She defines that:  The integer is good if it is divisible by $$$A \cdot B$$$;  Otherwise, the integer is nearly good, if it is divisible by $$$A$$$. For example, if $$$A = 6$$$ and $$$B = 4$$$, the integers $$$24$$$ and $$$72$$$ are good, the integers $$$6$$$, $$$660$$$ and $$$12$$$ are nearly good, the integers $$$16$$$, $$$7$$$ are neither good nor nearly good.Find $$$3$$$ different positive integers $$$x$$$, $$$y$$$, and $$$z$$$ such that exactly one of them is good and the other $$$2$$$ are nearly good, and $$$x + y = z$$$.

int solution() {
  long long int t;
  long long int a[10000];
  long long int b[10000];
  long long int x[10000];
  long long int y[10000];
  long long int z[10000];
  long long int c[10000];
  long long int k[10000];
  scanf("%lld", &t);
  for (int i = 0; i < t; i++) {
    k[i] = 0;
    scanf("%lld %lld", &a[i], &b[i]);
    if (b[i] != 1) {
      k[i]++;
      x[i] = a[i];
      y[i] = a[i] * b[i];
      z[i] = x[i] + y[i];
    } else {
      continue;
    }
  }
  for (int j = 0; j < t; j++) {
    if (k[j] == 1) {
      printf("YES\n%lld %lld %lld\n", x[j], y[j], z[j]);
    } else {
      printf("NO\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(|x| x.unwrap());

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

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

        if b == 1 {
            writeln!(&mut output, "NO").unwrap();
            continue;
        }

        let x = a;
        let y = a * (2 * b - 1);
        let z = x + y;

        writeln!(&mut output, "YES\n{} {} {}", x, y, z).unwrap();
    }
}


Score : <var>600</var> points

Problem Statement

Given is an integer sequence <var>A_1, ..., A_N</var> of length <var>N</var>.

We will choose exactly <var>\left\lfloor \frac{N}{2} \right\rfloor</var> elements from this sequence so that no two adjacent elements are chosen.

Find the maximum possible sum of the chosen elements.

Here <var>\lfloor x \rfloor</var> denotes the greatest integer not greater than <var>x</var>.

Constraints

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

<var>|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>A_1</var> <var>...</var> <var>A_N</var>

Output

Print the maximum possible sum of the chosen elements.

Sample Input 1

6
1 2 3 4 5 6

Sample Output 1

12

Choosing <var>2</var>, <var>4</var>, and <var>6</var> makes the sum <var>12</var>, which is the maximum possible value.

Sample Input 2

5
-1000 -100 -10 0 10

Sample Output 2

0

Choosing <var>-10</var> and <var>10</var> makes the sum <var>0</var>, which is the maximum possible value.

Sample Input 3

10
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

5000000000

Watch out for overflow.

Sample Input 4

27
18 -28 18 28 -45 90 -45 23 -53 60 28 -74 -71 35 -26 -62 49 -77 57 24 -70 -93 69 -99 59 57 -49

Sample Output 4

295

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let line = lines.next().unwrap().unwrap();
    let n: usize = line.parse().unwrap();
    let line = lines.next().unwrap().unwrap();
    let xs: Vec<i64> = line.split(' ').map(|x| x.parse().unwrap()).collect();
    let mut memo: Vec<i64> = vec![0; n];
    let mut leftmost: i64 = xs[0];
    for i in 1..n {
        if i == 1 {
            memo[i] = max(xs[0], xs[1]);
        } else if i % 2 == 0 {
            leftmost += xs[i];
            memo[i] = max(memo[i - 2] + xs[i], memo[i - 1]);
        } else {
            memo[i] = max(leftmost, memo[i - 2] + xs[i]);
        }
    }
    println!("{}", memo[n - 1]);
}


Score : <var>300</var> points

Problem Statement

Given is a string <var>S</var>. Let <var>T</var> be the concatenation of <var>K</var> copies of <var>S</var>.
We can repeatedly perform the following operation: choose a character in <var>T</var> and replace it with a different character.
Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in <var>T</var> are different.

Constraints

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

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum number of operations required.

Sample Input 1

issii
2

Sample Output 1

4

<var>T</var> is issiiissii.  For example, we can rewrite it into ispiqisyhi, and now any two adjacent characters are different.

Sample Input 2

qq
81

Sample Output 2

81

Sample Input 3

cooooooooonteeeeeeeeeest
999993333

Sample Output 3

8999939997

int solution() {
  char s[101];
  long long k;
  scanf("%s %lld", s, &k);
  int l = strlen(s);
  if (l == 1) {
    printf("%lld", k / 2);
    return 0;
  }
  int inner = 0;
  int cnt = 0;
  int uni = 0;
  for (int i = 0; i < l; i++) {
    if (s[i] == s[i + 1]) {
      cnt++;
    } else if (cnt) {
      inner += (cnt + 1) / 2;
      if (cnt == l - 1) {
        uni = 1;
      }
      cnt = 0;
    }
  }
  if (uni == 1) {
    printf("%lld", l * k / 2);
    return 0;
  }
  int head = 1;
  int tail = 1;
  int chk = 0;
  long long ans = inner * k;
  if (s[0] == s[l - 1]) {
    chk = 2;
    if (s[0] == s[1]) {
      int i = 0;
      while (s[i] == s[i + 1]) {
        head++;
        i++;
      }
    }
    if (s[l - 1] == s[l - 2]) {
      int i = 0;
      while (s[l - (1 + i)] == s[l - (2 + i)]) {
        tail++;
        i++;
      }
    }
  }

  if (chk == 2 && head % 2 == 1 && tail % 2 == 1) {
    ans += (k - 1);
  }
  printf("%lld", ans);

  return 0;
}

fn solution() {
    let S: Vec<char> = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().chars().collect()
    };
    let K: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };

    let N = S.len();
    let ans = if S.iter().collect::<std::collections::HashSet<_>>().len() == 1 {
        N * K / 2
    } else if S[0] == S[N - 1] {
        let c = S[0];
        let l = (0..N).take_while(|&i| S[i] == c).count();
        let r = (0..N).rev().take_while(|&i| S[i] == c).count();
        let (m, _) = (l..(N - r)).fold((0, '-'), |(res, prev), i| {
            if S[i] == prev {
                (res + 1, '-')
            } else {
                (res, S[i])
            }
        });
        l / 2 + m * K + (l + r) / 2 * (K - 1) + r / 2
    } else {
        let (m, _) = (0..N).fold((0, '-'), |(res, prev), i| {
            if S[i] == prev {
                (res + 1, '-')
            } else {
                (res, S[i])
            }
        });
        m * K
    };

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


Score : <var>200</var> points

Problem Statement

You are visiting a large electronics store to buy a refrigerator and a microwave.

The store sells <var>A</var> kinds of refrigerators and <var>B</var> kinds of microwaves. The <var>i</var>-th refrigerator ( <var>1 \le i \le A</var> ) is sold at <var>a_i</var> yen (the currency of Japan), and the <var>j</var>-th microwave ( <var>1 \le j \le B</var> ) is sold at <var>b_j</var> yen.

You have <var>M</var> discount tickets. With the <var>i</var>-th ticket ( <var>1 \le i \le M</var> ), you can get a discount of <var>c_i</var> yen from the total price when buying the <var>x_i</var>-th refrigerator and the <var>y_i</var>-th microwave together. Only one ticket can be used at a time.

You are planning to buy one refrigerator and one microwave. Find the minimum amount of money required.

Constraints

All values in input are integers.

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

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

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

<var> 1 \le a_i , b_i , c_i \le 10^5 </var>

<var> 1 \le x_i \le A </var>

<var> 1 \le y_i \le B </var>

<var> c_i \le a_{x_i} + b_{y_i} </var>

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var> <var>M</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_A</var>
<var>b_1</var> <var>b_2</var> <var>...</var> <var>b_B</var>
<var>x_1</var> <var>y_1</var> <var>c_1</var>
<var>\vdots</var>
<var>x_M</var> <var>y_M</var> <var>c_M</var>

Output

Print the answer.

Sample Input 1

2 3 1
3 3
3 3 3
1 2 1

Sample Output 1

5

With the ticket, you can get the <var>1</var>-st refrigerator and the <var>2</var>-nd microwave for <var>3+3-1=5</var> yen.

Sample Input 2

1 1 2
10
10
1 1 5
1 1 10

Sample Output 2

10

Note that you cannot use more than one ticket at a time.

Sample Input 3

2 2 1
3 5
3 5
2 2 2

Sample Output 3

6

You can get the <var>1</var>-st refrigerator and the <var>1</var>-st microwave for <var>6</var> yen, which is the minimum amount to pay in this case.
Note that using a ticket is optional.

int solution(void) {
  int i = 0;
  int rei = 0;
  int densi = 0;
  int m = 0;
  scanf("%d", &rei);
  scanf("%d", &densi);
  scanf("%d", &m);
  int rprice[rei];
  int dprice[densi];
  int waribiki1[rei];
  int waribiki2[densi];
  int a[m];
  int b[m];
  int c[m];
  int rmin = 100000;
  for (i = 0; i < rei; i++) {
    scanf("%d", &rprice[i]);
    if (rprice[i] < rmin) {
      rmin = rprice[i];
    }
  }
  int dmin = 100000;
  for (i = 0; i < densi; i++) {
    scanf("%d", &dprice[i]);
    if (dprice[i] < dmin) {
      dmin = dprice[i];
    }
  }
  for (i = 0; i < m; i++) {
    scanf("%d", &a[i]);
    scanf("%d", &b[i]);
    scanf("%d", &c[i]);
  }
  int min = 0;
  min = rmin + dmin;
  for (i = 0; i < m; i++) {
    if (rprice[a[i] - 1] + dprice[b[i] - 1] - c[i] < min) {
      min = rprice[a[i] - 1] + dprice[b[i] - 1] - c[i];
    }
  }
  printf("%d", min);
  return 0;
}

fn solution() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    input! {
      a: usize,
      b: usize,
      m: usize,
      aa: [i64; a],
      bb: [i64; b],
      ti: [(usize1, usize1, i64); m],
    }
    let mut ans = 1i64 << 60;
    for &(ai, bi, c) in &ti {
        ans = cmp::min(ans, aa[ai] + bb[bi] - c);
    }
    let am = aa.iter().min().unwrap();
    let bm = bb.iter().min().unwrap();
    ans = cmp::min(ans, am + bm);

    puts!("{}\n", ans);
}


Codeforces separates its users into $$$4$$$ divisions by their rating:  For Division 1: $$$1900 \leq \mathrm{rating}$$$  For Division 2: $$$1600 \leq \mathrm{rating} \leq 1899$$$  For Division 3: $$$1400 \leq \mathrm{rating} \leq 1599$$$  For Division 4: $$$\mathrm{rating} \leq 1399$$$ Given a $$$\mathrm{rating}$$$, print in which division the $$$\mathrm{rating}$$$ belongs.

fn solution() {
    let mut input_line = String::new();
    io::stdin()
        .read_line(&mut input_line)
        .expect("Failed to read line");

    let nt: u32 = input_line.trim().parse().expect("Failed to read line");

    for _tc in 0..nt {
        let mut input_line = String::new();
        io::stdin()
            .read_line(&mut input_line)
            .expect("Failed to read line");
        let r: i32 = input_line.trim().parse().expect("Input is not integer");

        match r {
            -5000..=1399 => println!("Division 4"),
            1400..=1599 => println!("Division 3"),
            1600..=1899 => println!("Division 2"),
            1900..=5000 => println!("Division 1"),
            _ => {}
        }
    }
}


Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($$$\frac{a}{b}$$$ and $$$\frac{c}{d}$$$) with integer numerators and denominators. Then children are commanded to play with their fractions.Burenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by $$$0$$$). Now she wants know the minimal number of claps to make her fractions equal (by value). Please help her and find the required number of claps!

int solution(void) {
  int i;
  int j;
  scanf("%d", &i);
  long long a[i];
  long long b[i];
  long long c[i];
  long long d[i];
  long long x;
  long long y;
  for (j = 0; j < i; j++) {
    scanf("%lld %lld %lld %lld", &a[j], &b[j], &c[j], &d[j]);
  }
  for (j = 0; j < i; j++) {
    x = a[j] * d[j];
    y = b[j] * c[j];
    if (x == y) {
      printf("0");
    } else if (a[j] == 0 || c[j] == 0 || x % y == 0 || y % x == 0) {
      printf("1");
    } else {
      printf("2");
    }
    printf("\n");
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s).unwrap();
    let mut mp = s.split_whitespace().map(|x| x.parse::<usize>().unwrap());

    let t = mp.next().unwrap();
    let mut s = String::new();

    for _ in 0..t {
        let (a, b, c, d) = (
            mp.next().unwrap(),
            mp.next().unwrap(),
            mp.next().unwrap(),
            mp.next().unwrap(),
        );

        let x = a * d;
        let y = b * c;

        if x == y {
            s += "0\n";
        } else if x == 0 || y == 0 {
            s += "1\n";
        } else if x % y == 0 || y % x == 0 {
            s += "1\n";
        } else {
            s += "2\n";
        }
    }

    print!("{}", s.trim());
}