Score : <var>400</var> points

Problem Statement

There are <var>N</var> squares arranged in a row, numbered <var>1, 2, ..., N</var> from left to right.
You are given a string <var>S</var> of length <var>N</var> consisting of . and #. If the <var>i</var>-th character of <var>S</var> is #, Square <var>i</var> contains a rock; if the <var>i</var>-th character of <var>S</var> is ., Square <var>i</var> is empty.

In the beginning, Snuke stands on Square <var>A</var>, and Fnuke stands on Square <var>B</var>.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square <var>C</var> and Fnuke will stand on Square <var>D</var>.

Determine whether this is possible.

Constraints

<var>4 \leq N \leq 200\ 000</var>

<var>S</var> is a string of length <var>N</var> consisting of . and #.

<var>1 \leq A, B, C, D \leq N</var>

Square <var>A</var>, <var>B</var>, <var>C</var> and <var>D</var> do not contain a rock.

<var>A</var>, <var>B</var>, <var>C</var> and <var>D</var> are all different.

<var>A < B</var>

<var>A < C</var>

<var>B < D</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes

int solution(void) {
  int n;
  int a;
  int b;
  int c;
  int d;
  scanf("%d%d%d%d%d", &n, &a, &b, &c, &d);
  char s[n + 5];
  scanf("%s", s);
  s[n] = '#';
  s[n + 1] = '#';
  s[a - 1] = 'A';
  s[b - 1] = 'B';
  bool ac = false, bd = false, change = false;
  while (1) {
    change = false;
    if (s[a] == '.' && ac == false) {
      s[a - 1] = '.';
      a++;
      s[a - 1] = 'A';
      change = true;
    } else if (s[a + 1] == '.' && ac == false) {
      s[a - 1] = '.';
      a += 2;
      s[a - 1] = 'A';
      change = true;
    } else if (s[b] == '.' && bd == false) {
      s[b - 1] = '.';
      b++;
      s[b - 1] = 'B';
      change = true;
    } else if (s[b + 1] == '.' && bd == false) {
      s[b - 1] = '.';
      b += 2;
      s[b - 1] = 'B';
      change = true;
    }
    if (a == c) {
      ac = true;
    }
    if (b == d) {
      bd = true;
    }
    if (ac == true && bd == true) {
      printf("Yes\n");
      break;
    }
    if (change == false) {
      printf("No\n");
      break;
    }
  }
  return 0;
}

fn solution() {
    input! {
        n: usize,
        a: usize1,
        b: usize1,
        c: usize1,
        d: usize1,
        s: chars,
    }
    let mut ans = true;
    for i in 0..n {
        if a < i && (i < c || i < d) && s[i] == '#' && s[i + 1] == '#' {
            ans = false;
        }
    }
    if d < c {
        let mut between = false;
        for i in b..d + 1 {
            if s[i - 1] == '.' && s[i] == '.' && s[i + 1] == '.' {
                between = true;
            }
        }
        if !between {
            ans = false;
        }
    }
    println!("{}", if ans { "Yes" } else { "No" })
}


Score : <var>100</var> points

Problem Statement

Takahashi has decided to distribute <var>N</var> AtCoder Crackers to <var>K</var> users of as evenly as possible.
When all the crackers are distributed, find the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>

Output

Print the minimum possible (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user.

Sample Input 1

7 3

Sample Output 1

1

When the users receive two, two and three crackers, respectively, the (absolute) difference between the largest number of crackers received by a user and the smallest number received by a user, is <var>1</var>.

Sample Input 2

100 10

Sample Output 2

0

The crackers can be distributed evenly.

Sample Input 3

1 1

Sample Output 3

0

int solution(void) {
  int N;
  int K;
  int min = 0;
  int max = 0;

  scanf("%d %d", &N, &K);
  while (N >= K) {
    N -= K;
    min++;
  }
  if (N == 0) {
    max = min;
  } else {
    max = min + 1;
  }
  printf("%d", max - min);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut s = String::new();
    stdin.read_line(&mut s).ok();
    let iter = s.split_whitespace();
    let mut numbers = Vec::new();
    for arg in iter {
        numbers.push(u64::from_str(arg).expect("e"));
    }
    let n: u64 = numbers[0];
    let k: u64 = numbers[1];
    if n.is_multiple_of(k) {
        println!("0");
    } else {
        println!("1");
    }
}


Score : <var>400</var> points

Problem Statement

You are given a string <var>S</var> of length <var>N</var> consisting of ( and ). Your task is to insert some number of ( and ) into <var>S</var> to obtain a correct bracket sequence.

Here, a correct bracket sequence is defined as follows:

() is a correct bracket sequence.

If <var>X</var> is a correct bracket sequence, the concatenation of (, <var>X</var> and ) in this order is also a correct bracket sequence.

If <var>X</var> and <var>Y</var> are correct bracket sequences, the concatenation of <var>X</var> and <var>Y</var> in this order is also a correct bracket sequence.

Every correct bracket sequence can be derived from the rules above.

Find the shortest correct bracket sequence that can be obtained. If there is more than one such sequence, find the lexicographically smallest one.

Constraints

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

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

<var>S</var> consists of ( and ).

Input

Input is given from Standard Input in the following format:

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

Output

Print the lexicographically smallest string among the shortest correct bracket sequences that can be obtained by inserting some number of ( and ) into <var>S</var>.

Sample Input 1

3
())

Sample Output 1

(())

Sample Input 2

6
)))())

Sample Output 2

(((()))())

Sample Input 3

8
))))((((

Sample Output 3

(((())))(((())))

int solution(void) {
  int N = 0;
  int i = 0;
  char buffer[256];
  int count = 0;
  int left = 0;

  scanf("%d", &N);
  scanf("%s", buffer);

  for (i = 0; i < N; i++) {
    if (buffer[i] == '(') {
      count++;
    } else if (buffer[i] == ')') {
      count--;
      if (count < 0) {
        left++;
        count++;
      }
    }
  }

  for (i = 0; i < left; i++) {
    printf("(");
  }

  printf("%s", buffer);

  for (i = 0; i < count; i++) {
    printf(")");
  }

  printf("\n");

  return 0;
}

fn solution() {
    let mut n = String::new();
    let mut line = String::new();
    let _ = io::stdin().read_line(&mut n);
    let _ = io::stdin().read_line(&mut line);
    line = line.split_whitespace().collect();
    let mut openCnt = line.match_indices("(").count();
    let mut closeCnt = line.match_indices(")").count();
    let mut misMatch = 0;
    let mut matchCnt = 0;
    for c in line.chars() {
        if c == '(' {
            misMatch += 1;
        } else if misMatch > 0 {
            misMatch -= 1;
            matchCnt += 1;
        }
    }
    openCnt -= matchCnt;
    closeCnt -= matchCnt;
    for _ in 0..closeCnt {
        line = "(".to_string() + line.as_str();
    }
    for _ in 0..openCnt {
        line.push(')');
    }
    println!("{}", line);
}


You are given the strings $$$a$$$ and $$$b$$$, consisting of lowercase Latin letters. You can do any number of the following operations in any order:   if $$$|a| > 0$$$ (the length of the string $$$a$$$ is greater than zero), delete the first character of the string $$$a$$$, that is, replace $$$a$$$ with $$$a_2 a_3 \ldots a_n$$$;  if $$$|a| > 0$$$, delete the last character of the string $$$a$$$, that is, replace $$$a$$$ with $$$a_1 a_2 \ldots a_{n-1}$$$;  if $$$|b| > 0$$$ (the length of the string $$$b$$$ is greater than zero), delete the first character of the string $$$b$$$, that is, replace $$$b$$$ with $$$b_2 b_3 \ldots b_n$$$;  if $$$|b| > 0$$$, delete the last character of the string $$$b$$$, that is, replace $$$b$$$ with $$$b_1 b_2 \ldots b_{n-1}$$$. Note that after each of the operations, the string $$$a$$$ or $$$b$$$ may become empty.For example, if $$$a=$$$"hello" and $$$b=$$$"icpc", then you can apply the following sequence of operations:   delete the first character of the string $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"icpc";  delete the first character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"cpc";  delete the first character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ello" and $$$b=$$$"pc";  delete the last character of the string $$$a$$$ $$$\Rightarrow$$$ $$$a=$$$"ell" and $$$b=$$$"pc";  delete the last character of the string $$$b$$$ $$$\Rightarrow$$$ $$$a=$$$"ell" and $$$b=$$$"p". For the given strings $$$a$$$ and $$$b$$$, find the minimum number of operations for which you can make the strings $$$a$$$ and $$$b$$$ equal. Note that empty strings are also equal.

int solution() {
  int t;
  scanf("%d", &t);
  getchar();
  for (int j = 1; j <= t; j++) {
    int a = 0;
    int b = 0;
    int max = 0;
    int count = 0;
    char s1[20];
    char s2[20];
    char c = getchar();
    while (c != '\n' && c != -1) {
      s1[a++] = c;
      c = getchar();
    }
    c = getchar();
    while (c != '\n' && c != -1) {
      s2[b++] = c;
      c = getchar();
    }
    for (int k = 0; k < a; k++) {
      for (int l = 0; l < b; l++) {
        if (s1[k] == s2[l]) {
          int x = k;
          int y = l;
          while (x < a && y < b && s1[x] == s2[y]) {
            count++;
            x++;
            y++;
          }
          if (count >= max) {
            max = count;
          }
          count = 0;
        }
      }
    }

    printf("%d\n", a + b - (2 * max));
  }
  return 0;
}

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

    let tc: usize = sc.next();
    for _ in 0..tc {
        let a: Vec<char> = sc.next::<String>().chars().collect();
        let b: Vec<char> = sc.next::<String>().chars().collect();
        let mut sub_strings: HashSet<String> = HashSet::new();
        for i in 0..a.len() {
            for j in i..a.len() {
                sub_strings.insert((i..=j).map(|i| a[i]).collect());
            }
        }
        let mut ans: usize = 0;
        for i in 0..b.len() {
            for j in i..b.len() {
                if sub_strings.contains(&(i..=j).map(|i| b[i]).collect::<String>()) {
                    ans = max(ans, 2 * (j - i + 1));
                }
            }
        }
        writeln!(out, "{}", a.len() + b.len() - ans).unwrap();
    }
}


Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.

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

    let n: usize = s.trim().parse().unwrap();
    let mut v: Vec<String> = vec![];

    for _ in 0..n {
        let mut s = String::new();
        stdin.read_line(&mut s).unwrap();
        v.push(s.trim().to_string());
    }

    let mut r: Vec<Vec<i32>> = vec![vec![0; n]; n];

    for (i, line) in v.iter().enumerate() {
        for (j, c) in line.chars().enumerate() {
            if c == 'o' {
                if i > 0 {
                    r[i - 1][j] += 1;
                }
                if i < n - 1 {
                    r[i + 1][j] += 1;
                }
                if j > 0 {
                    r[i][j - 1] += 1;
                }
                if j < n - 1 {
                    r[i][j + 1] += 1;
                }
            }
        }
    }

    for line in r {
        for cell in line {
            if cell % 2 == 1 {
                println!("NO");
                return;
            }
        }
    }

    println!("YES");
}


Score : <var>100</var> points

Problem Statement

We have <var>A</var> balls with the string <var>S</var> written on each of them and <var>B</var> balls with the string <var>T</var> written on each of them.

From these balls, Takahashi chooses one with the string <var>U</var> written on it and throws it away.

Find the number of balls with the string <var>S</var> and balls with the string <var>T</var> that we have now.

Constraints

<var>S</var>, <var>T</var>, and <var>U</var> are strings consisting of lowercase English letters.

The lengths of <var>S</var> and <var>T</var> are each between <var>1</var> and <var>10</var> (inclusive).

<var>S \not= T</var>

<var>S=U</var> or <var>T=U</var>.

<var>1 \leq A,B \leq 10</var>

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

Input

Input is given from Standard Input in the following format:

<var>S</var> <var>T</var>
<var>A</var> <var>B</var>
<var>U</var>

Output

Print the answer, with space in between.

Sample Input 1

red blue
3 4
red

Sample Output 1

2 4

Takahashi chose a ball with red written on it and threw it away.
Now we have two balls with the string <var>S</var> and four balls with the string <var>T</var>.

Sample Input 2

red blue
5 5
blue

Sample Output 2

5 4

Takahashi chose a ball with blue written on it and threw it away.
Now we have five balls with the string <var>S</var> and four balls with the string <var>T</var>.

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

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let st: Vec<String> = buf.split_whitespace().map(|w| w.to_string()).collect();
    buf.clear();
    std::io::stdin().read_line(&mut buf).unwrap();
    let mut ab: Vec<i32> = buf.split_whitespace().map(|w| w.parse().unwrap()).collect();
    buf.clear();
    std::io::stdin().read_line(&mut buf).unwrap();
    let u: String = buf.trim().to_string();
    if st[0] == u {
        ab[0] -= 1;
    } else {
        ab[1] -= 1;
    }
    println!("{} {}", ab[0], ab[1]);
}


Score : <var>300</var> points

Problem Statement

We have a sequence of <var>N</var> integers <var>A~=~A_0,~A_1,~...,~A_{N - 1}</var>.

Let <var>B</var> be a sequence of <var>K \times N</var> integers obtained by concatenating <var>K</var> copies of <var>A</var>. For example, if <var>A~=~1,~3,~2</var> and <var>K~=~2</var>, <var>B~=~1,~3,~2,~1,~3,~2</var>.

Find the inversion number of <var>B</var>, modulo <var>10^9 + 7</var>.

Here the inversion number of <var>B</var> is defined as the number of ordered pairs of integers <var>(i,~j)~(0 \leq i < j \leq K \times N - 1)</var> such that  <var>B_i > B_j</var>.

Constraints

All values in input are integers.

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>A_0</var> <var>A_1</var> <var>...</var> <var>A_{N - 1}</var>

Output

Print the inversion number of <var>B</var>, modulo <var>10^9 + 7</var>.

Sample Input 1

2 2
2 1

Sample Output 1

3

In this case, <var>B~=~2,~1,~2,~1</var>. We have:

<var>B_0 > B_1</var>

<var>B_0 > B_3</var>

<var>B_2 > B_3</var>

Thus, the inversion number of <var>B</var> is <var>3</var>.

Sample Input 2

3 5
1 1 1

Sample Output 2

0

<var>A</var> may contain multiple occurrences of the same number.

Sample Input 3

10 998244353
10 9 8 7 5 6 3 4 2 1

Sample Output 3

185297239

Be sure to print the output modulo <var>10^9 + 7</var>.

int solution(void) {
  long long n;
  long long a[2005];
  long long k;
  long long count = 0;
  scanf("%lld %lld", &n, &k);
  for (int j = 0; j < n; j++) {
    scanf("%lld", &a[j]);
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      if (a[i] > a[j]) {
        if (i < j) {
          count += k * (k + 1) / 2;
        } else {
          count += k * (k - 1) / 2;
        }
      }
      count %= 1000000007;
    }
  }
  k = k % 1000000007;
  count = count % 1000000007;
  printf("%lld\n", count);
  return 0;
}

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

    let MOD = 1_000_000_007;
    let K_1 = ((K * (K + 1)) / 2) % MOD;
    let K_2 = ((K * (K - 1)) / 2) % MOD;
    let ans = {
        let mut res = 0;
        for i in 0..N {
            let mut x = 0;
            for j in (i + 1)..N {
                if A[i] > A[j] {
                    x += 1;
                }
            }
            let mut y = 0;
            for j in 0..i {
                if A[i] > A[j] {
                    y += 1;
                }
            }
            x = (x * K_1) % MOD;
            y = (y * K_2) % MOD;
            res = (res + x) % MOD;
            res = (res + y) % MOD;
        }
        res
    };

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


You are given a positive integer $$$n$$$. Your task is to find any three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \le a, b, c \le 10^9$$$) for which $$$(a\oplus b)+(b\oplus c)+(a\oplus c)=n$$$, or determine that there are no such integers.Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.

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

fn solution() {
    let mut test_cases = String::new();
    io::stdin()
        .read_line(&mut test_cases)
        .expect("Failed to read test_cases");
    let test_cases: u32 = test_cases
        .trim()
        .parse()
        .expect("Failed to convert test_cases from String to u32");

    let mut solved = 0;
    loop {
        if solved == test_cases {
            break;
        }

        let mut n = String::new();
        io::stdin().read_line(&mut n).expect("Failed to read n");

        let n: u32 = n
            .trim()
            .parse()
            .expect("Failed to convert n from String to int");

        if n % 2 == 1 {
            println!("{}", -1);
        } else {
            println!("{} {} {}", n / 2, n / 2, 0);
        }

        solved += 1
    }
}


After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.Help guys determine the winner photo by the records of likes.

int solution() {
  int a[1000001] = {0};
  int n;
  int tmp;
  scanf("%d", &n);

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

    if (a[tmp] > a[max]) {
      max = tmp;
    }
  }

  printf("%d", max);
  return 0;
}

fn solution() {
    let mut input_text = String::new();
    io::stdin().read_to_string(&mut input_text).unwrap();
    let mut iter = input_text
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap());
    let _n = iter.next().unwrap();
    let a: Vec<i32> = iter.collect();
    let mut map = HashMap::<i32, i32>::new();
    let mut current_winner = -1;
    let mut current_max = 0;
    for vote in a {
        let new_vote_count = map.get(&vote).unwrap_or(&0) + 1;
        map.insert(vote, new_vote_count);
        if new_vote_count > current_max {
            current_max = new_vote_count;
            current_winner = vote;
        }
    }
    println!("{}", current_winner);
}


Score : <var>300</var> points

Problem Statement

Given any integer <var>x</var>, Aoki can do the operation below.

Operation: Replace <var>x</var> with the absolute difference of <var>x</var> and <var>K</var>.

You are given the initial value of an integer <var>N</var>. Find the minimum possible value taken by <var>N</var> after Aoki does the operation zero or more times.

Constraints

<var>0 ≤ N ≤ 10^{18}</var>

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>

Output

Print the minimum possible value taken by <var>N</var> after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, <var>N=7</var>.

After one operation, <var>N</var> becomes <var>|7-4| = 3</var>.

After two operations, <var>N</var> becomes <var>|3-4| = 1</var>, which is the minimum value taken by <var>N</var>.

Sample Input 2

2 6

Sample Output 2

2

<var>N=2</var> after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0

int solution() {
  long long int N;
  long long int K;
  long long int i;
  long long int j;
  long long int l;
  long long int m;

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

  if (N < K && K < N / 2) {
    printf("%lld\n", N);
  } else if (N < K && K > N / 2) {
    m = -(N - K);
    if (N > m) {
      printf("%lld\n", m);
    } else {
      printf("%lld\n", N);
    }
  }

  else if (N >= K && ((N % K) == 0 || K == 1)) {
    printf("0\n");
  } else if (N > K && !(N % K) == 0) {
    j = N % K;
    l = j - K;
    if (j < l) {
      printf("%lld\n", j);
    } else {
      printf("%lld\n", -l);
    }
  }
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let mut itr = s.split_whitespace().map(|e| e.parse().unwrap());
    let n: i64 = itr.next().unwrap();
    let k: i64 = itr.next().unwrap();

    let a = n / k;
    println!("{}", min((n - a * k).abs(), (n - (a + 1) * k).abs()));
}


You are given an integer $$$n$$$ and an integer $$$k$$$.In one step you can do one of the following moves:   decrease $$$n$$$ by $$$1$$$;  divide $$$n$$$ by $$$k$$$ if $$$n$$$ is divisible by $$$k$$$. For example, if $$$n = 27$$$ and $$$k = 3$$$ you can do the following steps: $$$27 \rightarrow 26 \rightarrow 25 \rightarrow 24 \rightarrow 8 \rightarrow 7 \rightarrow 6 \rightarrow 2 \rightarrow 1 \rightarrow 0$$$.You are asked to calculate the minimum number of steps to reach $$$0$$$ from $$$n$$$.

int solution(void) {
  int t;
  scanf("%d", &t);
  long long num[t];
  long long n;
  long long k;
  long long c = 0;
  for (int i = 0; i < t; i++, c = 0) {
    scanf("%lli%lli", &n, &k);
    while (n > 0) {
      if (n % k == 0) {
        n = n / k;
        c++;
      } else if (n % k != 0) {
        c = c + n % k;
        n = n - (n % k);
      }
    }
    num[i] = c;
  }
  for (int i = 0; i < t; i++) {
    printf("%lli\n", num[i]);
  }
  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let t: i64 = line.trim().parse::<i64>().expect("error");
    for _ in 0..t {
        line.clear();
        io::stdin().read_line(&mut line).unwrap();
        let r: Vec<i64> = line
            .trim()
            .split(' ')
            .map(|x| x.parse::<i64>().expect("error"))
            .collect();
        let mut n = r[0];
        let mut s = 0;
        let k = r[1];
        while n > 0 {
            let x = n % k;
            if x == 0 {
                n /= k;
                s += 1;
            } else {
                n -= x;
                s += x;
            }
        }
        println!("{:?}", s);
    }
}


You are given a string $$$s$$$, consisting only of characters '0' or '1'. Let $$$|s|$$$ be the length of $$$s$$$.You are asked to choose some integer $$$k$$$ ($$$k > 0$$$) and find a sequence $$$a$$$ of length $$$k$$$ such that:   $$$1 \le a_1 < a_2 < \dots < a_k \le |s|$$$;  $$$a_{i-1} + 1 < a_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k$$$. The characters at positions $$$a_1, a_2, \dots, a_k$$$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $$$a$$$ should not be adjacent.Let the resulting string be $$$s'$$$. $$$s'$$$ is called sorted if for all $$$i$$$ from $$$2$$$ to $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.Does there exist such a sequence $$$a$$$ that the resulting string $$$s'$$$ is sorted?

int solution() {
  int t;
  scanf("%d", &t);
  getchar();
  for (int j = 1; j <= t; j++) {
    int flag = 0;
    int flag2 = 0;
    char c = getchar();
    char prev;
    while (c != '\n' && c != -1) {
      prev = c;
      c = getchar();
      if (c == '1' && c == prev && flag != 1) {
        flag = 1;
      }
      if (flag && c == '0' && c == prev && flag2 == 0) {
        printf("NO\n");
        flag2 = 1;
      }
    }
    if (flag2 == 0) {
      printf("YES\n");
    }
  }
  return 0;
}

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

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

    let t: usize = scan!(usize);
    for _ in 1..=t {
        let s = scan!(chars);
        let n = s.len();
        let mut min11 = n + 2;
        let mut max00 = n + 2;
        for i in 1..n {
            if s[i - 1] == '1' && s[i] == '1' {
                min11 = i;
                break;
            }
        }
        for i in (1..n - 1).rev() {
            if s[i + 1] == '0' && s[i] == '0' {
                max00 = i;
                break;
            }
        }
        if min11 < n && max00 < n && min11 <= max00 {
            print!("NO");
        } else {
            print!("YES");
        }
        print!("\n");
    }
}


Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column;  if $$$i < n$$$ and $$$|h_i - h_{i+1}| \le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

fn solution() {
    let mut sout = BufWriter::new(io::stdout());
    let mut sin = BufReader::new(io::stdin());
    let mut buf = String::new();
    sin.read_line(&mut buf).unwrap();
    let t: usize = buf.trim().parse().unwrap();
    for _i in 0..t {
        buf = String::new();
        sin.read_line(&mut buf).unwrap();
        let buf_wp: Vec<isize> = buf
            .split_whitespace()
            .map(|it| it.trim().parse().unwrap())
            .collect();
        let (n, mut m, k) = (buf_wp[0] as usize, buf_wp[1], buf_wp[2]);
        buf = String::new();
        sin.read_line(&mut buf).unwrap();
        let mut h: Vec<isize> = buf
            .split_whitespace()
            .map(|it| it.trim().parse().unwrap())
            .collect();
        let mut failed = false;
        for i in 0..(n - 1) {
            m += h[i] - max(0, h[i + 1] - k);
            if m < 0 {
                failed = true;
                break;
            }
            h[i] = max(0, h[i + 1] - k);
        }
        if failed {
            writeln!(sout, "NO");
        } else {
            writeln!(sout, "YES");
        }
    }
}


You are given $$$n$$$ arrays $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$; each array consists of exactly $$$m$$$ integers. We denote the $$$y$$$-th element of the $$$x$$$-th array as $$$a_{x, y}$$$.You have to choose two arrays $$$a_i$$$ and $$$a_j$$$ ($$$1 \le i, j \le n$$$, it is possible that $$$i = j$$$). After that, you will obtain a new array $$$b$$$ consisting of $$$m$$$ integers, such that for every $$$k \in [1, m]$$$ $$$b_k = \max(a_{i, k}, a_{j, k})$$$.Your goal is to choose $$$i$$$ and $$$j$$$ so that the value of $$$\min \limits_{k = 1}^{m} b_k$$$ is maximum possible.

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

    let arr = buffer
        .split_whitespace()
        .map(|x| x.parse::<usize>().expect("convert to number"))
        .collect::<Vec<_>>();

    let n = arr[0];
    let m = arr[1];

    let matrix: Vec<_> = (0..n).map(|i| &arr[2 + i * m..2 + i * m + m]).collect();

    let combinations = 2usize.pow(m as u32);

    let (mut l, mut r) = (0, 1_000_000_001);

    let mut val_best = 0;
    let mut indices_chosen = None;

    while l + 1 < r {
        let mid = (l + r) / 2;

        let mut bitmasks = vec![false; combinations];
        let mut indices = vec![0; combinations];

        for (index, i) in matrix.iter().enumerate() {
            let mut mask = 0;
            for (ix, j) in i.iter().enumerate() {
                if j >= &mid {
                    mask |= 1 << ix;
                }
            }
            bitmasks[mask] = true;
            indices[mask] = index;
        }

        let mut found = false;
        'outer: for i in 0..combinations {
            for j in 0..combinations {
                let present = bitmasks[i] && bitmasks[j];

                let pattern: usize = i | j;
                if (pattern == combinations - 1) && present {
                    if mid >= val_best {
                        indices_chosen = Some((indices[i], indices[j]));
                        val_best = mid;
                    }
                    found = true;
                    break 'outer;
                }
            }
        }

        if found {
            l = mid;
        } else {
            r = mid;
        }
    }

    match indices_chosen {
        Some(x) => {
            println!("{} {}", x.0 + 1, x.1 + 1);
        }
        _ => {
            println!("1 1");
        }
    }
}


Score : <var>300</var> points

Problem Statement

Snuke is making sugar water in a beaker.
Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.

Operation 1: Pour <var>100A</var> grams of water into the beaker.

Operation 2: Pour <var>100B</var> grams of water into the beaker.

Operation 3: Put <var>C</var> grams of sugar into the beaker.

Operation 4: Put <var>D</var> grams of sugar into the beaker.

In our experimental environment, <var>E</var> grams of sugar can dissolve into <var>100</var> grams of water.

Snuke will make sugar water with the highest possible density.

The beaker can contain at most <var>F</var> grams of substances (water and sugar combined), and there must not be any undissolved sugar in the beaker.
Find the mass of the sugar water Snuke will make, and the mass of sugar dissolved in it.
If there is more than one candidate, any of them will be accepted.

We remind you that the sugar water that contains <var>a</var> grams of water and <var>b</var> grams of sugar is <var>\frac{100b}{a + b}</var> percent.
Also, in this problem, pure water that does not contain any sugar is regarded as <var>0</var> percent density sugar water.

Constraints

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

<var>1 \leq C < D \leq 30</var>

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

<var>100A \leq F \leq 3</var> <var>000</var>

<var>A</var>, <var>B</var>, <var>C</var>, <var>D</var>, <var>E</var> and <var>F</var> are all integers.

Inputs

Input is given from Standard Input in the following format:

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

Outputs

Print two integers separated by a space.
The first integer should be the mass of the desired sugar water, and the second should be the mass of the sugar dissolved in it.

Sample Input 1

1 2 10 20 15 200

Sample Output 1

110 10

In this environment, <var>15</var> grams of sugar can dissolve into <var>100</var> grams of water, and the beaker can contain at most <var>200</var> grams of substances.

We can make <var>110</var> grams of sugar water by performing Operation 1 once and Operation 3 once.
It is not possible to make sugar water with higher density.
For example, the following sequences of operations are infeasible:

If we perform Operation 1 once and Operation 4 once, there will be undissolved sugar in the beaker.

If we perform Operation 2 once and Operation 3 three times, the mass of substances in the beaker will exceed <var>200</var> grams.

Sample Input 2

1 2 1 2 100 1000

Sample Output 2

200 100

There are other acceptable outputs, such as:

400 200

However, the output below is not acceptable:

300 150

This is because, in order to make <var>300</var> grams of sugar water containing <var>150</var> grams of sugar, we need to pour exactly <var>150</var> grams of water into the beaker, which is impossible.

Sample Input 3

17 19 22 26 55 2802

Sample Output 3

2634 934

fn solution() {
    input! {
        a: usize,
        b: usize,
        c: usize,
        d: usize,
        e: usize,
        f: usize,
    }

    let mut mizu;
    let mut sato;
    let mut candidate = Vec::with_capacity(1_000);

    for ac in 0..f / (100 * a) + 1 {
        for bc in 0..(f - ac * a * 100) / (100 * b) + 1 {
            mizu = (a * ac + b * bc) * 100;
            if mizu == 0 {
                continue;
            }
            for cc in 0..(f - mizu) / c + 1 {
                for dc in 0..(f - mizu - c * cc) / d + 1 {
                    sato = c * cc + d * dc;
                    if sato <= e * (mizu / 100) {
                        candidate.push((mizu, sato));
                    }
                }
            }
        }
    }

    let mut cand = candidate[0];
    for &c in candidate.iter() {
        if cand.0 * c.1 > cand.1 * c.0 {
            cand = c
        }
    }
    println!("{} {}", cand.0 + cand.1, cand.1);
}


God's Blessing on This PermutationForces!A Random PebbleYou are given a permutation $$$p_1,p_2,\ldots,p_n$$$ of length $$$n$$$ and a positive integer $$$k \le n$$$. In one operation you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i < j \le n$$$) and swap $$$p_i$$$ with $$$p_j$$$.Find the minimum number of operations needed to make the sum $$$p_1 + p_2 + \ldots + p_k$$$ as small as possible.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

int solution() {
  int t;
  scanf("%d\n", &t);
  for (int p = 0; p < t; p++) {
    int ans = 0;
    int n;
    int k;
    scanf("%d  %d\n", &n, &k);
    int arr[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      if (arr[i] > k && i < k) {
        ans++;
      }
    }
    printf("%d \n", ans);
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut iterator = stdin.lock().lines();
    let line = iterator.next().unwrap().unwrap();
    let amount = line.parse::<i32>().unwrap();
    for _i in 0..amount {
        let line: String = iterator.next().unwrap().unwrap();
        let strings: Vec<&str> = line.split(" ").collect();
        let n = strings.first().unwrap().parse::<i32>().unwrap();
        let k = strings.get(1).unwrap().parse::<i32>().unwrap();
        let line: String = iterator.next().unwrap().unwrap();
        let strings: Vec<&str> = line.split(" ").collect();
        let mut numbers = vec![];
        for i in 0..n {
            numbers.push(strings.get(i as usize).unwrap().parse::<i32>().unwrap());
        }
        let mut sorted: Vec<i32> = numbers.clone();
        sorted.sort();
        let max = sorted.get(k as usize - 1).unwrap();
        let mut result = 0;
        for i in 0..k {
            if numbers.get(i as usize).unwrap() > max {
                result += 1;
            }
        }
        println!("{}", result);
    }
}


Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

int solution(void) {

  int points_count = 0;
  scanf("%d", &points_count);

  int max_distance = 0;
  scanf("%d", &max_distance);

  int bicycles_count = 1;
  int current_position = 0;
  scanf("%d", &current_position);
  int available_distance = max_distance;
  for (int i = 1; i < points_count; i++) {
    int next_position = 0;
    scanf("%d", &next_position);
    if ((current_position + max_distance) < next_position) {
      bicycles_count = -1;
      break;
    }

    if (next_position <= (current_position + available_distance)) {
      available_distance -= (next_position - current_position);
      current_position = next_position;
    } else {
      available_distance = max_distance - (next_position - current_position);
      current_position = next_position;
      bicycles_count++;
    }
  }

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

  return 0;
}

fn solution() {
    let mut s: String = String::new();
    stdin().read_line(&mut s);
    let k: i32 = s[s.find(' ').unwrap() + 1..s.len()]
        .trim()
        .parse::<i32>()
        .unwrap();
    s.clear();
    stdin().read_line(&mut s);
    let a: Vec<i32> = s
        .split_whitespace()
        .map(|s| s.parse::<i32>().unwrap())
        .collect();
    let mut b: Vec<i32> = Vec::new();
    for c in 0..a.len() - 1 {
        b.push(a[c + 1] - a[c])
    }
    let mut i: usize = 0;
    let mut l: i32 = k;
    let mut x: i32 = 1;
    let mut d: i32 = 0;
    while i < b.len() {
        if l - b[i] < 0 {
            if d == 2 {
                println!("-1");
                return;
            }
            l = k;
            x += 1;
            d += 1;
        } else {
            l -= b[i];
            i += 1;
            d = 0;
        }
    }
    println!("{}", x);
}


Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm.Let's consider that initially array contains n numbers from 1 to n and the number i is located in the cell with the index 2i - 1 (Indices are numbered starting from one) and other cells of the array are empty. Each step Dima selects a non-empty array cell with the maximum index and moves the number written in it to the nearest empty cell to the left of the selected one. The process continues until all n numbers will appear in the first n cells of the array. For example if n = 4, the array is changing as follows:  You have to write a program that allows you to determine what number will be in the cell with index x (1 ≤ x ≤ n) after Dima's algorithm finishes.

int solution() {

  long long n;
  long long q;
  long long p;
  scanf("%lld%lld", &n, &q);
  while (q--) {
    scanf("%lld", &p);
    while (!(p & 1)) {
      p = p + (n - (p / 2));
    }
    printf("%lld\n", (p + 1) / 2);
  }
  return 0;
}

fn solution() {
    use std::io::stdin;

    let mut line = String::new();

    let n: u64;
    let q: u32;

    {
        stdin().read_line(&mut line);
        let parts: Vec<&str> = line.split_whitespace().collect();
        n = parts[0].parse().expect("n");
        q = parts[1].parse().expect("q");
    }

    for _ in 0..q {
        line.clear();
        stdin().read_line(&mut line);
        let mut xi: u64 = line.trim().parse().expect("xi");
        while (xi & 1) == 0 {
            xi = xi + n - (xi >> 1)
        }
        println!("{}", (xi + 1) >> 1);
    }
}


AquaMoon had $$$n$$$ strings of length $$$m$$$ each. $$$n$$$ is an odd number.When AquaMoon was gone, Cirno tried to pair these $$$n$$$ strings together. After making $$$\frac{n-1}{2}$$$ pairs, she found out that there was exactly one string without the pair!In her rage, she disrupted each pair of strings. For each pair, she selected some positions (at least $$$1$$$ and at most $$$m$$$) and swapped the letters in the two strings of this pair at the selected positions.For example, if $$$m = 6$$$ and two strings "abcdef" and "xyzklm" are in one pair and Cirno selected positions $$$2$$$, $$$3$$$ and $$$6$$$ she will swap 'b' with 'y', 'c' with 'z' and 'f' with 'm'. The resulting strings will be "ayzdem" and "xbcklf".Cirno then stole away the string without pair and shuffled all remaining strings in arbitrary order.AquaMoon found the remaining $$$n-1$$$ strings in complete disarray. Also, she remembers the initial $$$n$$$ strings. She wants to know which string was stolen, but she is not good at programming. Can you help her?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int m;
    scanf("%d %d", &n, &m);
    char s[m];
    char cnt[m];
    for (int i = 0; i < m; i++) {
      cnt[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      scanf("%s", s);
      for (int j = 0; j < m; j++) {
        cnt[j] += s[j];
      }
    }
    for (int i = 0; i < n - 1; i++) {
      scanf("%s", s);
      for (int j = 0; j < m; j++) {
        cnt[j] -= s[j];
      }
    }
    for (int i = 0; i < m; i++) {
      printf("%c", cnt[i]);
    }
    printf("\n");
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(Result::unwrap);
    let t: u16 = lines.next().unwrap().parse().unwrap();

    for _ in 0..t {
        let (n, m): (usize, usize) = {
            let line = lines.next().unwrap();
            let mut words = line.split(' ');
            (
                words.next().unwrap().parse().unwrap(),
                words.next().unwrap().parse().unwrap(),
            )
        };

        let mut bits = vec![0_u32; m];

        for _ in 0..(2 * n - 1) {
            let line = lines.next().unwrap();
            for (b, c) in bits.iter_mut().zip(line.as_bytes()) {
                *b ^= 1 << (c - b'a');
            }
        }

        let word: Box<[u8]> = bits
            .into_iter()
            .map(|b| b.trailing_zeros() as u8 + b'a')
            .collect();

        println!("{}", str::from_utf8(&word).unwrap());
    }
}


YouKn0wWho has two even integers $$$x$$$ and $$$y$$$. Help him to find an integer $$$n$$$ such that $$$1 \le n \le 2 \cdot 10^{18}$$$ and $$$n \bmod x = y \bmod n$$$. Here, $$$a \bmod b$$$ denotes the remainder of $$$a$$$ after division by $$$b$$$. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.

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

fn solution() -> std::io::Result<()> {
    let mut input = String::new();
    stdin().read_to_string(&mut input)?;

    let mut input_iter = input.split_whitespace();
    let mut next_int = || input_iter.next().unwrap().parse::<i64>().unwrap();

    for _ in 0..next_int() {
        let x = next_int();
        let y = next_int();

        let res = if x == y {
            x
        } else if x > y {
            x + y
        } else {
            y - y % x / 2
        };

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

    Ok(())
}


Score : <var>600</var> points

Problem Statement

Find the number of sequences of length <var>K</var> consisting of positive integers such that the product of any two adjacent elements is at most <var>N</var>, modulo <var>10^9+7</var>.

Constraints

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

<s>1</s> <var>2\leq K\leq 100</var> (fixed at 21:33 JST)

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>

Output

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

Sample Input 1

3 2

Sample Output 1

5

<var>(1,1)</var>, <var>(1,2)</var>, <var>(1,3)</var>, <var>(2,1)</var>, and <var>(3,1)</var> satisfy the condition.

Sample Input 2

10 3

Sample Output 2

147

Sample Input 3

314159265 35

Sample Output 3

457397712

int solution() {
  long long int N;
  long long int K;
  scanf("%lld %lld", &N, &K);
  long long int m;
  m = 1000000000 + 7;
  long long int dp[101][100001];
  long long int a[100001];
  long long int b[100001];
  long long int i;
  long long int j;
  long long int k;
  k = 0;
  long long int l;
  long long int s;
  long long int c;
  long long int d;
  long long int ans;
  ans = 0;
  for (c = 1; c <= N; c = d + 1) {
    d = N / (N / c);
    k = k + 1;
    a[k] = c;
    b[k] = d;
  }
  dp[0][1] = 1;
  for (i = 1; i <= K; i++) {
    l = 0;
    s = 0;
    for (j = k; j >= 1; j--) {
      if (l + 1 <= k && a[l + 1] * a[j] <= N) {
        l = l + 1;
        s = (s + dp[i - 1][l]) % m;
      }
      dp[i][j] = ((b[j] - a[j] + 1) * s) % m;
      if (i == K) {
        ans = (ans + dp[K][j]) % m;
      }
    }
  }
  printf("%lld", ans);
}

fn solution() {
    input! {
        n: usize,
        k: usize
    }
    let d = 1000000007;
    let mut sq = 1;
    while sq * sq <= n {
        sq += 1;
    }
    sq -= 1;
    let m = n / (sq + 1);
    let len = sq + m;
    let mut c = vec![0; m];
    for i in 0..m {
        c[i] = (n / (m - i) - n / (m + 1 - i)) % d;
    }
    let mut dp = vec![vec![0; len]; k + 1];
    dp[0][0] = 1;
    for i in 1..k + 1 {
        let mut ac = vec![0; len];
        ac[0] = dp[i - 1][0];
        for j in 1..len {
            ac[j] = (ac[j - 1] + dp[i - 1][j]) % d;
        }
        for j in 0..sq {
            dp[i][j] = ac[len - j - 1];
        }
        for j in 0..m {
            dp[i][sq + j] = c[j] * ac[n / (n / (m - j)) - 1] % d;
        }
    }
    println!("{}", dp[k].iter().fold(0, |ac, x| (ac + x) % d));
}


Matrix Vector Multiplication

Write a program which reads a $ n \times m$ matrix $A$  and a $m \times 1$ vector $b$, and prints their product $Ab$.

  A column vector with <var>m</var> elements is represented by the following equation.

\[
  b = \left(
    \begin{array}{c}
      b_1  \\
      b_2  \\
      : \\
      b_m \\
    \end{array}
  \right)
\]

  A $n \times m$ matrix with $m$ column vectors, each of which consists of $n$ elements, is represented by the following equation.

\[
  A = \left(
    \begin{array}{cccc}
      a_{11} & a_{12} & ... & a_{1m} \\
      a_{21} & a_{22} & ... & a_{2m} \\
       :    &   :   &  :  &  : \\
      a_{n1} & a_{n2} & ... & a_{nm} \\
    \end{array}
  \right)
\]

  $i$-th element of a $m \times 1$ column vector $b$ is represented by $b_i$ ($i = 1, 2, ..., m$), and the element in $i$-th row and $j$-th column of a matrix $A$ is represented by $a_{ij}$ ($i = 1, 2, ..., n,$  $j = 1, 2, ..., m$).

The product of a $n \times m$ matrix $A$ and a $m \times 1$ column vector $b$ is a $n \times 1$ column vector $c$, and $c_i$ is obtained by the following formula:

\[
c_i = \sum_{j=1}^m a_{ij}b_j  = a_{i1}b_1 + a_{i2}b_2 + ... + a_{im}b_m
\]

Input

  In the first line, two integers $n$ and $m$ are given. In the following $n$ lines, $a_{ij}$ are given separated by a single space character. In the next $m$ lines, $b_i$ is given in a line.

Output

  The output consists of $n$ lines. Print $c_i$ in a line.

Constraints

$1 \leq n, m \leq 100$

$0 \leq b_i, a_{ij} \leq 1000$

Sample Input

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

Sample Output

5
6
9

fn solution() {
    let stdin = std::io::stdin();
    let lines = stdin
        .lock()
        .lines()
        .filter_map(|x| x.ok())
        .collect::<Vec<_>>();

    let mut ite1 = lines[0]
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());
    let n = ite1.next().unwrap();
    let m = ite1.next().unwrap();

    let vec_a = lines[1..n + 1]
        .iter()
        .map(|line| {
            line.split_whitespace()
                .map(|x| x.parse::<i32>().unwrap())
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();

    let vec_b = lines[n + 1..n + 1 + m]
        .iter()
        .map(|line| line.trim().parse::<i32>().unwrap())
        .collect::<Vec<_>>();

    for a in vec_a {
        let sum = a.iter().zip(vec_b.iter()).map(|(a, b)| a * b).sum::<i32>();
        println!("{}", sum);
    }
}


Score : <var>700</var> points

Problem Statement

Takahashi is locked within a building.

This building consists of <var>H×W</var> rooms, arranged in <var>H</var> rows and <var>W</var> columns.
We will denote the room at the <var>i</var>-th row and <var>j</var>-th column as <var>(i,j)</var>. The state of this room is represented by a character <var>A_{i,j}</var>. If <var>A_{i,j}=</var> #, the room is locked and cannot be entered; if <var>A_{i,j}=</var> ., the room is not locked and can be freely entered.
Takahashi is currently at the room where <var>A_{i,j}=</var> S, which can also be freely entered.

Each room in the <var>1</var>-st row, <var>1</var>-st column, <var>H</var>-th row or <var>W</var>-th column, has an exit.
Each of the other rooms <var>(i,j)</var> is connected to four rooms: <var>(i-1,j)</var>, <var>(i+1,j)</var>, <var>(i,j-1)</var> and <var>(i,j+1)</var>.

Takahashi will use his magic to get out of the building. In one cast, he can do the following:

Move to an adjacent room at most <var>K</var> times, possibly zero. Here, locked rooms cannot be entered.

Then, select and unlock at most <var>K</var> locked rooms, possibly zero. Those rooms will remain unlocked from then on.

His objective is to reach a room with an exit. Find the minimum necessary number of casts to do so.

It is guaranteed that Takahashi is initially at a room without an exit.

Constraints

<var>3 ≤ H ≤ 800</var>

<var>3 ≤ W ≤ 800</var>

<var>1 ≤ K ≤ H×W</var>

Each <var>A_{i,j}</var> is # , .  or S.

There uniquely exists <var>(i,j)</var> such that <var>A_{i,j}=</var> S, and it satisfies <var>2 ≤ i ≤ H-1</var> and <var>2 ≤ j ≤ W-1</var>.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum necessary number of casts.

Sample Input 1

3 3 3
#.#
#S.
###

Sample Output 1

1

Takahashi can move to room <var>(1,2)</var> in one cast.

Sample Input 2

3 3 3
###
#S#
###

Sample Output 2

2

Takahashi cannot move in the first cast, but can unlock room <var>(1,2)</var>.
Then, he can move to room <var>(1,2)</var> in the next cast, achieving the objective in two casts.

Sample Input 3

7 7 2
#######
#######
##...##
###S###
##.#.##
###.###
#######

Sample Output 3

2

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let h = it.next().unwrap().parse::<usize>().unwrap();
    let w = it.next().unwrap().parse::<usize>().unwrap();
    let k = it.next().unwrap().parse::<usize>().unwrap();
    let s = (0..h)
        .map(|_| it.next().unwrap().as_bytes())
        .collect::<Vec<_>>();
    let mut res = h * w;
    for i in 0..h {
        for j in 0..w {
            if s[i][j] != b'S' {
                continue;
            }
            let mut dist = vec![vec![h * w; w]; h];
            let mut qu = VecDeque::new();
            dist[i][j] = 0;
            qu.push_back((i, j));
            let dx = [-1, 0, 1, 0];
            let dy = [0, -1, 0, 1];
            while !qu.is_empty() {
                let (cx, cy) = qu.pop_front().unwrap();
                res = std::cmp::min(
                    res,
                    [cx, h - cx - 1, cy, w - cy - 1]
                        .iter()
                        .min()
                        .unwrap()
                        .div_ceil(k)
                        + 1,
                );
                if cx == 0 || cx == h - 1 || cy == 0 || cy == w - 1 {
                    continue;
                }
                if dist[cx][cy] == k {
                    continue;
                }
                for dir in 0..4 {
                    let nx = (cx as i32 + dx[dir]) as usize;
                    let ny = (cy as i32 + dy[dir]) as usize;
                    if s[nx][ny] == b'#' {
                        continue;
                    }
                    if dist[cx][cy] + 1 >= dist[nx][ny] {
                        continue;
                    }
                    dist[nx][ny] = dist[cx][cy] + 1;
                    qu.push_back((nx, ny));
                }
            }
        }
    }
    println!("{}", res);
}


This is the easy version of the problem. The only difference is that in this version $$$n \leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

int solution() {
  int n;
  int kt = 0;
  int N;
  scanf("%d", &n);
  N = n;
  long long a[n];
  long long i;
  long long sum;
  long long I;
  long long min;
  long long imin;
  for (i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
  }
mn:
  sum = 0;
  for (i = 0; i < n; i++) {
    sum += a[i];
    if (sum < 0) {
      I = i;
      kt = 1;
      break;
    }
  }
  if (kt == 1) {
    min = 1000000000;
    for (i = 0; i <= I; i++) {
      if (min > a[i]) {
        min = a[i];
        imin = i;
      }
    }
    a[imin] = 0;
    N--;
    kt = 0;
    goto mn;
  }
  printf("%d", N);
  return 0;
}

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

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

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

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

    let mut h = std::collections::BinaryHeap::new();
    let mut s = 0;

    let mut p = 0;

    for a in lines
        .next()
        .unwrap()
        .split_whitespace()
        .map(|a| a.parse::<i64>().unwrap())
    {
        if a < 0 {
            let x = -a;
            h.push(x);
            s -= x;
            while s < 0 {
                let x = h.pop().unwrap();
                s += x;
            }
        } else {
            p += 1;
            s += a;
        }
    }

    let ans = p + h.len();

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


Let's call left cyclic shift of some string $$$t_1 t_2 t_3 \dots t_{n - 1} t_n$$$ as string $$$t_2 t_3 \dots t_{n - 1} t_n t_1$$$.Analogically, let's call right cyclic shift of string $$$t$$$ as string $$$t_n t_1 t_2 t_3 \dots t_{n - 1}$$$.Let's say string $$$t$$$ is good if its left cyclic shift is equal to its right cyclic shift.You are given string $$$s$$$ which consists of digits 0–9.What is the minimum number of characters you need to erase from $$$s$$$ to make it good?

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

    for _ in 0..t {
        let s: Vec<u32> = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            buf.trim_end()
                .chars()
                .map(|c| c.to_digit(10).unwrap())
                .collect()
        };

        let mut ans = std::usize::MAX;
        for i in 0..=9 {
            for j in 0..=9 {
                let mut res = {
                    s.iter().fold(0, |acc, &x| {
                        if acc % 2 == 0 && x == i {
                            acc + 1
                        } else if acc % 2 == 1 && x == j {
                            acc + 1
                        } else {
                            acc
                        }
                    })
                };
                if i != j {
                    res = res / 2 * 2;
                }
                ans = std::cmp::min(ans, s.len() - res);
            }
        }
        println!("{}", ans);
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi loves gold coins. He gains <var>1000</var> happiness points for each <var>500</var>-yen coin he has and gains <var>5</var> happiness points for each <var>5</var>-yen coin he has. (Yen is the currency of Japan.)

Takahashi has <var>X</var> yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?

(We assume that there are six kinds of coins available: <var>500</var>-yen, <var>100</var>-yen, <var>50</var>-yen, <var>10</var>-yen, <var>5</var>-yen, and <var>1</var>-yen coins.)

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

Print the maximum number of happiness points that can be earned.

Sample Input 1

1024

Sample Output 1

2020

By exchanging his money so that he gets two <var>500</var>-yen coins and four <var>5</var>-yen coins, he gains <var>2020</var> happiness points, which is the maximum number of happiness points that can be earned.

Sample Input 2

0

Sample Output 2

0

He is penniless - or yenless.

Sample Input 3

1000000000

Sample Output 3

2000000000

He is a billionaire - in yen.

int solution(void) {
  int money = 0;
  scanf("%d", &money);
  int big_gold = money / 500;
  money -= 500 * big_gold;
  int small_gold = money / 5;
  int point = (big_gold * 1000) + (small_gold * 5);
  printf("%d", point);
  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let mut x = s.trim().parse::<i64>().unwrap();
    let ans = x / 500 * 1000;
    x %= 500;
    x = x / 5 * 5;

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


Score : <var>500</var> points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers <var>N</var> kinds of dishes. It takes <var>A_i</var> minutes to eat the <var>i</var>-th dish, whose deliciousness is <var>B_i</var>.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After <var>T-0.5</var> minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

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

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

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

<var>1 \leq B_i \leq 3000</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be <var>110</var>.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within <var>60</var> minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be <var>50</var>.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut wv: Vec<(usize, usize)> = (0..n)
        .map(|_| {
            (
                itr.next().unwrap().parse().unwrap(),
                itr.next().unwrap().parse().unwrap(),
            )
        })
        .collect();
    wv.sort();

    let mut dp = vec![0; t + 1];
    for i in 0..n {
        for j in (0..t).rev() {
            dp[j] = max(dp[j], dp[j]);
            dp[min(t, j + wv[i].0)] = max(dp[min(t, j + wv[i].0)], dp[j] + wv[i].1);
        }
    }
    println!("{}", dp[t]);
}


You are given an integer $$$x$$$ and an array of integers $$$a_1, a_2, \ldots, a_n$$$. You have to determine if the number $$$a_1! + a_2! + \ldots + a_n!$$$ is divisible by $$$x!$$$.Here $$$k!$$$ is a factorial of $$$k$$$ — the product of all positive integers less than or equal to $$$k$$$. For example, $$$3! = 1 \cdot 2 \cdot 3 = 6$$$, and $$$5! = 1 \cdot 2 \cdot 3 \cdot 4 \cdot 5 = 120$$$.

int solution() {
  int n;
  int k;
  scanf("%d%d", &n, &k);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  int count[k + 1];
  for (int i = 0; i < k + 1; i++) {
    count[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    count[a[i]]++;
  }
  int ans = 1;
  for (int i = 0; i < k; i++) {
    if (count[i] % (i + 1) == 0) {
      count[i + 1] = count[i + 1] + count[i] / (i + 1);
    } else {
      ans = 0;
      break;
    }
  }
  if (ans == 1) {
    printf("Yes");
  } else {
    printf("No");
  }
  return 0;
}

fn solution() {
    input! {
        n: usize,
        x: usize,
        a: [usize; n],
    }
    let mut count = vec![0; 500_002];
    for i in 0..n {
        count[a[i]] += 1;
    }
    for i in 1..=500_000 {
        count[i + 1] += count[i] / (i + 1);
        count[i] %= i + 1;
    }
    if count[..x].iter().all(|&c| c == 0) {
        println!("Yes");
    } else {
        println!("No");
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> towns in a coordinate plane. Town <var>i</var> is located at coordinates (<var>x_i</var>, <var>y_i</var>). The distance between Town <var>i</var> and Town <var>j</var> is <var>\sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}</var>.

There are <var>N!</var> possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, <var>\dots</var>, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these <var>N!</var> paths.

Constraints

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

<var>-1000 \leq x_i \leq 1000</var>

<var>-1000 \leq y_i \leq 1000</var>

<var>\left(x_i, y_i\right) \neq \left(x_j, y_j\right)</var> (if <var>i \neq j</var>)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>x_1</var> <var>y_1</var>
<var>:</var>
<var>x_N</var> <var>y_N</var>

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most <var>10^{-6}</var>.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: <var>1</var> → <var>2</var> → <var>3</var>, <var>1</var> → <var>3</var> → <var>2</var>, <var>2</var> → <var>1</var> → <var>3</var>, <var>2</var> → <var>3</var> → <var>1</var>, <var>3</var> → <var>1</var> → <var>2</var>, and <var>3</var> → <var>2</var> → <var>1</var>.

The length of the path <var>1</var> → <var>2</var> → <var>3</var> is <var>\sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}</var>.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

<var>\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...</var>

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: <var>1</var> → <var>2</var> and <var>2</var> → <var>1</var>. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
    let mut x = Vec::new();
    let mut y = Vec::new();
    for _ in 0..n {
        let x_y = lines.next().unwrap().unwrap();
        let mut x_y = x_y.split_whitespace();
        x.push(x_y.next().unwrap().parse::<f64>().unwrap());
        y.push(x_y.next().unwrap().parse::<f64>().unwrap());
    }

    let mut ans = 0.0;
    for i in 0..n {
        for j in 0..n {
            let d = (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
            ans += d.sqrt();
        }
    }
    ans /= n as f64;

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


Score : <var>100</var> points

Problem Statement

A string of length <var>6</var> consisting of lowercase English letters is said to be coffee-like if and only if its <var>3</var>-rd and <var>4</var>-th characters are equal and its <var>5</var>-th and <var>6</var>-th characters are also equal.

Given a string <var>S</var>, determine whether it is coffee-like.

Constraints

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the <var>3</var>-rd and <var>4</var>-th characters are equal, and the <var>5</var>-th and <var>6</var>-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes

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

    if coffee[2] == coffee[3] && coffee[4] == coffee[5] {
        println!("Yes");
    } else {
        println!("No");
    }
}


Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is different in evenness.

int solution() {
  int n;
  int countEven = 0;
  int countOdd = 0;
  int a = 0;
  int b = 0;
  int result = 0;
  int num[101];
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &num[i]);
  }
  for (int j = 1; j <= n; j++) {
    if (num[j] % 2 == 0) {
      countEven++;
      if (countEven == 1) {
        b = j;
      }
      if (countEven > 1 && countOdd == 1) {
        result = a;
        break;
      }
      if (countOdd > 1 && countEven == 1) {
        result = b;
        break;
      }
    }
    if (num[j] % 2 != 0) {
      countOdd++;
      if (countOdd == 1) {
        a = j;
      }
      if (countOdd > 1 && countEven == 1) {
        result = b;
        break;
      }
      if (countEven > 1 && countOdd == 1) {
        result = a;
        break;
      }
    }
  }
  printf("%d", result);
  return 0;
}

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

    let mut line = String::new();

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

    let words: Vec<i64> = line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let guess: Vec<i64> = words.clone().into_iter().filter(|x| x % 2 == 0).collect();

    let mut answer = 1;

    let mut evenness = 0;

    if guess.len() > 1 {
        evenness = 1;
    }

    for (idx, item) in words.into_iter().enumerate() {
        if item % 2 == evenness {
            answer = idx;
        }
    }

    println!("{}", answer + 1);
}


You are given a rectangular grid with $$$n$$$ rows and $$$m$$$ columns. The cell located on the $$$i$$$-th row from the top and the $$$j$$$-th column from the left has a value $$$a_{ij}$$$ written in it.You can perform the following operation any number of times (possibly zero):  Choose any two adjacent cells and multiply the values in them by $$$-1$$$. Two cells are called adjacent if they share a side. Note that you can use a cell more than once in different operations.You are interested in $$$X$$$, the sum of all the numbers in the grid. What is the maximum $$$X$$$ you can achieve with these operations?

fn solution() {
    let stream = io::stdin();

    let mut line = String::new();
    stream.read_line(&mut line).expect("Missing t");
    let t: i32 = line.trim().parse().expect("t is not a number");

    for _n in 0..t {
        let mut test_case_line = String::new();
        stream
            .read_line(&mut test_case_line)
            .expect("Missing number");

        let mut n: i32 = 0;
        let mut m: i32 = 0;
        for val in test_case_line.split(" ") {
            let num: i32 = val.trim().parse().expect("Invalid format");
            if n == 0 {
                n = num;
            } else {
                m = num;
            }
        }

        let mut min_positive_number = 101;
        let mut negative_number_count = 0;
        let mut result = 0;

        for _i in 0..n {
            let mut l = String::new();
            stream.read_line(&mut l).expect("Missing line");

            let mut v: Vec<i32> = Vec::new();
            for val in l.trim().split(" ") {
                v.push(val.parse().expect("Invalid format"));
            }

            for mut val in v {
                if val < 0 {
                    val = -val;
                    negative_number_count += 1;
                }

                min_positive_number = min(min_positive_number, val);
                result += val;
            }
        }

        if negative_number_count % 2 == 1 {
            result -= 2 * min_positive_number;
        }

        println!("{}", result)
    }
}


Score : <var>200</var> points

Problem Statement

We have a board with <var>H</var> horizontal rows and <var>W</var> vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the <var>r_1</var>-th row (from the top) and the <var>c_1</var>-th column (from the left) to the square at the <var>r_2</var>-th row and the <var>c_2</var>-th column if and only if exactly one of the following holds:

<var>r_1 + c_1 = r_2 + c_2</var>

<var>r_1 - c_1 = r_2 - c_2</var>

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>H \ W</var>

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000

int solution() {
  long long int lli_CellHeight = 0;
  long long int lli_CellWidth = 0;

  (void)scanf("%lld %lld", &lli_CellHeight, &lli_CellWidth);

  long long int lli_Ans = (lli_CellHeight * lli_CellWidth) / 2;
  if ((lli_CellHeight % 2 == 1) && (lli_CellWidth % 2 == 1)) {
    lli_Ans += 1;
  }
  if ((lli_CellHeight == 1) || (lli_CellWidth == 1)) {
    lli_Ans = 1;
  }

  (void)printf("%lld\n", lli_Ans);

  return 0;
}

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let input_vec: Vec<i64> = buffer
        .split_whitespace()
        .map(|c| c.parse().unwrap())
        .collect();

    let height = input_vec[0];
    let width = input_vec[1];
    if height == 1 || width == 1 {
        println!("{}", 1);
    } else {
        println!("{}", (width * height + 1) / 2);
    }
}


Define the score of some binary string $$$T$$$ as the absolute difference between the number of zeroes and ones in it. (for example, $$$T=$$$ 010001 contains $$$4$$$ zeroes and $$$2$$$ ones, so the score of $$$T$$$ is $$$|4-2| = 2$$$).Define the creepiness of some binary string $$$S$$$ as the maximum score among all of its prefixes (for example, the creepiness of $$$S=$$$ 01001 is equal to $$$2$$$ because the score of the prefix $$$S[1 \ldots 4]$$$ is $$$2$$$ and the rest of the prefixes have a score of $$$2$$$ or less).Given two integers $$$a$$$ and $$$b$$$, construct a binary string consisting of $$$a$$$ zeroes and $$$b$$$ ones with the minimum possible creepiness.

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

    let mut lines = content.lines();
    let num_tests: i32 = lines.next().unwrap().parse().unwrap();
    for _ in 0..num_tests {
        let arr: Vec<usize> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse().unwrap())
            .collect();
        let a = arr[0];
        let b = arr[1];
        let mut result = "01".repeat(min(a, b));
        if a < b {
            result += &"1".repeat(b - a);
        } else {
            result += &"0".repeat(a - b);
        }
        println!("{result}");
    }
}


Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?

int solution() {
  int d = 0;
  int l;

  scanf("%d %d", &d, &l);

  int lanterna[d];

  for (int i = 0; i < d; i++) {
    scanf("%d", &lanterna[i]);
  }
  for (int j = d - 1; j >= 1; j--) {
    for (int k = 0; k < j; k++) {
      if (lanterna[k] > lanterna[k + 1]) {
        int maior = lanterna[k];
        lanterna[k] = lanterna[k + 1];
        lanterna[k + 1] = maior;
      }
    }
  }

  double raio = lanterna[0] * 2;
  double aux = (l - lanterna[d - 1]) * 2;
  if (raio < aux) {
    raio = aux;
  }

  for (int i = 0; i < d - 1; i++) {
    if (raio < lanterna[i + 1] - lanterna[i]) {
      raio = lanterna[i + 1] - lanterna[i];
    }
  }
  printf("%f", raio / 2);
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let arr: Vec<i32> = s.split_whitespace().map(|s| s.parse().unwrap()).collect();
    let (_n, k) = (arr[0], arr[1]);
    let mut v = vec![0, k];
    s.clear();
    io::stdin().read_line(&mut s).unwrap();
    let arr: Vec<i32> = s.split_whitespace().map(|s| s.parse().unwrap()).collect();
    for c in arr {
        v.push(c);
    }
    v.sort();
    let mut ans = -1;
    for i in 1..v.len() {
        let mut tmp = v[i] - v[(i - 1)];
        if i == 1 || i == v.len() - 1 {
            tmp *= 2;
        }
        if ans < tmp {
            ans = tmp;
        }
    }
    println!("{}", ans as f64 / 2.0);
}


void solution(unsigned long long arr[], size_t n) {
  if (n == 0)
    return;

  unsigned long long max = arr[0];

  for (size_t i = 1; i < n; i++) {
    if (arr[i] > max)
      max = arr[i];
  }

  size_t radix = 1;

  while (radix < n) {
    radix <<= 1;
  }

  unsigned long long *output = malloc(n * sizeof(unsigned long long));

  size_t *counter = malloc(radix * sizeof(size_t));

  if (!output || !counter) {
    free(output);
    free(counter);
    return;
  }

  unsigned long long place = 1;

  while (place <= max) {

    memset(counter, 0, radix * sizeof(size_t));

    for (size_t i = 0; i < n; i++) {
      size_t digit = (arr[i] / place) % radix;

      counter[digit]++;
    }

    for (size_t i = 1; i < radix; i++) {
      counter[i] += counter[i - 1];
    }

    for (size_t i = n; i > 0; i--) {
      unsigned long long value = arr[i - 1];

      size_t digit = (value / place) % radix;

      counter[digit]--;

      output[counter[digit]] = value;
    }

    memcpy(arr, output, n * sizeof(unsigned long long));

    place *= radix;
  }

  free(output);
  free(counter);
}

fn solution(arr: &mut [u64]) {
    let max: usize = match arr.iter().max() {
        Some(&x) => x as usize,
        None => return,
    };

    let radix = arr.len().next_power_of_two();

    let mut place = 1;
    while place <= max {
        let digit_of = |x| x as usize / place % radix;

        let mut counter = vec![0; radix];
        for &x in arr.iter() {
            counter[digit_of(x)] += 1;
        }

        for i in 1..radix {
            counter[i] += counter[i - 1];
        }

        for &x in arr.to_owned().iter().rev() {
            counter[digit_of(x)] -= 1;
            arr[counter[digit_of(x)]] = x;
        }
        place *= radix;
    }
}


Score : <var>200</var> points

Problem Statement

<var>N</var> Snukes called Snuke <var>1</var>, Snuke <var>2</var>, ..., Snuke <var>N</var> live in a town.

There are <var>K</var> kinds of snacks sold in this town, called Snack <var>1</var>, Snack <var>2</var>, ..., Snack <var>K</var>. The following <var>d_i</var> Snukes have Snack <var>i</var>: Snuke <var>A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}</var>.

Takahashi will walk around this town and make mischief on the Snukes who have no snacks. How many Snukes will fall victim to Takahashi's mischief?

Constraints

All values in input are integers.

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

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>d_1</var>
<var>A_{1, 1} \cdots A_{1, d_1}</var>
<var>\vdots</var>
<var>d_K</var>
<var>A_{K, 1} \cdots A_{K, d_K}</var>

Output

Print the answer.

Sample Input 1

3 2
2
1 3
1
3

Sample Output 1

1

Snuke <var>1</var> has Snack <var>1</var>.

Snuke <var>2</var> has no snacks.

Snuke <var>3</var> has Snack <var>1</var> and <var>2</var>.

Thus, there will be one victim: Snuke <var>2</var>.

Sample Input 2

3 3
1
3
1
3
1
3

Sample Output 2

2

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let mut itr = s.split_whitespace().map(|e| e.parse().unwrap());
    let n: usize = itr.next().unwrap();
    let k: usize = itr.next().unwrap();
    let mut set = HashSet::new();

    for _ in 0..k {
        s.clear();
        stdin().read_line(&mut s).ok();
        let _d: usize = s.trim().parse().unwrap();
        s.clear();
        stdin().read_line(&mut s).ok();
        let itr = s.split_whitespace().map(|e| e.parse::<usize>().unwrap());
        for e in itr {
            set.insert(e);
        }
    }

    let mut ans = 0;
    for i in 1..=n {
        if !set.contains(&i) {
            ans += 1;
        }
    }

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


You are given two integers $$$n$$$ and $$$k$$$.Your task is to construct such a string $$$s$$$ of length $$$n$$$ that for each $$$i$$$ from $$$1$$$ to $$$k$$$ there is at least one $$$i$$$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer $$$t$$$ independent queries.

fn solution() {
    for _ in 0..({
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();
        line.trim().parse::<u8>().unwrap()
    }) {
        let (n, k) = {
            let mut line = String::new();
            io::stdin().read_line(&mut line).unwrap();
            let s: Vec<u8> = line.trim().split(' ').map(|s| s.parse().unwrap()).collect();
            (s[0], s[1])
        };

        for i in 0..n {
            print!("{}", char::from_u32(((i % k) + 97) as u32).unwrap());
        }

        println!();
    }
}


Score : <var>300</var> points

Problem Statement

Takahashi, Aoki and Snuke love cookies. They have <var>A</var>, <var>B</var> and <var>C</var> cookies, respectively. Now, they will exchange those cookies by repeating the action below:

Each person simultaneously divides his cookies in half and gives one half to each of the other two persons.

This action will be repeated until there is a person with odd number of cookies in hand.

How many times will they repeat this action?
Note that the answer may not be finite.

Constraints

<var>1 ≤ A,B,C ≤ 10^9</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of times the action will be performed by the three people, if this number is finite.
If it is infinite, print -1 instead.

Sample Input 1

4 12 20

Sample Output 1

3

Initially, Takahashi, Aoki and Snuke have <var>4</var>, <var>12</var> and <var>20</var> cookies. Then,

After the first action, they have <var>16</var>, <var>12</var> and <var>8</var>.

After the second action, they have <var>10</var>, <var>12</var> and <var>14</var>.

After the third action, they have <var>13</var>, <var>12</var> and <var>11</var>.

Now, Takahashi and Snuke have odd number of cookies, and therefore the answer is <var>3</var>.

Sample Input 2

14 14 14

Sample Output 2

-1

Sample Input 3

454 414 444

Sample Output 3

1

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let v: Vec<i32> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let (mut a, mut b, mut c) = (v[0], v[1], v[2]);
    let mut ans = 0_i32;
    loop {
        if a % 2 == 1 || b % 2 == 1 || c % 2 == 1 {
            break;
        }
        if a == b && b == c {
            ans = -1;
            break;
        }
        let (a_tmp, b_tmp, c_tmp) = (a, b, c);
        a = (b_tmp + c_tmp) / 2;
        b = (c_tmp + a_tmp) / 2;
        c = (a_tmp + b_tmp) / 2;
        ans += 1;
    }
    println!("{}", ans);
}


You are a usual chat user on the most famous streaming platform. Of course, there are some moments when you just want to chill and spam something.More precisely, you want to spam the emote triangle of size $$$k$$$. It consists of $$$2k-1$$$ messages. The first message consists of one emote, the second one — of two emotes, ..., the $$$k$$$-th one — of $$$k$$$ emotes, the $$$k+1$$$-th one — of $$$k-1$$$ emotes, ..., and the last one — of one emote.For example, the emote triangle for $$$k=3$$$ consists of $$$5$$$ messages:  Of course, most of the channels have auto moderation. Auto moderator of the current chat will ban you right after you spam at least $$$x$$$ emotes in succession (you can assume you are the only user in the chat). Now you are interested — how many messages will you write before getting banned? Or maybe you will not get banned at all (i.e. will write all $$$2k-1$$$ messages and complete your emote triangle successfully)? Note that if you get banned as a result of writing a message, this message is also counted.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long k;
    long long x;
    scanf("%lld%lld", &k, &x);
    if (2 * x < k * k + k) {
      long long letsgo = (long long)(int)ceil((sqrt((8 * x) + 1) - 1) / 2);
      if (letsgo * (letsgo + 1) / 2 >= x && (letsgo - 1) * (letsgo) / 2 < x) {
        printf("%lld\n", letsgo);
      } else {
        printf("%lld\n", letsgo + 1);
      }
    } else {
      x -= (k + 1) * k / 2;
      long long tmpval = ((k - 1) * k / 2) - x;
      long long letsgo = (long long)(sqrt((8 * tmpval) + 1) - (double)1) / 2;
      if (2 * x < k * k - k) {
        if (letsgo * (letsgo + 1) / 2 <= tmpval &&
            (letsgo + 1) * (letsgo + 2) / 2 > tmpval) {
          printf("%lld\n", (2 * k) - 1 - letsgo);
        } else {
          printf("%lld\n", (2 * k) - letsgo);
        }
      } else {
        printf("%lld\n", (2 * k) - 1);
      }
    }
  }
  return 0;
}

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

    for _testcase in 0..testcases {
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("");

        let (k, x): (i64, i64) = match input.trim().split(" ").collect::<Vec<&str>>()[..] {
            [first, second] => (first.parse().unwrap(), second.parse().unwrap()),
            _ => panic!("AH"),
        };

        let k_sum_graph = |t: i64| -> i64 {
            if t <= k {
                (t * t + t) / 2
            } else {
                (-(t.pow(2)) + (4 * k - 1) * t - (2 * k.pow(2) - 2 * k)) / 2
            }
        };

        let mut low = 0;
        let mut mid = 0;
        let mut high = 2 * k - 1;

        while low <= high {
            mid = low + (high - low) / 2;

            let s = k_sum_graph(mid);

            if s > x {
                high = mid - 1;
            } else if s < x {
                if k_sum_graph(mid + 1) >= x {
                    mid += 1;
                    break;
                }
                low = mid + 1;
            } else {
                break;
            }
        }

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


There is a robot in a warehouse and $$$n$$$ packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point $$$(0, 0)$$$. The $$$i$$$-th package is at the point $$$(x_i, y_i)$$$. It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point $$$(0, 0)$$$ doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point $$$(x, y)$$$ to the point ($$$x + 1, y$$$) or to the point $$$(x, y + 1)$$$.As we say above, the robot wants to collect all $$$n$$$ packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string $$$s$$$ of length $$$n$$$ is lexicographically less than the string $$$t$$$ of length $$$n$$$ if there is some index $$$1 \le j \le n$$$ that for all $$$i$$$ from $$$1$$$ to $$$j-1$$$ $$$s_i = t_i$$$ and $$$s_j < t_j$$$. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.

fn solution() {
    let stdin = std::io::stdin();
    let mut lines = stdin.lock().lines();

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

    for _ in 0..t {
        let n = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
        let mut x: Vec<(usize, usize)> = lines
            .by_ref()
            .take(n)
            .map(|line| {
                let line = line.unwrap();
                let mut v = line.split(' ').map(|x| x.parse::<usize>().unwrap());
                let a = v.next().unwrap();
                let b = v.next().unwrap();
                (a, b)
            })
            .collect();

        x.sort_unstable_by_key(|k| k.0);
        x.sort_by_key(|k| k.1);

        let mut xy = Some((0, 0));
        let mut path = String::new();

        for p in x {
            if let Some(cur) = xy {
                if p.0 >= cur.0 && p.1 >= cur.1 {
                    for _ in 0..p.0 - cur.0 {
                        path.push('R');
                    }
                    for _ in 0..p.1 - cur.1 {
                        path.push('U');
                    }

                    xy = Some(p);
                } else {
                    xy = None;
                }
            }
        }

        if xy.is_some() {
            println!("YES\n{}", path);
        } else {
            println!("NO");
        }
    }
}


Score : <var>400</var> points

Problem Statement

<var>N</var> people are arranged in a row from left to right.

You are given a string <var>S</var> of length <var>N</var> consisting of 0 and 1, and a positive integer <var>K</var>.

The <var>i</var>-th person from the left is standing on feet if the <var>i</var>-th character of <var>S</var> is 0, and standing on hands if that character is 1.

You will give the following direction at most <var>K</var> times (possibly zero):

Direction: Choose integers <var>l</var> and <var>r</var> satisfying <var>1 \leq l \leq r \leq N</var>, and flip the <var>l</var>-th, <var>(l+1)</var>-th, <var>...</var>, and <var>r</var>-th persons. That is, for each <var>i = l, l+1, ..., r</var>, the <var>i</var>-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most <var>K</var> directions.

Constraints

<var>N</var> is an integer satisfying <var>1 \leq N \leq 10^5</var>.

<var>K</var> is an integer satisfying <var>1 \leq K \leq 10^5</var>.

The length of the string <var>S</var> is <var>N</var>.

Each character of the string <var>S</var> is 0 or 1.

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible number of consecutive people standing on hands after at most <var>K</var> directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with <var>l = 1, r = 3</var>, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.

fn solution() {
    use std::io::Read;
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let _n: usize = s.next().unwrap().parse().unwrap();
    let k: usize = s.next().unwrap().parse().unwrap();
    let s: Vec<char> = s.next().unwrap().chars().collect();
    let mut l = 0;
    let mut r = 0;
    let mut cnt = 0;
    let mut ans = 0;
    while l < s.len() {
        while r < s.len() {
            if s[r] == '0' {
                if cnt >= k {
                    break;
                }
                while r < s.len() && s[r] == '0' {
                    r += 1;
                }
                cnt += 1;
            } else {
                r += 1;
            }
        }
        if r - l > ans {
            ans = r - l;
        }
        if s[l] == '1' {
            while l < s.len() && s[l] == '1' {
                l += 1;
            }
        }
        if l < s.len() {
            cnt = cnt.saturating_sub(1);
            while l < s.len() && s[l] == '0' {
                l += 1;
            }
        }
    }
    println!("{}", ans);
}


Score : <var>600</var> points

Problem Statement

Snuke has an integer sequence <var>A</var> of length <var>N</var>.

He will make three cuts in <var>A</var> and divide it into four (non-empty) contiguous subsequences <var>B, C, D</var> and <var>E</var>.
The positions of the cuts can be freely chosen.

Let <var>P,Q,R,S</var> be the sums of the elements in <var>B,C,D,E</var>, respectively.
Snuke is happier when the absolute difference of the maximum and the minimum among <var>P,Q,R,S</var> is smaller.
Find the minimum possible absolute difference of the maximum and the minimum among <var>P,Q,R,S</var>.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Find the minimum possible absolute difference of the maximum and the minimum among <var>P,Q,R,S</var>.

Sample Input 1

5
3 2 4 1 2

Sample Output 1

2

If we divide <var>A</var> as <var>B,C,D,E=(3),(2),(4),(1,2)</var>, then <var>P=3,Q=2,R=4,S=1+2=3</var>.
Here, the maximum and the minimum among <var>P,Q,R,S</var> are <var>4</var> and <var>2</var>, with the absolute difference of <var>2</var>.
We cannot make the absolute difference of the maximum and the minimum less than <var>2</var>, so the answer is <var>2</var>.

Sample Input 2

10
10 71 84 33 6 47 23 25 52 64

Sample Output 2

36

Sample Input 3

7
1 2 3 1000000000 4 5 6

Sample Output 3

999999994

int solution(void) {
  long n;
  long a[200000];
  long i;
  long j;
  long k;
  long as[200000];
  long suml;
  long sumr;
  long p;
  long q;
  long r;
  long s;
  long ans;
  long temp;
  long max;
  long min;
  long maxl;
  long minl;
  long maxr;
  long minr;

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

  for (i = 0; i < n; i++) {
    if (i == 0) {
      as[0] = a[0];
    } else {
      as[i] = as[i - 1] + a[i];
    }
  }

  ans = as[n - 1];

  i = 0;
  k = 2;
  for (j = 1; j <= n - 3; j++) {
    suml = as[j];
    for (; i <= j - 1; i++) {
      if (as[i] >= (suml + 1) / 2) {
        break;
      }
    }
    if (i != 0 &&
        labs(as[i - 1] - (suml / 2)) <= labs(as[i] - ((suml + 1) / 2))) {
      i--;
    }

    sumr = as[n - 1] - as[j];
    if (j >= k) {
      k = j + 1;
    }
    for (; k <= n - 2; k++) {
      if (as[k] - as[j] >= (sumr + 1) / 2) {
        break;
      }
    }
    if (k != j + 1 && labs(as[k - 1] - as[j] - (sumr / 2)) <=
                          labs(as[k] - as[j] - ((sumr + 1) / 2))) {
      k--;
    }

    p = as[i];
    q = as[j] - as[i];
    r = as[k] - as[j];
    s = as[n - 1] - as[k];
    maxl = (p > q) ? p : q;
    minl = (p < q) ? p : q;
    maxr = (r > s) ? r : s;
    minr = (r < s) ? r : s;
    max = (maxl > maxr) ? maxl : maxr;
    min = (minl < minr) ? minl : minr;
    temp = max - min;
    if (ans >= temp) {
      ans = temp;
    }
  }

  printf("%ld", ans);

  return 0;
}

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

    let mut s = vec![0i64; n + 1];
    for i in 0..n {
        s[i + 1] = s[i] + a[i];
    }

    let mut ans = 1i64 << 60;

    let mut p = 1;
    let mut r = 3;
    for q in 2..n - 1 {
        let mut P = s[p];
        let mut Q = s[q] - s[p];
        let mut R = s[r] - s[q];
        let mut S = s[n] - s[r];
        while p + 1 < q && (s[q] - s[p + 1] - s[p + 1]).abs() <= (Q - P).abs() {
            p += 1;
            P = s[p];
            Q = s[q] - s[p];
        }
        while r + 1 < n && (s[n] - s[r + 1] - s[r + 1] + s[q]).abs() <= (S - R).abs() {
            r += 1;
            R = s[r] - s[q];
            S = s[n] - s[r];
        }
        ans = min(ans, max(max(max(P, Q), R), S) - min(min(min(P, Q), R), S));
    }
    println!("{}", ans);
}