You have $$$n$$$ stacks of blocks. The $$$i$$$-th stack contains $$$h_i$$$ blocks and it's height is the number of blocks in it. In one move you can take a block from the $$$i$$$-th stack (if there is at least one block) and put it to the $$$i + 1$$$-th stack. Can you make the sequence of heights strictly increasing?Note that the number of stacks always remains $$$n$$$: stacks don't disappear when they have $$$0$$$ blocks.

int solution() {
  int t = 0;
  int n = 0;
  int sw = 0;
  int h[100] = {0};
  long long int sum = 0;
  scanf("%d", &t);
  while (t-- > 0) {
    sum = 0;
    sw = 1;
    scanf("%d", &n);

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

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

      sum += h[i];
      if (sum < ((i * (i + 1)) / 2)) {
        sw = 0;
        break;
      }
    }
    if (sw == 0) {
      printf("NO\n");
    }
    if (sw == 1) {
      printf("YES\n");
    }
  }
  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 n: usize = sc.next();
        let mut arr: Vec<i64> = (0..n).map(|_| sc.next()).collect();
        let mut valid = true;
        for i in 0..n - 1 {
            let x = min(arr[i], i as i64);
            if x < i as i64 {
                valid = false;
                break;
            }
            arr[i + 1] += arr[i] - x;
        }
        let ans = if valid && arr[n - 1] >= n as i64 - 1 {
            "YES"
        } else {
            "NO"
        };
        writeln!(out, "{}", ans).unwrap();
    }
}


Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.  The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?

int solution() {
  int no;
  int moves = 0;
  char str[1000];
  char nstr[1000];
  scanf("%d", &no);
  scanf("%s", str);
  scanf("%s", nstr);
  for (int i = 0; i < no; i++) {
    int no1 = str[i] - '0';
    int no2 = nstr[i] - '0';
    if (no1 - no2 > 0) {
      if (no1 - no2 > 10 - no1 + no2) {
        moves = moves + 10 - no1 + no2;
      } else {
        moves = moves + no1 - no2;
      }
    } else {
      if (no2 - no1 > 10 - no2 + no1) {
        moves = moves + 10 - no2 + no1;
      } else {
        moves = moves + no2 - no1;
      }
    }
  }
  printf("%d", moves);
}

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

    let mut original_state = String::new();
    std::io::stdin().read_line(&mut original_state).unwrap();
    let mut final_state = String::new();
    std::io::stdin().read_line(&mut final_state).unwrap();

    let final_state = final_state.trim().as_bytes();
    let original_state = original_state.trim().as_bytes();
    let mut number_move: usize = 0;
    for i in 0..number_disk {
        let distance: isize = (original_state[i] as isize) - (final_state[i] as isize);
        let mut distance = distance.unsigned_abs();
        if distance > 5 {
            distance = 10 - distance;
        }

        number_move += distance;
    }
    println!("{}", number_move);
}


A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string $$$s$$$ determine if it is square.

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

  char *str = malloc(sizeof(char) * 101);
  for (int i = 0; i < n; i++) {
    scanf("%s", str);
    int length = strlen(str);

    if (length % 2 == 1) {
      printf("NO\n");
      continue;
    }
    char *tmp = malloc(sizeof(char) * (length / 2) + 1);
    char *tmp2 = malloc(sizeof(char) * (length / 2) + 1);

    for (int j = 0; j < (length / 2) + 1; j++) {
      tmp[j] = str[j];
      tmp2[j] = str[j + length / 2];

      if (j == (length / 2)) {
        tmp[j] = '\0';
        tmp2[j + length / 2] = '\0';
      }
    }

    if (!strcmp(tmp, tmp2))
      printf("YES\n");
    else
      printf("NO\n");

    free(tmp);
    free(tmp2);
  }

  free(str);
}

fn solution() {
    std::io::stdin().lines().skip(1).flatten().for_each(|s| {
        match s.split_at(s.len().wrapping_div(2)) {
            (a, b) if a == b => println!("YES"),
            _ => println!("NO"),
        }
    });
}


When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types:   transform lowercase letters to uppercase and vice versa;  change letter «O» (uppercase latin letter) to digit «0» and vice versa;  change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.

fn solution() {
    let mut s: String = String::new();
    stdin().read_line(&mut s);
    s = s.to_lowercase();
    s = s.replace("1", "!");
    s = s.replace("0", "o");
    s = s.replace("i", "!");
    s = s.replace("l", "!");
    let mut n: String = String::new();
    stdin().read_line(&mut n).unwrap();
    let n: i32 = n.trim().parse::<i32>().unwrap();
    let mut st: String = String::new();
    let mut p: i32 = 0;
    for _c in 0..n {
        stdin().read_line(&mut st);
        st = st.to_lowercase();
        st = st.replace("1", "!");
        st = st.replace("0", "o");
        st = st.replace("i", "!");
        st = st.replace("l", "!");
        if s == st {
            p = 1
        }
        st.clear();
    }
    if p == 0 {
        println!("Yes")
    } else {
        println!("No")
    }
}


Score : <var>200</var> points

Problem Statement

Given are integers <var>a,b,c</var> and <var>d</var>.
If <var>x</var> and <var>y</var> are integers and <var>a \leq x \leq b</var> and <var>c\leq y \leq d</var> hold, what is the maximum possible value of <var>x \times y</var>?

Constraints

<var>-10^9 \leq a \leq b \leq 10^9</var>

<var>-10^9 \leq c \leq d \leq 10^9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>a</var> <var>b</var> <var>c</var> <var>d</var>

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If <var>x = 1</var> and <var>y = 1</var> then <var>x \times y = 1</var>.
If <var>x = 2</var> and <var>y = 1</var> then <var>x \times y = 2</var>.
Therefore, the answer is <var>2</var>.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let a: i64 = s.next().unwrap().parse().unwrap();
    let b: i64 = s.next().unwrap().parse().unwrap();
    let c: i64 = s.next().unwrap().parse().unwrap();
    let d: i64 = s.next().unwrap().parse().unwrap();
    let v = [a * d, a * c, b * d, b * c];
    println!("{}", v.iter().max().unwrap());
}


Score : <var>200</var> points

Problem Statement

We have a long seat of width <var>X</var> centimeters.
There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length <var>Y</var> centimeters.

We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least <var>Z</var> centimeters between two people, and between the end of the seat and a person.

At most how many people can sit on the seat?

Constraints

All input values are integers.

<var>1 \leq X, Y, Z \leq 10^5</var>

<var>Y+2Z \leq X</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the answer.

Sample Input 1

13 3 1

Sample Output 1

3

There is just enough room for three, as shown below:

Figure

Sample Input 2

12 3 1

Sample Output 2

2

Sample Input 3

100000 1 1

Sample Output 3

49999

Sample Input 4

64146 123 456

Sample Output 4

110

Sample Input 5

64145 123 456

Sample Output 5

109

int solution(void) {

  int max;
  int x;
  int y;
  int ans = 0;

  scanf("%d %d %d", &max, &x, &y);

  while (-1) {
    if (max == (ans * x) + ((ans + 1) * y)) {
      break;
    }
    if (max < (ans * x) + ((ans + 1) * y)) {
      ans--;
      break;
    }
    ans++;
  }

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

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let vec: Vec<&str> = s.trim().split(' ').collect();
    let x: i32 = vec[0].parse().unwrap();
    let y: i32 = vec[1].parse().unwrap();
    let z: i32 = vec[2].parse().unwrap();
    if x % (y + z) == 0 || x % (y + z) < z {
        println!("{}", x / (y + z) - 1);
    } else {
        println!("{}", x / (y + z));
    }
}


問題 3

　入力ファイルの１行目に正整数 n （n≧3）が書いてあり，
つづく n 行に異なる正整数 a1, ..., an が
１つずつ書いてある．
a1, ..., an から異なる２個を選んで作られる
順列を（数として見て）小さい順に並べたとき，
３番目に来るものを出力せよ．

　ただし，
例えば，a1 = 1，a4 = 11 のような場合も，
a1a4 と a4a1 は異なる順列とみなす．
また，
1≦ai≦10000 (i=1, ..., n) かつ 3≦n≦104 である．

出力ファイルにおいては，
出力の最後にも改行コードを入れること．

入出力例

入力例１

3
2
7
5

出力例１

52

入力例２

4
17
888
1
71

出力例２

171

問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。

int solution(void) {
  int n;
  int i;
  int j;
  int a;
  int exist[10001] = {0};
  int smalla[10];
  int smalla_num;
  int result[3] = {1000000000, 1000000000, 1000000000};
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d", &a);
    exist[a] = 1;
  }
  smalla_num = 0;
  for (i = 0; i <= 10000 && smalla_num < 10; i++) {
    if (exist[i]) {
      smalla[smalla_num++] = i;
    }
  }
  for (i = 0; i < smalla_num; i++) {
    for (j = 0; j < smalla_num; j++) {
      char buffer[100];
      int now;
      if (i == j) {
        continue;
      }
      sprintf(buffer, "%d%d", smalla[i], smalla[j]);
      sscanf(buffer, "%d", &now);
      if (now <= result[2]) {
        result[2] = now;
      }
      if (now <= result[1]) {
        result[2] = result[1];
        result[1] = now;
      }
      if (now <= result[0]) {
        result[1] = result[0];
        result[0] = now;
      }
    }
  }
  printf("%d\n", result[2]);
  return 0;
}

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

    let n = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
    let mut array = lines
        .take(n)
        .map(|s| s.unwrap().parse::<u32>().unwrap())
        .collect::<Vec<_>>();
    array.sort();

    let mut vec = Vec::with_capacity(12);

    for a in array.iter().take(4) {
        for b in array.iter().take(4) {
            if a == b {
                continue;
            }

            let log = (*b as f64).log10() as u32;
            vec.push(a * 10u32.pow(log + 1) + b);
        }
    }

    vec.sort();

    println!("{}", vec[2]);
}


Score : <var>200</var> points

Problem Statement

Raccoon is fighting with a monster.

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

Raccoon can use <var>N</var> kinds of special moves. Using the <var>i</var>-th move decreases the monster's health by <var>A_i</var>.
There is no other way to decrease the monster's health.

Raccoon wins when the monster's health becomes <var>0</var> or below.

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Constraints

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

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If Raccoon can win without using the same move twice or more, print Yes; otherwise, print No.

Sample Input 1

10 3
4 5 6

Sample Output 1

Yes

The monster's health will become <var>0</var> or below after, for example, using the second and third moves.

Sample Input 2

20 3
4 5 6

Sample Output 2

No

Sample Input 3

210 5
31 41 59 26 53

Sample Output 3

Yes

Sample Input 4

211 5
31 41 59 26 53

Sample Output 4

No

int solution() {
  int h = 0;
  int n = 0;
  int sum = 0;

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

  if (sum >= h) {
    printf("Yes");
  } else {
    printf("No");
  }

  return 0;
}

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

    io::stdin().read_to_string(&mut buffer).unwrap();

    let mut lines = buffer.lines();
    let a = lines.next().unwrap();
    let b = lines.next().unwrap();

    let a2 = a
        .split_whitespace()
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<i32>>();
    let b2 = b
        .split_whitespace()
        .map(|s| s.parse::<i32>().unwrap())
        .collect::<Vec<i32>>();

    let hp = a2[0];
    let sum = b2.into_iter().sum::<i32>();
    if hp <= sum {
        println!("Yes");
    } else {
        println!("No");
    }
}


Tanya wants to go on a journey across the cities of Berland. There are $$$n$$$ cities situated along the main railroad line of Berland, and these cities are numbered from $$$1$$$ to $$$n$$$. Tanya plans her journey as follows. First of all, she will choose some city $$$c_1$$$ to start her journey. She will visit it, and after that go to some other city $$$c_2 > c_1$$$, then to some other city $$$c_3 > c_2$$$, and so on, until she chooses to end her journey in some city $$$c_k > c_{k - 1}$$$. So, the sequence of visited cities $$$[c_1, c_2, \dots, c_k]$$$ should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city $$$i$$$ has a beauty value $$$b_i$$$ associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities $$$c_i$$$ and $$$c_{i + 1}$$$, the condition $$$c_{i + 1} - c_i = b_{c_{i + 1}} - b_{c_i}$$$ must hold.For example, if $$$n = 8$$$ and $$$b = [3, 4, 4, 6, 6, 7, 8, 9]$$$, there are several three possible ways to plan a journey:  $$$c = [1, 2, 4]$$$;  $$$c = [3, 5, 6, 8]$$$;  $$$c = [7]$$$ (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?

int solution() {
  int n;
  scanf("%d", &n);
  long long int max = 0;
  int b[n];
  int cut[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", b + i);
    cut[i] = b[i] - i - 1;
  }
  if (n == 1) {
    printf("%d", b[0]);
    return 0;
  }
  int min = cut[0];
  int amax = cut[0];
  for (int i = 0; i < n; i++) {
    if (cut[i] < min) {
      min = cut[i];
    }
    if (cut[i] > amax) {
      amax = cut[i];
    }
  }
  long long int size = amax - min + 1;
  long long int index[size];
  memset(index, 0, size * sizeof *index);
  for (int i = 0; i < n; i++) {
    index[cut[i] - min] += b[i];
  }

  for (int i = 0; i < size; i++) {
    if (index[i] > max) {
      max = index[i];
    }
  }
  printf("%lld", max);
  return 0;
}

fn solution() {
    use std::io::{self, BufRead};

    let mut cities_input = String::new();
    stdin()
        .read_line(&mut cities_input)
        .expect("Failed to parse");
    let reader = io::stdin();
    let mut sums = HashMap::<i64, i64>::new();
    let beauties_cities: Vec<i64> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|s| s.parse().unwrap())
        .collect();
    for (city, beauty) in beauties_cities.iter().enumerate() {
        let key = beauty - city as i64;
        sums.insert(key, *sums.get(&key).get_or_insert(&0) + *beauty);
    }

    println!("{}", sums.values().max().get_or_insert(&0));
}


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.Initially, you have an integer $$$x = 0$$$. During one move, you can do one of the following two operations:  Choose exactly one $$$i$$$ from $$$1$$$ to $$$n$$$ and increase $$$a_i$$$ by $$$x$$$ ($$$a_i := a_i + x$$$), then increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$).  Just increase $$$x$$$ by $$$1$$$ ($$$x := x + 1$$$). The first operation can be applied no more than once to each $$$i$$$ from $$$1$$$ to $$$n$$$.Your task is to find the minimum number of moves required to obtain such an array that each its element is divisible by $$$k$$$ (the value $$$k$$$ is given).You have to answer $$$t$$$ independent test cases.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let xs: Vec<u64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let (n, k) = (xs[0] as usize, xs[1]);
        let mut xs: Vec<u64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        for i in 0..n {
            xs[i] = (k - (xs[i] % k)) % k;
        }
        xs.sort();
        let mut m: u64 = xs[0];
        let mut count: u64 = if xs[0] == 0 { 0 } else { 1 };
        let mut max_m: u64 = 0;
        let mut max_count: u64 = 0;
        for i in 1..n {
            if xs[i] == 0 {
                continue;
            }
            if xs[i] != m {
                if max_count <= count {
                    max_count = count;
                    max_m = m;
                }
                count = 1;
                m = xs[i]
            } else {
                count += 1;
            }
        }
        if max_count <= count {
            max_count = count;
            max_m = m;
        }
        let ans = if max_count == 0 {
            0
        } else {
            1 + (max_count - 1) * k + max_m
        };
        println!("{}", ans);
    }
}


Score : <var>200</var> points

Problem Statement

Find the number of palindromic numbers among the integers between <var>A</var> and <var>B</var> (inclusive).
Here, a palindromic number is a positive integer whose string representation in base <var>10</var> (without leading zeros) reads the same forward and backward.

Constraints

<var>10000 \leq A \leq B \leq 99999</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of palindromic numbers among the integers between <var>A</var> and <var>B</var> (inclusive).

Sample Input 1

11009 11332

Sample Output 1

4

There are four integers that satisfy the conditions: <var>11011</var>, <var>11111</var>, <var>11211</var> and <var>11311</var>.

Sample Input 2

31415 92653

Sample Output 2

612

int solution() {

  int A = 0;
  int B = 0;
  int number = 0;
  int answer = 0;
  int D[5];

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

  for (int i = A; i <= B; ++i) {
    number = i;
    for (int j = 4; j >= 0; --j) {
      D[j] = number % 10;
      number /= 10;
    }
    if (D[0] == D[4] && D[1] == D[3]) {
      ++answer;
    }
  }

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

  return 0;
}

fn solution() {
    let mut buf: String = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let a = iter.next().unwrap().parse::<i64>().unwrap();
    let b = iter.next().unwrap().parse::<i64>().unwrap();
    let mut ans = 0;
    for i in a..b + 1 {
        let mut i_as_str = format!("{}", i);
        unsafe {
            i_as_str.as_mut_vec().reverse();
            if format!("{}", i) == i_as_str {
                ans += 1;
            }
        }
    }
    println!("{}", ans);
}


Score : <var>300</var> points

Problem Statement

There are <var>N+1</var> towns. The <var>i</var>-th town is being attacked by <var>A_i</var> monsters.

We have <var>N</var> heroes. The <var>i</var>-th hero can defeat monsters attacking the <var>i</var>-th or <var>(i+1)</var>-th town, for a total of at most <var>B_i</var> monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_{N+1}</var>
<var>B_1</var> <var>B_2</var> <var>...</var> <var>B_N</var>

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3

fn solution() {
    let min = |a, b| if a < b { a } else { b };

    let mut n = String::new();
    stdin().read_line(&mut n).unwrap();
    let n: usize = n.trim().parse().unwrap();

    let mut ais = String::new();
    stdin().read_line(&mut ais).unwrap();
    let mut ais: Vec<usize> = ais.split_whitespace().flat_map(str::parse).collect();
    ais.reverse();

    let mut bis = String::new();
    stdin().read_line(&mut bis).unwrap();
    let mut bis: Vec<usize> = bis.split_whitespace().flat_map(str::parse).collect();
    bis.reverse();
    bis.push(0);

    let mut result = 0;
    for i in 0..n {
        for j in 0..2 {
            let d = min(ais[i + j], bis[i]);
            ais[i + j] -= d;
            bis[i] -= d;
            result += d;
        }
    }
    println!("{}", result);
}


Marcin is a coach in his university. There are $$$n$$$ students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.Let's focus on the students. They are indexed with integers from $$$1$$$ to $$$n$$$. Each of them can be described with two integers $$$a_i$$$ and $$$b_i$$$; $$$b_i$$$ is equal to the skill level of the $$$i$$$-th student (the higher, the better). Also, there are $$$60$$$ known algorithms, which are numbered with integers from $$$0$$$ to $$$59$$$. If the $$$i$$$-th student knows the $$$j$$$-th algorithm, then the $$$j$$$-th bit ($$$2^j$$$) is set in the binary representation of $$$a_i$$$. Otherwise, this bit is not set.Student $$$x$$$ thinks that he is better than student $$$y$$$ if and only if $$$x$$$ knows some algorithm which $$$y$$$ doesn't know. Note that two students can think that they are better than each other. A group of students can work together calmly if no student in this group thinks that he is better than everyone else in this group.Marcin wants to send a group of at least two students which will work together calmly and will have the maximum possible sum of the skill levels. What is this sum?

int solution() {
  long int n;
  long int i;
  long int j;
  scanf("%ld", &n);

  long long int a[n];
  long long int b[n];
  long long int c[n];
  long long int ch[n];
  long long int skill = 0;
  long long int flag = 0;

  for (i = 0; i < n; i++) {
    c[i] = 0;
    ch[i] = -1;
    scanf("%lld", &a[i]);
  }
  for (i = 0; i < n; i++) {
    scanf("%lld", &b[i]);
  }
  for (i = 0; i < n; i++) {
    if (c[i] == 0) {
      for (j = i + 1; j < n; j++) {
        if (a[i] == a[j]) {
          c[i] = 1;
          c[j] = 1;
          ch[i] = a[i];
        }
      }
    }
  }
  for (j = 0; j < n; j++) {
    if (c[j] == 1) {
      skill = skill + b[j];
    }
  }
  if (skill != 0) {
    for (j = 0; j < n; j++) {
      if (c[j] == 0) {
        for (i = 0; i < n; i++) {
          if (ch[i] != -1 && ((ch[i] & a[j]) == a[j])) {
            flag = 1;
            break;
          }
        }
        if (flag == 1) {
          skill = skill + b[j];
        }
        flag = 0;
      }
    }
  }
  printf("%lld\n", skill);

  return 0;
}

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

    let n: i32 = iter.next().unwrap().parse().unwrap();
    let mut A = vec![];
    let mut B = vec![];
    let mut counter: BTreeMap<i64, Vec<i32>> = BTreeMap::new();
    for i in 0..n {
        let a: i64 = iter.next().unwrap().parse().unwrap();
        A.push(a);
        let indices = counter.entry(a).or_insert(vec![]);
        indices.push(i);
    }

    for _ in 0..n {
        let b: i64 = iter.next().unwrap().parse().unwrap();
        B.push(b);
    }

    let mut total_skill = 0;
    let mut skills: Vec<i64> = vec![];
    for a in counter.keys().rev() {
        let indices = counter.get(a).unwrap();
        let mut ok = indices.len() > 1;
        if !ok {
            for skill in &skills {
                if (a & !skill) == 0 {
                    ok = true;
                    break;
                }
            }
        }

        if ok {
            skills.push(*a);
            for index in indices {
                total_skill += B[*index as usize];
            }
        }
    }
    println!("{}", total_skill);
}


Score : <var>500</var> points

Problem Statement

We have a chocolate bar partitioned into <var>H</var> horizontal rows and <var>W</var> vertical columns of squares.

The square <var>(i, j)</var> at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left is dark if <var>S_{i,j}</var> is 0, and white if <var>S_{i,j}</var> is 1.

We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.

How many times do we need to cut the bar so that every block after the cuts has <var>K</var> or less white squares?

Constraints

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

<var>1 \leq W \leq 1000</var>

<var>1 \leq K \leq H \times W</var>

<var>S_{i,j}</var> is 0 or 1.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of minimum times the bar needs to be cut so that every block after the cuts has <var>K</var> or less white squares.

Sample Input 1

3 5 4
11100
10001
00111

Sample Output 1

2

For example, cutting between the <var>1</var>-st and <var>2</var>-nd rows and between the <var>3</var>-rd and <var>4</var>-th columns - as shown in the figure to the left - works.

Note that we cannot cut the bar in the ways shown in the two figures to the right.

Sample Input 2

3 5 8
11100
10001
00111

Sample Output 2

0

No cut is needed.

Sample Input 3

4 10 4
1110010010
1000101110
0011101001
1101000111

Sample Output 3

3

int solution() {
  int H;
  int W;
  int K;
  char S[10][1000];
  char s[1002];
  int pattern;

  scanf("%d %d %d", &H, &W, &K);

  for (int i = 0; i < H; i++) {
    scanf("%s", s);
    for (int j = 0; j < W; j++) {
      S[i][j] = s[j];
    }
  }

  pattern = 1;
  for (int i = 0; i < H - 1; i++) {
    pattern *= 2;
  }

  int cut = 0;
  int min = H + W - 2;
  for (int i = 0; i < pattern; i++) {
    int bit = 1;
    int count = 0;
    int cutH[9];
    int regionH[10];
    int index = 0;

    for (int j = 0; j < H - 1; j++) {
      if (i & bit) {
        cutH[index] = j;
        index += 1;
      }
      bit *= 2;
    }
    count += index;

    for (int j = 0; j < index + 1; j++) {
      regionH[j] = 0;
    }

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

      int indexH = 0;
      for (int k = 0; k < H; k++) {
        regionH[indexH] += (S[k][j] == '1');
        if (indexH < index && cutH[indexH] == k) {
          indexH += 1;
        }
      }
      int flagH = 0;
      for (int k = 0; k < index + 1; k++) {
        if (regionH[k] > K) {
          flagH++;
        }
      }
      if (flagH) {

        for (int k = 0; k < index + 1; k++) {
          regionH[k] = 0;
        }
        indexH = 0;
        for (int k = 0; k < H; k++) {
          regionH[indexH] += (S[k][j] == '1');
          if (indexH < index && cutH[indexH] == k) {
            indexH += 1;
          }
        }
        count++;

        flagH = 0;
        for (int k = 0; k < index + 1; k++) {
          if (regionH[k] > K) {
            flagH++;
          }
        }
        if (flagH) {
          count = H + W - 2;
        }
      }
    }

    if (count < min) {
      min = count;
    }
  }
  printf("%d\n", min);
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let h: usize = itr.next().unwrap().parse().unwrap();
    let w: usize = itr.next().unwrap().parse().unwrap();
    let k: usize = itr.next().unwrap().parse().unwrap();
    let d: Vec<Vec<char>> = (0..h)
        .map(|_| itr.next().unwrap().chars().collect())
        .collect();
    let mut s: Vec<Vec<usize>> = vec![vec![0; w + 5]; h + 5];
    for i in 0..h {
        for j in 0..w {
            s[i + 1][j + 1] = (d[i][j] == '1') as usize;
        }
    }
    for i in 1..h + 1 {
        for j in 1..w + 1 {
            s[i][j + 1] += s[i][j];
        }
    }
    for i in 1..h + 1 {
        for j in 1..w + 1 {
            s[i + 1][j] += s[i][j];
        }
    }

    let mut ans = 1 << 30;

    for bit in 0..(1 << (h - 1)) {
        let mut count = 0;
        let mut x = 0;
        let mut good = false;
        for i in 0..w {
            let mut ok = true;
            let mut y = 0;
            for j in 0..h {
                if bit >> j & 1 == 1 || j == h - 1 {
                    if s[j + 1][i + 1] + s[y][x] - s[j + 1][x] - s[y][i + 1] > k {
                        ok = false;
                    }
                    y = j + 1;
                }
            }
            if !ok {
                count += 1;
                x = i;
            } else {
                good = true;
            }
        }
        if good {
            ans = std::cmp::min(ans, count + (bit as u32).count_ones());
        }
    }

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


You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.

fn solution() {
    let n: usize = {
        let mut read_buf = String::new();
        io::stdin().read_line(&mut read_buf).unwrap();
        read_buf.trim().parse().unwrap()
    };
    let numbers = {
        let mut read_buf = String::new();
        io::stdin().read_line(&mut read_buf).unwrap();
        read_buf
    };

    let mut cnt = [0, 0, 0];
    for c in numbers.trim().chars() {
        if c == '0' {
            cnt[0] += 1;
        } else if c == '1' {
            cnt[1] += 1;
        } else if c == '2' {
            cnt[2] += 1;
        }
    }
    let base_number = n / 3;
    let mut a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
    if cnt[0] <= base_number && cnt[1] <= base_number && cnt[2] >= base_number {
        a[2][0] = base_number - cnt[0];
        a[2][1] = base_number - cnt[1];
        for c in numbers.chars() {
            if c == '2' {
                if a[2][0] > 0 {
                    print!("0");
                    a[2][0] -= 1;
                } else if a[2][1] > 0 {
                    print!("1");
                    a[2][1] -= 1;
                } else {
                    print!("2");
                }
            } else {
                print!("{}", c);
            }
        }
    } else if cnt[0] <= base_number && cnt[1] >= base_number && cnt[2] <= base_number {
        a[1][0] = base_number - cnt[0];
        a[1][1] = base_number;
        a[1][2] = base_number - cnt[2];
        for c in numbers.chars() {
            if c == '1' {
                if a[1][0] > 0 {
                    print!("0");
                    a[1][0] -= 1;
                } else if a[1][1] > 0 {
                    print!("1");
                    a[1][1] -= 1;
                } else if a[1][2] > 0 {
                    print!("2");
                    a[1][2] -= 1;
                }
            } else {
                print!("{}", c);
            }
        }
    } else if cnt[0] >= base_number && cnt[1] <= base_number && cnt[2] <= base_number {
        a[0][0] = base_number;
        a[0][1] = base_number - cnt[1];
        a[0][2] = base_number - cnt[2];
        for c in numbers.chars() {
            if c == '0' {
                if a[0][0] > 0 {
                    print!("0");
                    a[0][0] -= 1;
                } else if a[0][1] > 0 {
                    print!("1");
                    a[0][1] -= 1;
                } else if a[0][2] > 0 {
                    print!("2");
                    a[0][2] -= 1;
                }
            } else {
                print!("{}", c);
            }
        }
    } else if cnt[0] <= base_number && cnt[1] >= base_number && cnt[2] >= base_number {
        a[1][0] = cnt[1] - base_number;
        a[2][0] = cnt[2] - base_number;
        for c in numbers.chars() {
            if c == '1' {
                if a[1][0] > 0 {
                    print!("0");
                    a[1][0] -= 1;
                } else {
                    print!("1");
                }
            } else if c == '2' {
                if a[2][0] > 0 {
                    print!("0");
                    a[2][0] -= 1;
                } else {
                    print!("2");
                }
            } else {
                print!("{}", c);
            }
        }
    } else if cnt[0] >= base_number && cnt[1] <= base_number && cnt[2] >= base_number {
        a[0][0] = base_number;
        a[0][1] = cnt[0] - base_number;
        a[2][1] = cnt[2] - base_number;
        for c in numbers.chars() {
            if c == '0' {
                if a[0][0] > 0 {
                    print!("0");
                    a[0][0] -= 1;
                } else if a[0][1] > 0 {
                    print!("1");
                    a[0][1] -= 1;
                }
            } else if c == '2' {
                if a[2][1] > 0 {
                    print!("1");
                    a[2][1] -= 1;
                } else {
                    print!("2");
                }
            } else {
                print!("{}", c);
            }
        }
    } else if cnt[0] >= base_number && cnt[1] >= base_number && cnt[2] <= base_number {
        a[0][0] = base_number;
        a[0][2] = cnt[0] - base_number;
        a[1][1] = base_number;
        a[1][2] = cnt[1] - base_number;
        for c in numbers.chars() {
            if c == '0' {
                if a[0][0] > 0 {
                    print!("0");
                    a[0][0] -= 1;
                } else if a[0][2] > 0 {
                    print!("2");
                    a[0][2] -= 1;
                }
            } else if c == '1' {
                if a[1][1] > 0 {
                    print!("1");
                    a[1][1] -= 1;
                } else if a[1][2] > 0 {
                    print!("2");
                    a[1][2] -= 1;
                }
            } else {
                print!("{}", c);
            }
        }
    }
}


You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word "hello". Determine how long it will take to print the word $$$s$$$.

fn solution() {
    let mut keys = String::new();
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("");
    let n: i32 = input.trim().parse().expect("");
    for _ in 0..n {
        keys.clear();
        input.clear();
        io::stdin().read_line(&mut keys).expect("");
        io::stdin().read_line(&mut input).expect("");
        input = input.trim().to_string();
        keys = keys.trim().to_string();
        let mut sum = 0;
        let mut prev = input.as_bytes()[0];
        for &c in input.as_bytes() {
            let x = keys.find(c as char).unwrap() as i64;
            let y = keys.find(prev as char).unwrap() as i64;
            sum += (x - y).abs();
            prev = c;
        }
        println!("{}", sum);
    }
}


You are playing a computer game. To pass the current level, you have to kill a big horde of monsters. In this horde, there are $$$n$$$ monsters standing in the row, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th monster has $$$a_i$$$ health and a special "Death's Blessing" spell of strength $$$b_i$$$ attached to it.You are going to kill all of them one by one. It takes exactly $$$h$$$ seconds to kill a monster with health $$$h$$$.When the $$$i$$$-th monster dies, it casts its spell that increases the health of its neighbors by $$$b_i$$$ (the neighbors of the $$$j$$$-th monster in the row are the monsters on places $$$j - 1$$$ and $$$j + 1$$$. The first and the last monsters have only one neighbor each).After each monster is killed, the row shrinks, so its former neighbors become adjacent to each other (so if one of them dies, the other one is affected by its spell). For example, imagine a situation with $$$4$$$ monsters with health $$$a = [2, 6, 7, 3]$$$ and spells $$$b = [3, 6, 0, 5]$$$. One of the ways to get rid of the monsters is shown below:  $$$2$$$$$$6$$$$$$7$$$$$$3$$$$$$\xrightarrow{6\ s}$$$$$$8$$$$$$13$$$$$$3$$$$$$\xrightarrow{13\ s}$$$$$$8$$$$$$3$$$$$$\xrightarrow{8\ s}$$$$$$6$$$$$$\xrightarrow{6\ s}$$$$$$\{\}$$$$$$3$$$$$$6$$$$$$0$$$$$$5$$$$$$3$$$$$$0$$$$$$5$$$$$$3$$$$$$5$$$$$$5$$$ The first row represents the health of each monster, the second one — the power of the spells. As a result, we can kill all monsters in $$$6 + 13 + 8 + 6$$$ $$$=$$$ $$$33$$$ seconds. Note that it's only an example and may not be the fastest way to get rid of the monsters.What is the minimum time required to kill all monsters in the row?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int a[n];
    int b[n];
    long long sum = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    scanf("%d", &b[0]);
    int max = b[0];
    sum += b[0] + a[0];
    for (int i = 1; i < n; i++) {
      scanf("%d", &b[i]);
      sum += a[i] + b[i];
      if (b[i] > max) {
        max = b[i];
      }
    }

    printf("%lld\n", sum - max);
  }
  return 0;
}

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let t = buffer.trim().parse::<u16>().unwrap();
    for _ in 0..t {
        buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        let n = buffer.trim().parse::<u32>().unwrap();

        buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        let a: Vec<u64> = buffer
            .split_whitespace()
            .map(|s| s.parse::<u64>().unwrap())
            .collect();

        buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        let b: Vec<u64> = buffer
            .split_whitespace()
            .map(|s| s.parse::<u64>().unwrap())
            .collect();

        let mut total = 0u64;
        let mut maxb = 0u64;
        for i in 0..n as usize {
            total += a[i] + b[i];
            if maxb < b[i] {
                maxb = b[i];
            };
        }
        total -= maxb;
        println!("{}", total);
    }
}


Score : <var>200</var> points

Problem Statement

We have a bingo card with a <var>3\times3</var> grid. The square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left contains the number <var>A_{i, j}</var>.

The MC will choose <var>N</var> numbers, <var>b_1, b_2, \cdots, b_N</var>. If our bingo sheet contains some of those numbers, we will mark them on our sheet.

Determine whether we will have a bingo when the <var>N</var> numbers are chosen, that is, the sheet will contain three marked numbers in a row, column, or diagonal.

Constraints

All values in input are integers.

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

<var>A_{i_1, j_1} \neq A_{i_2, j_2} ((i_1, j_1) \neq (i_2, j_2))</var>

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

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

<var>b_i \neq b_j (i \neq j)</var>

Input

Input is given from Standard Input in the following format:

<var>A_{1, 1}</var> <var>A_{1, 2}</var> <var>A_{1, 3}</var>
<var>A_{2, 1}</var> <var>A_{2, 2}</var> <var>A_{2, 3}</var>
<var>A_{3, 1}</var> <var>A_{3, 2}</var> <var>A_{3, 3}</var>
<var>N</var>
<var>b_1</var>
<var>\vdots</var>
<var>b_N</var>

Output

If we will have a bingo, print Yes; otherwise, print No.

Sample Input 1

84 97 66
79 89 11
61 59 7
7
89
7
87
79
24
84
30

Sample Output 1

Yes

We will mark <var>A_{1, 1}, A_{2, 1}, A_{2, 2}, A_{3, 3}</var>, and complete the diagonal from the top-left to the bottom-right.

Sample Input 2

41 7 46
26 89 2
78 92 8
5
6
45
16
57
17

Sample Output 2

No

We will mark nothing.

Sample Input 3

60 88 34
92 41 43
65 73 48
10
60
43
88
11
48
73
65
41
92
34

Sample Output 3

Yes

We will mark all the squares.

fn solution() {
    let mut A = Vec::<Vec<i64>>::new();
    for _ in 0..3 {
        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();

        A.push(words);
    }

    let mut N = String::new();

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

    let N: i64 = N.trim().parse().unwrap();

    let mut bingo = HashSet::new();

    for _ in 0..N {
        let mut b = String::new();

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

        let b: i64 = b.trim().parse().unwrap();
        bingo.insert(b);
    }

    let row1: HashSet<_> = [A[0][0], A[0][1], A[0][2]].iter().cloned().collect();
    let row2: HashSet<_> = [A[1][0], A[1][1], A[1][2]].iter().cloned().collect();
    let row3: HashSet<_> = [A[2][0], A[2][1], A[2][2]].iter().cloned().collect();
    let col1: HashSet<_> = [A[0][0], A[1][0], A[2][0]].iter().cloned().collect();
    let col2: HashSet<_> = [A[0][1], A[1][1], A[2][1]].iter().cloned().collect();
    let col3: HashSet<_> = [A[0][2], A[1][2], A[2][2]].iter().cloned().collect();
    let dia1: HashSet<_> = [A[0][0], A[1][1], A[2][2]].iter().cloned().collect();
    let dia2: HashSet<_> = [A[0][2], A[1][1], A[2][0]].iter().cloned().collect();

    let mut ans = false;
    if row1.is_subset(&bingo)
        || row2.is_subset(&bingo)
        || row3.is_subset(&bingo)
        || col1.is_subset(&bingo)
        || col2.is_subset(&bingo)
        || col3.is_subset(&bingo)
        || dia1.is_subset(&bingo)
        || dia2.is_subset(&bingo)
    {
        ans = true;
    }

    if ans {
        println!("Yes");
    } else {
        println!("No");
    }
}


Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $$$n$$$ stairs, then it is made of $$$n$$$ columns, the first column is $$$1$$$ cell high, the second column is $$$2$$$ cells high, $$$\ldots$$$, the $$$n$$$-th column if $$$n$$$ cells high. The lowest cells of all stairs must be in the same row.A staircase with $$$n$$$ stairs is called nice, if it may be covered by $$$n$$$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $$$7$$$ stairs looks like:  Find out the maximal number of different nice staircases, that can be built, using no more than $$$x$$$ cells, in total. No cell can be used more than once.

int solution(void) {
  int a = 0;
  scanf("%d", &a);
  while (a--) {
    long long k;
    scanf("%lld", &k);
    int m = 0;
    for (long long n = 1; n * (n + 1) / 2 <= k; n = 2 * n + 1) {
      k -= n * (n + 1) / 2;
      m++;
    }
    printf("%d\n", m);
  }
  return 0;
}

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

    handle.read_line(&mut buf).unwrap();
    let tests: i64 = buf.trim().parse().unwrap();

    for _test in 0..tests {
        buf.clear();
        handle.read_line(&mut buf).unwrap();

        let mut n: u64 = buf.trim().parse().unwrap();
        let mut a = 1u64;
        let mut score = 0u64;
        while n >= a + ((a - 1) / 2) * a {
            n -= a + ((a - 1) / 2) * a;
            a = a * 2 + 1;
            score += 1;
        }

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


Boboniu gives you  $$$r$$$ red balls,  $$$g$$$ green balls,  $$$b$$$ blue balls,  $$$w$$$ white balls. He allows you to do the following operation as many times as you want:   Pick a red ball, a green ball, and a blue ball and then change their color to white. You should answer if it's possible to arrange all the balls into a palindrome after several (possibly zero) number of described operations.

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut tests: u8 = line.trim().parse().unwrap();
    while tests > 0 {
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        let red: u32 = iter.next().unwrap().parse().unwrap();
        let green: u32 = iter.next().unwrap().parse().unwrap();
        let blue: u32 = iter.next().unwrap().parse().unwrap();
        let white: u32 = iter.next().unwrap().parse().unwrap();
        let odds = (red & 1) + (green & 1) + (blue & 1) + (white & 1);
        if if odds < 2 {
            true
        } else if odds > 2 {
            red > 0 && green > 0 && blue > 0
        } else {
            false
        } {
            println!("Yes");
        } else {
            println!("No");
        }
        tests -= 1;
    }
}


Enumeration of Subsets I

Print all subsets of a set $S$, which contains $0, 1, ... n-1$ as elements. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elements.

Input

  The input is given in the following format.

$n$

Output

  Print subsets ordered by their decimal integers. Print a subset in a line in the following format.

$d$: $e_0$ $e_1$ ...

  Print ':' after the integer value $d$, then print elements $e_i$ in the subset in ascending order. Seprate two adjacency elements by a space character.

Constraints

$1 \leq n \leq 18$

Sample Input 1

4

Sample Output 1

0:
1: 0
2: 1
3: 0 1
4: 2
5: 0 2
6: 1 2
7: 0 1 2
8: 3
9: 0 3
10: 1 3
11: 0 1 3
12: 2 3
13: 0 2 3
14: 1 2 3
15: 0 1 2 3

  Note that if the subset is empty, your program should not output a space character after ':'.

int solution() {
  long long k = 0;
  int n;
  scanf("%d", &n);
  printf("0:\n");
  for (int s = 1; s < pow(2, n); s++) {
    printf("%d:", s);
    for (int i = 0; i <= n - 1; i++) {
      if (s & (1 << i)) {
        printf(" %d", i);
      }
    }
    printf("\n");
  }
}

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

    let n = input.parse().unwrap();

    let out = stdout();
    let mut out = BufWriter::new(out.lock());
    writeln!(out, "0:");

    for p in 0..n {
        for d in (1 << p)..(2 << p) {
            write!(out, "{}:", d);

            for e in 0..p + 1 {
                if d & 1 << e != 0 {
                    write!(out, " {}", e);
                }
            }
            writeln!(out);
        }
    }
}


Score : <var>300</var> points

Problem Statement

You are given an undirected connected graph with <var>N</var> vertices and <var>M</var> edges that does not contain self-loops and double edges.

The <var>i</var>-th edge <var>(1 \leq i \leq M)</var> connects Vertex <var>a_i</var> and Vertex <var>b_i</var>.

An edge whose removal disconnects the graph is called a bridge.

Find the number of the edges that are bridges among the <var>M</var> edges.

Notes

A self-loop is an edge <var>i</var> such that <var>a_i=b_i</var> <var>(1 \leq i \leq M)</var>.

Double edges are a pair of edges <var>i,j</var> such that <var>a_i=a_j</var> and <var>b_i=b_j</var> <var>(1 \leq i<j \leq M)</var>.

An undirected graph is said to be connected when there exists a path between every pair of vertices.

Constraints

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

<var>N-1 \leq M \leq min(N(N−1)⁄2,50)</var>

<var>1 \leq a_i<b_i \leq N</var>

The given graph does not contain self-loops and double edges.

The given graph is connected.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>a_2</var> <var>b_2</var>
<var>:</var>
<var>a_M</var> <var>b_M</var>

Output

Print the number of the edges that are bridges among the <var>M</var> edges.

Sample Input 1

7 7
1 3
2 7
3 4
4 5
4 6
5 6
6 7

Sample Output 1

4

The figure below shows the given graph:

The edges shown in red are bridges. There are four of them.

Sample Input 2

3 3
1 2
1 3
2 3

Sample Output 2

0

It is possible that there is no bridge.

Sample Input 3

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

Sample Output 3

5

It is possible that every edge is a bridge.

int solution(void) {

  int n;
  int m;
  scanf("%d %d", &n, &m);
  int a[m];
  int b[m];
  for (int i = 0; i < m; i++) {
    scanf("%d %d", &a[i], &b[i]);
  }
  int check_list[n + 1];
  int flag;
  int bridge = 0;
  for (int i = 0; i < m; i++) {
    for (int j = 1; j <= n; j++) {
      check_list[j] = 0;
    }
    if (i == 0) {
      check_list[a[1]] = 1;
      check_list[b[1]] = 1;
    } else {
      check_list[a[0]] = 1;
      check_list[b[0]] = 1;
    }
    while (1) {
      flag = 0;
      for (int j = 0; j < m; j++) {
        if (j == i) {
          continue;
        }
        if (check_list[a[j]] == 0 && check_list[b[j]] == 1) {
          check_list[a[j]] = 1;
          flag = 1;
        } else if (check_list[a[j]] == 1 && check_list[b[j]] == 0) {
          check_list[b[j]] = 1;
          flag = 1;
        }
      }
      if (flag == 0) {
        break;
      }
    }
    flag = 1;
    for (int j = 1; j <= n; j++) {
      if (check_list[j] == 0) {
        flag = 0;
        break;
      }
    }
    if (flag == 0) {
      bridge++;
    }
  }
  printf("%d\n", bridge);

  return 0;
}

fn solution() {
    let (n, m) = input!(usize, usize);
    let mut edges: Vec<(usize, usize)> = Vec::with_capacity(m);
    let mut graph: Vec<Vec<bool>> = vec![vec![false; n + 1]; n + 1];
    for _ in 0..m {
        let (from, to) = input!(usize, usize);
        graph[from][to] = true;
        graph[to][from] = true;
        edges.push((from, to));
    }

    let mut cnt = 0;
    for &(from, to) in edges.iter() {
        graph[from][to] = false;
        graph[to][from] = false;
        let mut trail: Vec<bool> = vec![false; n + 1];
        let mut stack: Vec<usize> = vec![1];
        while let Some(edge_from) = stack.pop() {
            trail[edge_from] = true;
            for (edge_to, &is_exits_path) in graph[edge_from].iter().enumerate() {
                if is_exits_path && !trail[edge_to] && !stack.contains(&edge_to) {
                    stack.push(edge_to);
                }
            }
        }
        if trail.iter().skip(1).any(|&x| !x) {
            cnt += 1;
        }
        graph[from][to] = true;
        graph[to][from] = true;
    }
    println!("{}", cnt);
}


Tax Rate Changed

    VAT (value-added tax) is a tax imposed at a certain rate proportional to the sale price.

    Our store uses the following rules to calculate the after-tax prices.

	When the VAT rate is x%,
	for an item with the before-tax price of p yen,
	its after-tax price of the item is p (100+x) / 100 yen, fractions rounded off.

	The total after-tax price of multiple items paid at once is
	the sum of after-tax prices of the items.

    The VAT rate is changed quite often.
    Our accountant has become aware that
    "different pairs of items that had the same total after-tax price
    may have different total after-tax prices after VAT rate changes."
    For example, when the VAT rate rises from 5% to 8%,
    a pair of items that had the total after-tax prices of 105 yen before
    can now have after-tax prices either of 107, 108, or 109 yen, as shown in the table below.

Before-tax prices of two items	After-tax price with 5% VAT	After-tax price with 8% VAT

20, 80	21 + 84 = 105	21 + 86 = 107

2, 99	2 + 103 = 105	2 + 106 = 108

13, 88	13 + 92 = 105	14 + 95 = 109

    Our accountant is examining effects of VAT-rate changes on after-tax prices.
    You are asked to write a program that calculates the possible maximum
    total after-tax price of two items with the new VAT rate,
    knowing their total after-tax price before the VAT rate change.

Input

    The input consists of multiple datasets.
    Each dataset is in one line,
    which consists of three integers x, y, and s separated by a space.
    x is the VAT rate in percent before the VAT-rate change,
    y is the VAT rate in percent after the VAT-rate change,
    and s is the sum of after-tax prices of two items before the VAT-rate change.
    For these integers, 0 < x < 100, 0 < y < 100,
    10 < s < 1000, and x ≠ y hold.
    For before-tax prices of items, all possibilities of 1 yen through s-1 yen should be considered.

    The end of the input is specified by three zeros separated by a space.

Output

    For each dataset,
    output in a line the possible maximum total after-tax price when the VAT rate is changed to y%.

Sample Input

5 8 105
8 5 105
1 2 24
99 98 24
12 13 26
1 22 23
1 13 201
13 16 112
2 24 50
1 82 61
1 84 125
1 99 999
99 1 999
98 99 999
1 99 11
99 1 12
0 0 0

Output for the Sample Input

109
103
24
24
26
27
225
116
62
111
230
1972
508
1004
20
7

Hints

    In the following table,
    an instance of a before-tax price pair that has the maximum after-tax price after the VAT-rate change
    is given for each dataset of the sample input.

Dataset	Before-tax prices	After-tax price with y% VAT

5 8 105	   13, 88	 14 + 95 = 109

8 5 105	   12, 87	 12 + 91 = 103

1 2 24	     1, 23	  1 + 23 =  24

99 98 24	   1, 12	  1 + 23 =  24

12 13 26	   1, 23	  1 + 25 =  26

1 22 23	    1, 22	  1 + 26 =  27

1 13 201	   1,199	  1 +224 = 225

13 16 112	 25, 75	 29 + 87 = 116

2 24 50	   25, 25	 31 + 31 =  62

1 82 61	   11, 50	 20 + 91 = 111

1 84 125	  50, 75	 92 +138 = 230

1 99 999	  92,899	183+1789 =1972

99 1 999	   1,502	  1 +507 = 508

98 99 999	  5,500	  9 +995 =1004

1 99 11	    1, 10	  1 + 19 =  20

99 1 12	    1,  6	  1 +  6 =   7

fn solution() {
    loop {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).ok();
        let mut iter = buf.split_whitespace().map(|n| usize::from_str(n).unwrap());
        let (x, y, s) = (
            iter.next().unwrap(),
            iter.next().unwrap(),
            iter.next().unwrap(),
        );
        if x == 0 && y == 0 && s == 0 {
            return;
        }

        let mut yen_max = 0;
        for yen_a in 1..s {
            for yen_b in yen_a..s {
                if yen_a * (100 + x) / 100 + yen_b * (100 + x) / 100 == s {
                    let yen_candidate = yen_a * (100 + y) / 100 + yen_b * (100 + y) / 100;
                    if yen_candidate > yen_max {
                        yen_max = yen_candidate;
                    }
                } else if yen_a * (100 + x) / 100 + yen_b * (100 + x) / 100 > s {
                    break;
                }
            }
        }
        println!("{}", yen_max);
    }
}


This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format:  $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$  $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides.

int solution() {
  int frec[100001] = {0};
  char temp[2];
  long long int n = 0;
  long long int flag4 = 0;
  long long int flag2 = 0;
  scanf("%lld", &n);
  long long int max = 0;
  for (long long int i = 0; i < n; i++) {
    long long int tmp = 0;
    scanf("%lld", &tmp);
    flag4 -= frec[tmp] / 4;
    flag2 -= frec[tmp] / 2;
    frec[tmp]++;
    flag4 += frec[tmp] / 4;
    flag2 += frec[tmp] / 2;
  }
  long long int m = 0;
  scanf("%lld", &m);

  for (long long int i = 0; i < m; i++) {
    scanf("%c", &temp[0]);
    char act = 'A';
    long long int nr = 0;
    scanf("%c%lld", &act, &nr);
    flag4 -= frec[nr] / 4;
    flag2 -= frec[nr] / 2;
    if (act == '+') {
      frec[nr]++;
      flag4 += frec[nr] / 4;
      flag2 += frec[nr] / 2;
    } else {
      frec[nr]--;
      flag4 += frec[nr] / 4;
      flag2 += frec[nr] / 2;
    }
    if (flag4 >= 1 && flag2 >= 4) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

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

    let n: usize = {
        let mut buf = String::new();
        reader.read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

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

    let mut map: HashMap<usize, usize> = HashMap::new();
    let (mut fours, mut twos) = (0, 0);
    for i in 0..n {
        let val = map.entry(a[i]).or_insert(0);
        *val += 1;
        if (*val).is_multiple_of(4) {
            fours += 1;
            twos -= 1;
        } else if (*val).is_multiple_of(2) {
            twos += 1;
        }
    }

    let q: usize = {
        let mut buf = String::new();
        reader.read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };

    for _ in 0..q {
        let (c, x): (char, usize) = {
            let mut buf = String::new();
            reader.read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        if c == '+' {
            let val = map.entry(x).or_insert(0);
            *val += 1;
            if (*val).is_multiple_of(4) {
                fours += 1;
                twos -= 1;
            } else if (*val).is_multiple_of(2) {
                twos += 1;
            }
        } else {
            let val = map.entry(x).or_insert(0);
            if (*val).is_multiple_of(4) {
                fours -= 1;
                twos += 1;
            } else if (*val).is_multiple_of(2) {
                twos -= 1;
            }
            *val -= 1;
        }

        if fours >= 2 || (fours >= 1 && twos >= 2) {
            writeln!(writer, "YES").unwrap();
        } else {
            writeln!(writer, "NO").unwrap();
        }
    }
}


Score: <var>300</var> points

Problem Statement

Mr. Infinity has a string <var>S</var> consisting of digits from 1 to 9. Each time the date changes, this string changes as follows:

Each occurrence of 2 in <var>S</var> is replaced with 22. Similarly, each 3 becomes 333, 4 becomes 4444, 5 becomes 55555, 6 becomes 666666, 7 becomes 7777777, 8 becomes 88888888 and 9 becomes 999999999. 1 remains as 1.

For example, if <var>S</var> is 1324, it becomes 1333224444 the next day, and it becomes 133333333322224444444444444444 the day after next.
You are interested in what the string looks like after <var>5 \times 10^{15}</var> days. What is the <var>K</var>-th character from the left in the string after <var>5 \times 10^{15}</var> days?

Constraints

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

<var>K</var> is an integer between <var>1</var> and <var>10^{18}</var> (inclusive).

The length of the string after <var>5 \times 10^{15}</var> days is at least <var>K</var>.

Input

Input is given from Standard Input in the following format:

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

Output

Print the <var>K</var>-th character from the left in Mr. Infinity's string after <var>5 \times 10^{15}</var> days.

Sample Input 1

1214
4

Sample Output 1

2

The string <var>S</var> changes as follows:

Now: 1214

After one day: 12214444

After two days: 1222214444444444444444

After three days: 12222222214444444444444444444444444444444444444444444444444444444444444444

The first five characters in the string after <var>5 \times 10^{15}</var> days is 12222. As <var>K=4</var>, we should print the fourth character, 2.

Sample Input 2

3
157

Sample Output 2

3

The initial string is 3. The string after <var>5 \times 10^{15}</var> days consists only of 3.

Sample Input 3

299792458
9460730472580800

Sample Output 3

2

int solution() {
  char s[101];
  long n;
  scanf("%s %ld", s, &n);
  int i = 0;
  while (s[i] == '1' && i < n - 1) {
    i++;
  }
  printf("%c\n", s[i]);
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let sb: Vec<char> = s.trim().chars().collect();
    let mut ns = String::new();
    std::io::stdin().read_line(&mut ns).unwrap();
    let k: usize = ns.trim().parse().unwrap();

    let mut i: usize = 0;
    while i < k - 1 && sb[i] == '1' {
        i += 1;
    }
    println!("{}", sb[i]);
}


There are three cells on an infinite 2-dimensional grid, labeled $$$A$$$, $$$B$$$, and $$$F$$$. Find the length of the shortest path from $$$A$$$ to $$$B$$$ if:   in one move you can go to any of the four adjacent cells sharing a side;  visiting the cell $$$F$$$ is forbidden (it is an obstacle).

int solution() {
  int t;
  int ansar[10005];
  scanf("%d", &t);
  int start[2];
  int end[2];
  int obstacle[2];
  for (int y = 0; y < t; y++) {
    scanf("%d %d", &start[0], &start[1]);
    scanf("%d %d", &end[0], &end[1]);
    scanf("%d %d", &obstacle[0], &obstacle[1]);
    int ansx = end[0] < start[0] ? start[0] - end[0] : end[0] - start[0];
    int ansy = end[1] < start[1] ? start[1] - end[1] : end[1] - start[1];
    int answer = ansx + ansy;
    if (start[0] == end[0] && start[0] == obstacle[0]) {
      if ((obstacle[1] > start[1] && obstacle[1] < end[1]) ||
          (obstacle[1] > end[1] && obstacle[1] < start[1])) {
        answer += 2;
      }
    }
    if (start[1] == end[1] && start[1] == obstacle[1]) {
      if ((obstacle[0] > start[0] && obstacle[0] < end[0]) ||
          (obstacle[0] > end[0] && obstacle[0] < start[0])) {
        answer += 2;
      }
    }
    ansar[y] = answer;
  }

  for (int g = 0; g < t; g++) {
    printf("%d\n", ansar[g]);
  }
  return 0;
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    let mut i = i.lock().lines().skip(1);
    while let Some(_) = i.next() {
        if let [(ax, ay), (bx, by), (fx, fy)] = (0..3)
            .map(|_| {
                i.next()
                    .unwrap()
                    .unwrap()
                    .split(' ')
                    .map(|w| w.parse::<i32>().unwrap())
                    .collect::<Vec<_>>()
            })
            .map(|v| (v[0], v[1]))
            .collect::<Vec<_>>()[..]
        {
            let (ax, bx) = (ax.max(bx), ax.min(bx));
            let (ay, by) = (ay.max(by), ay.min(by));
            let r = if (ax == bx && bx == fx && (fy > by && fy < ay))
                || (ay == by && by == fy && (fx > bx && fx < ax))
            {
                2
            } else {
                0
            };
            writeln!(o, "{}", (ax - bx) + (ay - by) + r).ok();
        }
    }
}


Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.

fn solution() -> io::Result<()> {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s)?;
    let mut it = s.split_whitespace().map(|s| s.to_string());
    let t: usize = it.next().unwrap().parse().unwrap();
    let mut out = String::new();
    let m = i64::pow(10, 9) + 7;
    for _ in 1..=t {
        let n: i64 = it.next().unwrap().parse().unwrap();
        let mut k: i64 = it.next().unwrap().parse().unwrap();
        let mut bits = vec![];
        while k > 0 {
            let bit = k % 2;
            bits.push(bit);
            k /= 2;
        }
        let mut p = 1;
        let mut ans = 0;
        for bit in bits {
            if bit == 1 {
                ans += p;
                ans %= m;
            }
            p *= n;
            p %= m;
        }
        let ans = format!("{}\n", ans);
        out.push_str(ans.as_str());
    }
    print!("{}", out);
    Ok(())
}


A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length $$$0$$$ are not allowed).Let's consider empty cells are denoted by '.', then the following figures are stars:  The leftmost figure is a star of size $$$1$$$, the middle figure is a star of size $$$2$$$ and the rightmost figure is a star of size $$$3$$$. You are given a rectangular grid of size $$$n \times m$$$ consisting only of asterisks '*' and periods (dots) '.'. Rows are numbered from $$$1$$$ to $$$n$$$, columns are numbered from $$$1$$$ to $$$m$$$. Your task is to draw this grid using any number of stars or find out that it is impossible. Stars can intersect, overlap or even coincide with each other. The number of stars in the output can't exceed $$$n \cdot m$$$. Each star should be completely inside the grid. You can use stars of same and arbitrary sizes.In this problem, you do not need to minimize the number of stars. Just find any way to draw the given grid with at most $$$n \cdot m$$$ stars.

fn solution() {
    let input_handle = io::stdin();
    let input_line = &mut String::new();
    input_handle.read_line(input_line).unwrap();
    let mut input_parts = input_line
        .split_whitespace()
        .map(|token| token.parse::<usize>().unwrap());
    let n = input_parts.next().unwrap();
    let m = input_parts.next().unwrap();

    let field = &mut vec![vec!['.'; m]; n];
    for i in 0..n {
        let input_line = &mut String::new();
        input_handle.read_line(input_line).unwrap();
        for j in 0..m {
            field[i][j] = input_line.as_bytes()[j] as char;
        }
    }

    let up = &mut vec![vec![0i32; m]; n];
    let down = &mut vec![vec![0i32; m]; n];
    let left = &mut vec![vec![0i32; m]; n];
    let right = &mut vec![vec![0i32; m]; n];

    for i in 0..n {
        for j in 0..m {
            if field[i][j] == '.' {
            } else {
                if i > 0 {
                    up[i][j] = up[i - 1][j] + 1;
                } else {
                    up[i][j] = 1;
                }
                if j > 0 {
                    left[i][j] = left[i][j - 1] + 1;
                } else {
                    left[i][j] = 1;
                }
            }
        }
    }

    for i in (0..n).rev() {
        for j in (0..m).rev() {
            if field[i][j] == '.' {
            } else {
                if i < n - 1 {
                    down[i][j] = down[i + 1][j] + 1;
                } else {
                    down[i][j] = 1;
                }
                if j < m - 1 {
                    right[i][j] = right[i][j + 1] + 1;
                } else {
                    right[i][j] = 1;
                }
            }
        }
    }

    let h = &mut vec![vec![0i32; m]; n];
    let v = &mut vec![vec![0i32; m]; n];

    for i in 0..n {
        for j in 0..m {
            let len = min(min(up[i][j], down[i][j]), min(left[i][j], right[i][j])) - 1;
            if len <= 0 {
                continue;
            }
            let len = len as usize;
            h[i][j - len] += 1;
            if j + len + 1 < m {
                h[i][j + len + 1] -= 1;
            }
            v[i - len][j] += 1;
            if i + len + 1 < n {
                v[i + len + 1][j] -= 1;
            }
        }
    }

    for i in 0..n {
        for j in 0..m {
            if i > 0 {
                v[i][j] += v[i - 1][j];
            }
            if j > 0 {
                h[i][j] += h[i][j - 1];
            }
        }
    }

    let mut size = 0;
    for i in 0..n {
        for j in 0..m {
            let len = min(up[i][j], min(down[i][j], min(left[i][j], right[i][j]))) - 1;
            if len > 0 {
                size += 1;
            }
            let is_asterisk = h[i][j] > 0 || v[i][j] > 0;
            let is_asterisk2 = field[i][j] == '*';
            if is_asterisk != is_asterisk2 {
                println!("-1");
                return;
            }
        }
    }

    println!("{}", size);
    let mut s = String::new();
    for i in 0..n {
        for j in 0..m {
            let len = min(up[i][j], min(down[i][j], min(left[i][j], right[i][j]))) - 1;
            if len <= 0 {
                continue;
            }
            s += &fmt::format(format_args!("{} {} {}\n", i + 1, j + 1, len));
        }
    }
    print!("{}", s);
}


You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

int solution() {

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

  while (t--) {
    int n;
    int a;
    int b;
    scanf("%d %d %d", &n, &a, &b);

    char *s = malloc(sizeof(char) * (n + 1));
    scanf("%s", s);
    s[n] = '\0';

    int cost = a * n;
    if (b >= 0) {
      cost += b * n;
    } else {
      int num_o_groups = 0;
      int num_z_groups = 0;

      char last = 'z';
      for (int i = 0; i < n; i++) {
        if (s[i] == last) {
          continue;
        }
        last = s[i];
        if (s[i] == '0') {
          num_z_groups += 1;
        } else {
          num_o_groups += 1;
        }
      }

      if (num_o_groups < num_z_groups) {
        cost += (num_o_groups + 1) * b;
      } else {
        cost += (num_z_groups + 1) * b;
      }
    }

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

    free(s);
  }

  return 0;
}

fn solution() {
    let mut line = {
        let mut lines = std::io::stdin().lines();
        move || lines.next().unwrap().unwrap()
    };
    for _ in 0..line().parse().unwrap() {
        let (n, a, b) = {
            let line = line();
            let mut line = line.split_whitespace().map(|x| x.parse::<i32>().unwrap());
            (
                line.next().unwrap(),
                line.next().unwrap(),
                line.next().unwrap(),
            )
        };
        let bits: Vec<_> = line().chars().collect();
        println!(
            "{}",
            if b > 0 {
                n * (a + b)
            } else {
                let mut chunk = 0;
                for window in bits.windows(2) {
                    if window[0] != window[1] {
                        chunk += 1;
                    }
                }
                chunk = (chunk + 3) / 2;
                n * a + b * chunk
            }
        );
    }
}


A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \le i \le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?

int solution() {
  int tests = 0;

  scanf("%d", &tests);
  while (tests--) {
    int n = 0;
    scanf("%d", &n);

    printf("%d\n", (n / 2) + (n % 2));
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        println!("{}", (n - 1) / 2 + 1);
    }
}


Score : <var>200</var> points

Problem Statement

We have <var>A</var> cards, each of which has an integer <var>1</var> written on it. Similarly, we also have <var>B</var> cards with <var>0</var>s and <var>C</var> cards with <var>-1</var>s.

We will pick up <var>K</var> among these cards. What is the maximum possible sum of the numbers written on the cards chosen?

Constraints

All values in input are integers.

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

<var>1 \leq K \leq A + B + C \leq 2 \times 10^9</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible sum of the numbers written on the cards chosen.

Sample Input 1

2 1 1 3

Sample Output 1

2

Consider picking up two cards with <var>1</var>s and one card with a <var>0</var>.
In this case, the sum of the numbers written on the cards is <var>2</var>, which is the maximum possible value.

Sample Input 2

1 2 3 4

Sample Output 2

0

Sample Input 3

2000000000 0 0 2000000000

Sample Output 3

2000000000

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

  scanf("%lld %lld %lld %lld", &A, &B, &C, &K);

  if (A <= K && K <= A + B) {
    printf("%lld", A);
  } else if (K < A) {
    printf("%lld", K);
  } else {
    printf("%lld", A - (K - A - B));
  }

  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let nums: Vec<i32> = line
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();
    let (mut a, b, _, mut k) = (nums[0], nums[1], nums[2], nums[3]);

    if k >= a {
        k -= a;
    } else {
        a = k;
        k = 0;
    }

    if k >= b {
        k -= b;
    } else {
        k = 0;
    }

    let c = -k;

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


A Pythagorean triple is a triple of integer numbers $$$(a, b, c)$$$ such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to $$$a$$$, $$$b$$$ and $$$c$$$, respectively. An example of the Pythagorean triple is $$$(3, 4, 5)$$$.Vasya studies the properties of right triangles, and he uses a formula that determines if some triple of integers is Pythagorean. Unfortunately, he has forgotten the exact formula; he remembers only that the formula was some equation with squares. So, he came up with the following formula: $$$c = a^2 - b$$$.Obviously, this is not the right formula to check if a triple of numbers is Pythagorean. But, to Vasya's surprise, it actually worked on the triple $$$(3, 4, 5)$$$: $$$5 = 3^2 - 4$$$, so, according to Vasya's formula, it is a Pythagorean triple.When Vasya found the right formula (and understood that his formula is wrong), he wondered: how many are there triples of integers $$$(a, b, c)$$$ with $$$1 \le a \le b \le c \le n$$$ such that they are Pythagorean both according to his formula and the real definition? He asked you to count these triples.

int solution(void) {

  int T;
  int N;

  scanf("%d", &T);
  while (T--) {
    scanf("%d", &N);

    int i = 1;
    while (2 * i * i + 2 * i + 1 <= N) {
      i++;
    }
    printf("%d\n", i - 1);
  }
}

fn solution() {
    use std::io::{self, Write};

    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 n: usize = sc.next();
    let queries: Vec<i64> = (0..n).map(|_| sc.next()).collect();
    let mut set: BTreeSet<i64> = BTreeSet::new();
    let mut a: i64 = 2;
    while (a * a - 1) / 2 < 1e9 as i64 {
        let b = (a * a - 1) / 2;
        let c = b + 1;
        if a <= b && b <= c && ((a * a + b * b) == (c * c)) && (c == (a * a - b)) {
            set.insert(c);
        }
        a += 1;
    }
    let ns: Vec<i64> = set.into_iter().collect();
    for query in queries {
        let lower = ns
            .binary_search_by(|x| {
                if *x <= query {
                    Ordering::Less
                } else {
                    Ordering::Greater
                }
            })
            .err()
            .unwrap();
        writeln!(out, "{}", lower).unwrap();
    }
}


Madoka as a child was an extremely capricious girl, and one of her favorite pranks was drawing on her wall. According to Madoka's memories, the wall was a table of $$$n$$$ rows and $$$m$$$ columns, consisting only of zeroes and ones. The coordinate of the cell in the $$$i$$$-th row and the $$$j$$$-th column ($$$1 \le i \le n$$$, $$$1 \le j \le m$$$) is $$$(i, j)$$$.One day she saw a picture "Mahou Shoujo Madoka Magica" and decided to draw it on her wall. Initially, the Madoka's table is a table of size $$$n \times m$$$ filled with zeroes. Then she applies the following operation any number of times:Madoka selects any rectangular subtable of the table and paints it in a chess coloring (the upper left corner of the subtable always has the color $$$0$$$). Note that some cells may be colored several times. In this case, the final color of the cell is equal to the color obtained during the last repainting.  White color means $$$0$$$, black means $$$1$$$. So, for example, the table in the first picture is painted in a chess coloring, and the others are not. For better understanding of the statement, we recommend you to read the explanation of the first test.Help Madoka and find some sequence of no more than $$$n \cdot m$$$ operations that allows you to obtain the picture she wants, or determine that this is impossible.

fn solution() {
    let std_in = stdin();
    let mut input = Scanner::new(std_in.lock());

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

    let tests = input.token();
    for _ in 0..tests {
        let (n, m): (usize, usize) = (input.token(), input.token());
        let a: Vec<Vec<_>> = (0..n)
            .map(|_| input.token::<String>().chars().map(|c| c == '1').collect())
            .collect();
        if a[0][0] {
            writeln!(&mut output, "-1").unwrap();
            continue;
        }

        let mut result = Vec::new();
        for r in (0..n).rev() {
            for c in (0..m).rev() {
                if a[r][c] {
                    if c == 0 {
                        result.push((r - 1, c, r, c));
                    } else {
                        result.push((r, c - 1, r, c));
                    }
                }
            }
        }

        writeln!(&mut output, "{}", result.len()).unwrap();
        for (a, b, c, d) in result {
            writeln!(&mut output, "{} {} {} {}", a + 1, b + 1, c + 1, d + 1).unwrap();
        }
    }
}


Score : <var>300</var> points

Problem Statement

You are given an array <var>A</var> of length <var>N</var>.
Your task is to divide it into several contiguous subarrays.
Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order.
At least how many subarrays do you need to divide <var>A</var> into?

Constraints

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

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

Each <var>A_i</var> is an integer.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum possible number of subarrays after division of <var>A</var>.

Sample Input 1

6
1 2 3 2 2 1

Sample Output 1

2

One optimal solution is to divide the array into <var>[1,2,3]</var> and <var>[2,2,1]</var>.

Sample Input 2

9
1 2 1 2 1 2 1 2 1

Sample Output 2

5

Sample Input 3

7
1 2 3 2 1 999999999 1000000000

Sample Output 3

3

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

    let (ans, _, _) = A[1..].iter().fold((1, A[0], 0), |(res, prev, sign), &a| {
        let d = a - prev;
        if d == 0 {
            (res, a, sign)
        } else if d > 0 && sign >= 0 || d <= 0 && sign <= 0 {
            (res, a, d)
        } else {
            (res + 1, a, 0)
        }
    });

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


Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things:  Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one);  Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves:  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$.  You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$.  You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$.  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$.  You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int root = sqrt(n);
    if (root * root >= n) {
      printf("%d\n", (2 * root) - 2);
    } else if ((root + 1) * root >= n) {
      printf("%d\n", (2 * root) - 1);
    } else {
      printf("%d\n", 2 * root);
    }
  }
}

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

    for _i in 0..t {
        let mut n = String::new();
        io::stdin().read_line(&mut n).unwrap();
        let n = n.trim().parse::<i32>().unwrap();

        let mut ans = 1000000000;
        let mut x = 1;

        while x * x <= n {
            let some = x - 1 + ((n - x) + x - 1) / x;

            ans = match ans.cmp(&some) {
                Ordering::Less => ans,
                _ => some,
            };

            x += 1;
        }

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


Score : <var>300</var> points

Problem Statement

AtCoDeer the deer is seeing a quick report of election results on TV.
Two candidates are standing for the election: Takahashi and Aoki.
The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes.
AtCoDeer has checked the report <var>N</var> times, and when he checked it for the <var>i</var>-th <var>(1≦i≦N)</var> time, the ratio was <var>T_i:A_i</var>.
It is known that each candidate had at least one vote when he checked the report for the first time.

Find the minimum possible total number of votes obtained by the two candidates when he checked the report for the <var>N</var>-th time.
It can be assumed that the number of votes obtained by each candidate never decreases.

Constraints

<var>1≦N≦1000</var>

<var>1≦T_i,A_i≦1000 (1≦i≦N)</var>

<var>T_i</var> and <var>A_i</var> <var>(1≦i≦N)</var> are coprime.

It is guaranteed that the correct answer is at most <var>10^{18}</var>.

Input

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

<var>N</var>
<var>T_1</var> <var>A_1</var>
<var>T_2</var> <var>A_2</var>
<var>:</var>
<var>T_N</var> <var>A_N</var>

Output

Print the minimum possible total number of votes obtained by Takahashi and Aoki when AtCoDeer checked the report for the <var>N</var>-th time.

Sample Input 1

3
2 3
1 1
3 2

Sample Output 1

10

When the numbers of votes obtained by the two candidates change as <var>2,3 → 3,3 → 6,4</var>, the total number of votes at the end is <var>10</var>, which is the minimum possible number.

Sample Input 2

4
1 1
1 1
1 5
1 100

Sample Output 2

101

It is possible that neither candidate obtained a vote between the moment when he checked the report, and the moment when he checked it for the next time.

Sample Input 3

5
3 10
48 17
31 199
231 23
3 2

Sample Output 3

6930

int solution() {
  int n;
  scanf("%d", &n);
  long long int t[n];
  long long int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%lld%lld", &t[i], &a[i]);
  }
  long long int tz = t[0];
  long long int az = a[0];
  for (int i = 1; i < n; i++) {
    long long int r = tz / t[i];
    long long int s = az / a[i];
    long long int p = 0;
    long long int q = 0;
    if (r > s) {
      p = r * t[i];
      q = r * a[i];
    } else {
      p = s * t[i];
      q = s * a[i];
    }
    while (p < tz || q < az) {
      p += t[i];
      q += a[i];
    }
    tz = p;
    az = q;
  }
  printf("%lld\n", tz + az);

  return 0;
}

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

    let mut x: usize = 1;
    let mut a: usize = 0;
    let mut b: usize = 0;
    for _ in 0..n {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let v: Vec<usize> = s.trim().split(' ').map(|x| x.parse().unwrap()).collect();
        let y = v[0] + v[1];
        let mut i: usize = std::cmp::max(x / y, std::cmp::max(a / v[0], b / v[1]));
        while y * i < x || v[0] * i < a || v[1] * i < b {
            i += 1;
        }
        x = y * i;
        a = v[0] * i;
        b = v[1] * i;
    }
    println!("{}", x);
}


Homer has two friends Alice and Bob. Both of them are string fans. One day, Alice and Bob decide to play a game on a string $$$s = s_1 s_2 \dots s_n$$$ of length $$$n$$$ consisting of lowercase English letters. They move in turns alternatively and Alice makes the first move.In a move, a player must choose an index $$$i$$$ ($$$1 \leq i \leq n$$$) that has not been chosen before, and change $$$s_i$$$ to any other lowercase English letter $$$c$$$ that $$$c \neq s_i$$$.When all indices have been chosen, the game ends. The goal of Alice is to make the final string lexicographically as small as possible, while the goal of Bob is to make the final string lexicographically as large as possible. Both of them are game experts, so they always play games optimally. Homer is not a game expert, so he wonders what the final string will be.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

int solution(void) {
  int tc = 1;
  scanf("%d", &tc);
  while (tc--) {
    char str[50];
    scanf("%s", str);
    for (int i = 0; str[i]; i++) {
      if (i % 2) {
        if (str[i] == 'z') {
          str[i] = 'y';
        } else {
          str[i] = 'z';
        }
      } else {
        if (str[i] == 'a') {
          str[i] = 'b';
        } else {
          str[i] = 'a';
        }
      }
    }
    printf("%s\n", str);
  }
  return 0;
}

fn solution() {
    let k = std::io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i32>()
        .unwrap();
    for _ele in 0..k {
        let mut kstr = String::new();
        std::io::stdin().read_line(&mut kstr).unwrap();
        let kstr = kstr.trim();
        for (index, st_ele) in kstr.as_bytes().iter().enumerate() {
            if index % 2 == 0 {
                if st_ele == &b'a' {
                    print!("b")
                } else {
                    print!("a")
                }
            } else {
                if st_ele == &b'z' {
                    print!("y")
                } else {
                    print!("z")
                }
            }
        }
        println!();
    }
}


There is a sheet of paper that can be represented with a grid of size $$$n \times m$$$: $$$n$$$ rows and $$$m$$$ columns of cells. All cells are colored in white initially.$$$q$$$ operations have been applied to the sheet. The $$$i$$$-th of them can be described as follows:   $$$x_i$$$ $$$y_i$$$ — choose one of $$$k$$$ non-white colors and color the entire row $$$x_i$$$ and the entire column $$$y_i$$$ in it. The new color is applied to each cell, regardless of whether the cell was colored before the operation. The sheet after applying all $$$q$$$ operations is called a coloring. Two colorings are different if there exists at least one cell that is colored in different colors.How many different colorings are there? Print the number modulo $$$998\,244\,353$$$.

int solution() {
  int t = 0;
  int nm[2] = {};
  long long k = 0LL;
  int q = 0;
  int xy[200000][2] = {};

  int res = 0;

  long long mod_num = 998244353;

  int colored[2][200000] = {};

  res = scanf("%d", &t);
  while (t > 0) {
    long long ans = 1LL;
    int colored_cnt[2] = {};
    res = scanf("%d", nm);
    res = scanf("%d", nm + 1);
    res = scanf("%lld", &k);
    res = scanf("%d", &q);
    for (int i = 0; i < q; i++) {
      res = scanf("%d", xy[i]);
      res = scanf("%d", xy[i] + 1);
      xy[i][0]--;
      xy[i][1]--;
    }

    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < nm[i]; j++) {
        colored[i][j] = 0;
      }
    }

    for (int i = q - 1; i >= 0; i--) {
      int is_colored = 0;
      for (int j = 0; j < 2; j++) {
        if (colored[j][xy[i][j]] <= 0 && colored_cnt[1 - j] < nm[1 - j]) {
          is_colored = 1;
          colored_cnt[j]++;
        }
        colored[j][xy[i][j]] = 1;
      }
      if (is_colored > 0) {
        ans = (ans * k) % mod_num;
      }
    }

    printf("%lld\n", ans);
    t--;
  }

  return 0;
}

fn solution() {
    let stdin = stdin();
    let mut stdin = stdin.lock();

    let mut buf = String::new();
    stdin.read_to_string(&mut buf).unwrap();

    let input = &mut buf
        .split_ascii_whitespace()
        .map(|s| s.parse::<u32>().unwrap());
    let mut input = || input.next().unwrap();

    let nn = input() as usize;

    let mut data = Vec::new();
    let mut used = Vec::new();

    const Q: u64 = 998244353;

    let mut ans = Vec::new();
    for _ii in 0..nn {
        let (n, m, k, q) = (
            input() as usize,
            input() as usize,
            input() as u64,
            input() as usize,
        );

        data.clear();
        data.extend((0..q).map(|_| (input(), input())));

        used.clear();
        used.resize(n + m, false);

        let mut z = 0;
        let (mut nr, mut nc) = (0, 0);
        for &(i, j) in data.iter().rev() {
            let dr = 1 - replace(&mut used[i as usize - 1], true) as usize;
            let dc = 1 - replace(&mut used[j as usize + n - 1], true) as usize;
            z += dr | dc;

            nr += dr;
            nc += dc;
            if nr >= n || nc >= m {
                break;
            }
        }

        let mut acc = 1;
        let mut step = k;
        loop {
            if z & 1 != 0 {
                acc = acc * step % Q;
            }
            z >>= 1;
            if z == 0 {
                break;
            }
            step = step * step % Q;
        }

        writeln!(ans, "{acc}").unwrap();
    }

    stdout().write(&ans).unwrap();
}


Phoenix is playing with a new puzzle, which consists of $$$n$$$ identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.    A puzzle piece The goal of the puzzle is to create a square using the $$$n$$$ pieces. He is allowed to rotate and move the pieces around, but none of them can overlap and all $$$n$$$ pieces must be used (of course, the square shouldn't contain any holes as well). Can he do it?

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

    let mut n = String::new();
    'test: for _t in 0..t {
        n.clear();
        io::stdin().read_line(&mut n).unwrap();
        let mut n: u64 = n.trim().parse().unwrap();
        for _i in 0..2 {
            if n % 2 == 1 {
                break;
            }

            n /= 2;
            let n_sqrt: f64 = (n as f64).sqrt() + 0.1;
            let n_sqrt_trunc: u64 = n_sqrt as u64;
            if n_sqrt_trunc * n_sqrt_trunc == n {
                println!("YES");
                continue 'test;
            }
        }
        println!("NO");
    }
}