You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    char arr[1002];
    int total = 0;
    int ch[260];
    for (int g = 0; g < 260; g++) {
      ch[g] = 0;
    }
    for (int i = 0; i < n; i++) {
      scanf("%s", arr);
      total += strlen(arr);
      for (int y = 0; arr[y] != 0; y++) {
        ch[arr[y]]++;
      }
    }
    int win = 1;
    for (int h = 0; h < 260; h++) {
      if (ch[h] % n == 0) {
        continue;
      }
      win = 0;
      break;
    }
    if (win == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

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

    stdin.read_line(&mut input)?;

    let t: u8 = input.trim().parse().expect("'t' is not a integer!");
    input.clear();

    for _ in 0..t {
        stdin.read_line(&mut input)?;
        let n: usize = input.trim().parse().expect("'n' is not a integer!");
        input.clear();

        let mut freq: [usize; 256] = [0; 256];

        for _ in 0..n {
            stdin.read_line(&mut input)?;

            for &i in input.trim().as_bytes() {
                freq[i as usize] += 1;
            }

            input.clear();
        }

        let x: usize = freq.iter().map(|i| i % n).sum();

        if x == 0 {
            println!("YES")
        } else {
            println!("NO")
        }
    }

    Ok(())
}


Score : <var>200</var> points

Problem Statement

In some village, there are <var>999</var> towers that are <var>1,(1+2),(1+2+3),...,(1+2+3+...+999)</var> meters high from west to east, at intervals of <var>1</var> meter.

It had been snowing for a while before it finally stopped. For some two adjacent towers located <var>1</var> meter apart, we measured the lengths of the parts of those towers that are not covered with snow, and the results are <var>a</var> meters for the west tower, and <var>b</var> meters for the east tower.

Assuming that the depth of snow cover and the altitude are the same everywhere in the village, find the amount of the snow cover.

Assume also that the depth of the snow cover is always at least <var>1</var> meter.

Constraints

<var>1 \leq a < b < 499500(=1+2+3+...+999)</var>

All values in input are integers.

There is no input that contradicts the assumption.

Input

Input is given from Standard Input in the following format:

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

Output

If the depth of the snow cover is <var>x</var> meters, print <var>x</var> as an integer.

Sample Input 1

8 13

Sample Output 1

2

The heights of the two towers are <var>10</var> meters and <var>15</var> meters, respectively.
Thus, we can see that the depth of the snow cover is <var>2</var> meters.

Sample Input 2

54 65

Sample Output 2

1

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

  int i = 0;
  int sum = 0;
  for (i = 1; i <= b - a; i++) {
    sum += i;
  }
  printf("%d\n", sum - b);
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let vec: Vec<&str> = buf.split_whitespace().collect();
    let a: i32 = vec[0].parse().unwrap();
    let b: i32 = vec[1].parse().unwrap();
    let c: i32 = b - a;
    let mut ans = 0;
    for x in 1..c {
        ans += x;
    }
    println!("{:?}", ans - a);
}


A frog is currently at the point $$$0$$$ on a coordinate axis $$$Ox$$$. It jumps by the following algorithm: the first jump is $$$a$$$ units to the right, the second jump is $$$b$$$ units to the left, the third jump is $$$a$$$ units to the right, the fourth jump is $$$b$$$ units to the left, and so on.Formally:   if the frog has jumped an even number of times (before the current jump), it jumps from its current position $$$x$$$ to position $$$x+a$$$;  otherwise it jumps from its current position $$$x$$$ to position $$$x-b$$$. Your task is to calculate the position of the frog after $$$k$$$ jumps.But... One more thing. You are watching $$$t$$$ different frogs so you have to answer $$$t$$$ independent queries.

fn solution() {
    let mut input = String::new();
    std::io::stdin()
        .read_line(&mut input)
        .expect("INPUT::read line failed");

    let mut amount = input
        .trim()
        .parse::<i32>()
        .expect("AMOUNT::parse i32 failed");

    while amount > 0 {
        let mut input = String::new();
        std::io::stdin()
            .read_line(&mut input)
            .expect("INPUT::read line failed");
        let mut input = input.trim().split(' ');
        let mut numbers = [i64::default(); 3];

        for i in numbers.iter_mut() {
            *i = input.next().unwrap().parse::<i64>().unwrap();
        }

        let outcome = (numbers[0] - numbers[1]) * (numbers[2] / 2);

        match numbers[2] % 2 {
            1 => println!("{}", outcome + numbers[0]),
            0 => println!("{}", outcome),
            _ => {}
        }

        amount -= 1;
    }
}


Score : <var>600</var> points

Problem Statement

We have <var>3N</var> cards arranged in a row from left to right, where each card has an integer between <var>1</var> and <var>N</var> (inclusive) written on it. The integer written on the <var>i</var>-th card from the left is <var>A_i</var>.

You will do the following operation <var>N-1</var> times:

Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain <var>1</var> point.

After these <var>N-1</var> operations, if the integers written on the remaining three cards are all equal, you will gain <var>1</var> additional point.

Find the maximum number of points you can gain.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>\cdots</var> <var>A_{3N}</var>

Output

Print the maximum number of points you can gain.

Sample Input 1

2
1 2 1 2 2 1

Sample Output 1

2

Let us rearrange the five leftmost cards so that the integers written on the six cards will be <var>2\ 2\ 2\ 1\ 1\ 1</var> from left to right.

Then, remove the three leftmost cards, all of which have the same integer <var>2</var>, gaining <var>1</var> point.

Now, the integers written on the remaining cards are <var>1\ 1\ 1</var>.

Since these three cards have the same integer <var>1</var>, we gain <var>1</var> more point.

In this way, we can gain <var>2</var> points - which is the maximum possible.

Sample Input 2

3
1 1 2 2 3 3 3 2 1

Sample Output 2

1

Sample Input 3

3
1 1 2 2 2 3 3 3 1

Sample Output 3

3

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let S: Vec<usize> = buf.split_whitespace().map(|s| s.parse().unwrap()).collect();
    let N = S[0];

    let mut dp1 = vec![None; N + 1];
    let mut dp2 = vec![vec![None; N + 1]; N + 1];
    {
        let mut s = S[1..=2].to_vec();
        s.sort();
        let (a, b) = (s[0], s[1]);
        dp1[a].get_or_insert(0);
        dp1[b].get_or_insert(0);
        dp1[0].get_or_insert(0);
        dp2[a][b].get_or_insert(0);
    }

    let mut base = 0;
    let mut q = Vec::new();

    for i in 1..N {
        let mut s = S[3 * i..3 * (i + 1)].to_vec();
        s.sort();
        let (a, b, c) = (s[0], s[1], s[2]);

        if a == c {
            base += 1;
            continue;
        } else if a == b {
            for x in 1..=N {
                if x < a {
                    if let Some(v) = dp2[x][a] {
                        q.push((x, c, v + 1));
                    }
                } else if x < c {
                    if let Some(v) = dp2[a][x] {
                        q.push((x, c, v + 1));
                    }
                } else {
                    if let Some(v) = dp2[a][x] {
                        q.push((c, x, v + 1));
                    }
                }
            }
            if let Some(v) = dp2[c][c] {
                q.push((a, a, v + 1));
            }
        } else if b == c {
            for x in 1..=N {
                if x < a {
                    if let Some(v) = dp2[x][c] {
                        q.push((x, a, v + 1));
                    }
                } else if x < c {
                    if let Some(v) = dp2[x][c] {
                        q.push((a, x, v + 1));
                    }
                } else {
                    if let Some(v) = dp2[c][x] {
                        q.push((a, x, v + 1));
                    }
                }
            }
            if let Some(v) = dp2[a][a] {
                q.push((c, c, v + 1));
            }
        } else {
            if let Some(v) = dp2[a][a] {
                q.push((b, c, v + 1));
            }
            if let Some(v) = dp2[b][b] {
                q.push((a, c, v + 1));
            }
            if let Some(v) = dp2[c][c] {
                q.push((a, b, v + 1));
            }
        }

        q.push((a, b, dp1[0].unwrap()));
        q.push((a, c, dp1[0].unwrap()));
        q.push((b, c, dp1[0].unwrap()));

        for x in 1..=N {
            if let Some(v) = dp1[x] {
                for y in &[a, b, c] {
                    if x < *y {
                        q.push((x, *y, v));
                    } else {
                        q.push((*y, x, v));
                    }
                }
            }
        }

        while let Some((a, b, v)) = q.pop() {
            if dp2[a][b].is_none() || dp2[a][b].unwrap() < v {
                let u = dp2[a][b].get_or_insert(v);
                *u = v;
                for i in &[0, a, b] {
                    let u = dp1[*i].get_or_insert(v);
                    *u = max(*u, v);
                }
            }
        }
    }

    let s = S[S.len() - 1];
    println!(
        "{}",
        match dp2[s][s] {
            Some(_v) => base + max(1 + dp2[s][s].unwrap_or(0), dp1[0].unwrap_or(0)),
            None => base + dp1[0].unwrap(),
        }
    );
}


Score : <var>200</var> points

Problem Statement

Square1001 has seen an electric bulletin board displaying the integer <var>1</var>.
He can perform the following operations A and B to change this value:

Operation A: The displayed value is doubled.

Operation B: The displayed value increases by <var>K</var>.

Square1001 needs to perform these operations <var>N</var> times in total.
Find the minimum possible value displayed in the board after <var>N</var> operations.

Constraints

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum possible value displayed in the board after <var>N</var> operations.

Sample Input 1

4
3

Sample Output 1

10

The value will be minimized when the operations are performed in the following order: A, A, B, B.

In this case, the value will change as follows: <var>1</var> → <var>2</var> → <var>4</var> → <var>7</var> → <var>10</var>.

Sample Input 2

10
10

Sample Output 2

76

The value will be minimized when the operations are performed in the following order: A, A, A, A, B, B, B, B, B, B.

In this case, the value will change as follows: <var>1</var> → <var>2</var> → <var>4</var> → <var>8</var> → <var>16</var> → <var>26</var> → <var>36</var> → <var>46</var> → <var>56</var> → <var>66</var> → <var>76</var>.

By the way, this contest is AtCoder Beginner Contest 076.

int solution() {
  int n = 0;
  int k = 0;
  int x = 1;
  scanf("%d\n%d", &n, &k);
  for (int i = 0; i < n; i++) {
    if (2 * x <= x + k) {
      x *= 2;
    } else {
      x += k;
    }
  }
  printf("%d\n", x);
}

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

    let mut ans = 1;
    for _i in 0..n {
        if ans < k {
            ans *= 2;
        } else {
            ans += k;
        }
    }
    println!("{}", ans);
}


You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf    cur = init    ok = true    for i = 1 to |s|        res = res + 1        if s[i] == '+'            cur = cur + 1        else            cur = cur - 1        if cur < 0            ok = false            break    if ok        breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.

int solution() {

  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    char s[1000000];
    scanf("%s", s);
    int n = strlen(s);
    int a[n];
    int b[n];
    long long int r = 0;
    long long int c = 0;
    for (int i = 0; i < n; i++) {
      if (s[i] == '+') {
        a[i] = 1;
      } else {
        a[i] = -1;
      }
    }
    long int sum = 0;
    long int j = -1;
    for (int i = 0; i < n; i++) {
      sum = sum + a[i];
      r++;
      if (sum == j) {

        j--;

        c = c + r;
      }
    }
    c = c + n;

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

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).expect("");
    let s: u64 = s.trim().parse().expect("");
    for _i in 0..s {
        let mut st = String::new();
        io::stdin().read_line(&mut st).expect("");
        let st = st.trim();
        let l = st.len();
        let mut rez = st.len() as u64;
        let mut cnt = 0;
        let mut mi = 0;
        let mut st = st.chars();
        for j in 0_usize..l {
            let a = st.next().unwrap();
            if a == '+' {
                cnt += 1;
            } else if a == '-' {
                cnt -= 1;
            }
            if cnt < mi {
                mi = cnt;
                rez += (j + 1) as u64;
            }
        }
        println!("{}", rez);
    }
}


Alicia has an array, $$$a_1, a_2, \ldots, a_n$$$, of non-negative integers. For each $$$1 \leq i \leq n$$$, she has found a non-negative integer $$$x_i = max(0, a_1, \ldots, a_{i-1})$$$. Note that for $$$i=1$$$, $$$x_i = 0$$$.For example, if Alicia had the array $$$a = \{0, 1, 2, 0, 3\}$$$, then $$$x = \{0, 0, 1, 2, 2\}$$$.Then, she calculated an array, $$$b_1, b_2, \ldots, b_n$$$: $$$b_i = a_i - x_i$$$.For example, if Alicia had the array $$$a = \{0, 1, 2, 0, 3\}$$$, $$$b = \{0-0, 1-0, 2-1, 0-2, 3-2\} = \{0, 1, 1, -2, 1\}$$$.Alicia gives you the values $$$b_1, b_2, \ldots, b_n$$$ and asks you to restore the values $$$a_1, a_2, \ldots, a_n$$$. Can you help her solve the problem?

int solution(void) {
  int n;
  int b[200007];
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &b[i]);
  }
  int maxi = 0;
  for (int i = 0; i < n; i++) {
    printf("%d ", maxi + b[i]);

    if (b[i] > 0) {
      maxi += b[i];
    }
  }
  puts("");
}

fn solution() -> io::Result<()> {
    let mut input = String::new();

    let mut a: Vec<i32> = Vec::new();
    let mut b: Vec<i32> = Vec::new();

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

    for i in input.split_ascii_whitespace() {
        b.push(i.parse().unwrap());
    }

    let mut max = 0;

    for i in b {
        let x = i + max;
        if x > max {
            max = x;
        }
        a.push(x);
    }

    for (i, item) in a.iter().enumerate() {
        if i == 0 {
            print!("{}", item);
        } else {
            print!(" {}", item);
        }
    }
    println!();

    Ok(())
}


Score : <var>400</var> points

Problem Statement

One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence <var>(a_1, ..., a_N)</var> of length <var>N</var>.
He is interested in properties of the sequence <var>a</var>.

For a nonempty contiguous subsequence <var>a_l, ..., a_r</var> <var>(1 \leq l \leq r \leq N)</var> of the sequence <var>a</var>, its beauty is defined as <var>a_l + ... + a_r</var>. Niwango-kun wants to know the maximum possible value of the bitwise AND of the beauties of <var>K</var> nonempty contiguous subsequences among all <var>N(N+1)/2</var> nonempty contiguous subsequences. (Subsequences may share elements.)

Find the maximum possible value for him.

Constraints

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

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

<var>1 \leq K \leq N(N+1)/2</var>

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

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

Output

Print the answer.

Sample Input 1

4 2
2 5 2 5

Sample Output 1

12

There are <var>10</var> nonempty contiguous subsequences of <var>a</var>. Let us enumerate them:

contiguous subsequences starting from the first element: <var>\{2\}, \{2, 5\}, \{2, 5, 2\}, \{2, 5, 2, 5\}</var>

contiguous subsequences starting from the second element: <var>\{5\}, \{5, 2\}, \{5, 2, 5\}</var>

contiguous subsequences starting from the third element: <var>\{2\}, \{2, 5\}</var>

contiguous subsequences starting from the fourth element: <var>\{5\}</var>

(Note that even if the elements of subsequences are equal, subsequences that have different starting indices are considered to be different.)

The maximum possible bitwise AND of the beauties of two different contiguous subsequences is <var>12</var>.
This can be achieved by choosing <var>\{5, 2, 5\}</var> (with beauty <var>12</var>) and <var>\{2, 5, 2, 5\}</var> (with beauty <var>14</var>).

Sample Input 2

8 4
9 1 8 2 7 5 6 4

Sample Output 2

32

int solution(void) {
  int n;
  int k;
  int count = 0;
  scanf("%d%d", &n, &k);
  long long a[n];
  long long b[n * (n + 1) / 2];
  long long ans = 0;
  long long max = 0;
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
  }
  for (int i = 0; i < n; i++) {
    long long sum = 0;
    for (int j = i; j < n; j++) {
      sum += a[j];
      b[count] = sum;
      if (b[count] > max) {
        max = b[count];
      }
      count++;
    }
  }

  int count2 = 0;
  int p = 0;
  for (p = 0; pow(2, p) < max; p++) {
  }
  p--;

  for (int i = p; i >= 0; i--) {
    count2 = 0;
    for (int j = 0; j < count; j++) {
      if (b[j] >= pow(2, i)) {
        count2++;
      }
    }
    if (count2 >= k) {
      ans += pow(2, i);
      for (int j = 0; j < count; j++) {
        if (b[j] < pow(2, i)) {
          b[j] = 0;
        } else {
          b[j] -= pow(2, i);
        }
      }
    } else {
      for (int j = 0; j < count; j++) {
        if (b[j] < pow(2, i)) {
        } else {
          b[j] -= pow(2, i);
        }
      }
    }
  }
  printf("%lld\n", ans);
  return 0;
}

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let k: usize = s.next().unwrap().parse().unwrap();
    let a: Vec<u64> = vec![0]
        .into_iter()
        .chain(s.map(|a| a.parse::<u64>().unwrap()))
        .scan(0, |s, a| {
            *s += a;
            Some(*s)
        })
        .collect();
    let mut a: Vec<u64> = (0..n)
        .flat_map(|i| (i + 1..n + 1).map(move |j| (i, j)))
        .map(|(i, j)| a[j] - a[i])
        .collect();
    a.sort_by_key(|a| std::u64::MAX - a);
    let msb = 63 - a[0].leading_zeros();
    let mut ans: u64 = 0;
    let mut g: std::collections::BTreeSet<_> = (0..a.len()).collect();
    for bit in (0..msb + 1).rev() {
        let index: std::collections::BTreeSet<_> = g
            .iter()
            .filter(|&&i| a[i] & (1 << bit) != 0)
            .copied()
            .collect();
        if index.len() >= k {
            g = g.intersection(&index).cloned().collect();
            ans |= 1 << bit;
        }
    }
    println!("{}", ans);
}


Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog. Sheep and dogs always stay in place, but wolves can roam freely around the pasture, by repeatedly moving to the left, right, up or down to a neighboring cell. When a wolf enters a cell with a sheep, it consumes it. However, no wolf can enter a cell with a dog.Initially there are no dogs. Place dogs onto the pasture in such a way that no wolf can reach any sheep, or determine that it is impossible. Note that since you have many dogs, you do not need to minimize their number.

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

    let mut it = input.split_whitespace();

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

    let mut grid = Vec::with_capacity(r * c);

    for l in it.take(r) {
        for c in l.chars() {
            let x = match c {
                'S' => Cell::Sheep,
                'W' => Cell::Wolf,
                '.' => Cell::Empty,
                _ => panic!("Invalid input"),
            };
            grid.push(x);
        }
    }

    let no = || {
        println!("No");
        std::process::exit(0);
    };

    for (i, cell) in grid.iter().enumerate() {
        if let Cell::Sheep = *cell {
            let right = i + 1;
            match grid.get(right) {
                Some(Cell::Wolf) if right % c != 0 => no(),
                _ => (),
            }

            if c <= i {
                let up = i - c;
                if let Some(Cell::Wolf) = grid.get(up) {
                    no()
                }
            }

            if 0 < i {
                let left = i - 1;
                match grid.get(left) {
                    Some(Cell::Wolf) if left % c != c - 1 => no(),
                    _ => (),
                }
            }

            let down = i + c;
            if let Some(Cell::Wolf) = grid.get(down) {
                no()
            }
        }
    }

    println!("YES");

    let mut grid_str = String::with_capacity(r * (c + 1));

    for r in 0..r {
        for ci in 0..c {
            let i = r * c + ci;
            let x = match grid[i] {
                Cell::Sheep => 'S',
                Cell::Wolf => 'W',
                Cell::Empty => 'D',
            };
            grid_str.push(x);
        }
        grid_str.push('\n');
    }
    println!("{}", grid_str);
}


Score : <var>400</var> points

Problem Statement

We have a grid with <var>H</var> rows and <var>W</var> columns. The square at the <var>i</var>-th row and the <var>j</var>-th column will be called Square <var>(i,j)</var>.

The integers from <var>1</var> through <var>H×W</var> are written throughout the grid, and the integer written in Square <var>(i,j)</var> is <var>A_{i,j}</var>.

You, a magical girl, can teleport a piece placed on Square <var>(i,j)</var> to Square <var>(x,y)</var> by consuming <var>|x-i|+|y-j|</var> magic points.

You now have to take <var>Q</var> practical tests of your ability as a magical girl.

The <var>i</var>-th test will be conducted as follows:

Initially, a piece is placed on the square where the integer <var>L_i</var> is written.

Let <var>x</var> be the integer written in the square occupied by the piece. Repeatedly move the piece to the square where the integer <var>x+D</var> is written, as long as <var>x</var> is not <var>R_i</var>. The test ends when <var>x=R_i</var>.

Here, it is guaranteed that <var>R_i-L_i</var> is a multiple of <var>D</var>.

For each test, find the sum of magic points consumed during that test.

Constraints

<var>1 \leq H,W \leq 300</var>

<var>1 \leq D \leq H×W</var>

<var>1 \leq A_{i,j} \leq H×W</var>

<var>A_{i,j} \neq A_{x,y} ((i,j) \neq (x,y))</var>

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

<var>1 \leq L_i \leq R_i \leq H×W</var>

<var>(R_i-L_i)</var> is a multiple of <var>D</var>.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>D</var>
<var>A_{1,1}</var> <var>A_{1,2}</var> <var>...</var> <var>A_{1,W}</var>
<var>:</var>
<var>A_{H,1}</var> <var>A_{H,2}</var> <var>...</var> <var>A_{H,W}</var>
<var>Q</var>
<var>L_1</var> <var>R_1</var>
<var>:</var>
<var>L_Q</var> <var>R_Q</var>

Output

For each test, print the sum of magic points consumed during that test.

Output should be in the order the tests are conducted.

Sample Input 1

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

Sample Output 1

5

<var>4</var> is written in Square <var>(1,2)</var>.

<var>6</var> is written in Square <var>(3,3)</var>.

<var>8</var> is written in Square <var>(3,1)</var>.

Thus, the sum of magic points consumed during the first test is <var>(|3-1|+|3-2|)+(|3-3|+|1-3|)=5</var>.

Sample Input 2

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

Sample Output 2

0
0

Note that there may be a test where the piece is not moved at all, and there may be multiple identical tests.

Sample Input 3

5 5 4
13 25 7 15 17
16 22 20 2 9
14 11 12 1 19
10 6 23 8 18
3 21 5 24 4
3
13 13
2 10
13 13

Sample Output 3

0
5
0

int solution(void) {

  long h;
  long w;
  long d;
  long q;
  scanf("%ld %ld %ld", &h, &w, &d);
  long a[h][w];
  for (long i = 0; i < h; i++) {
    for (long j = 0; j < w; j++) {
      scanf("%ld", &a[i][j]);
    }
  }
  scanf("%ld", &q);
  long l[q];
  long r[q];
  for (int i = 0; i < q; i++) {
    scanf("%ld %ld", &l[i], &r[i]);
  }
  long x[(h * w) + 1];
  long y[(h * w) + 1];
  for (long i = 0; i < h; i++) {
    for (long j = 0; j < w; j++) {
      x[a[i][j]] = i;
      y[a[i][j]] = j;
    }
  }
  long magic[(h * w) + 1];
  for (long i = 1; i <= d; i++) {
    magic[i] = 0;
  }
  for (long i = d + 1; i <= h * w; i++) {
    magic[i] = magic[i - d] + labs(x[i] - x[i - d]) + labs(y[i] - y[i - d]);
  }
  for (long i = 0; i < q; i++) {
    printf("%ld\n", magic[r[i]] - magic[l[i]]);
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let h: usize = iter.next().unwrap().parse().unwrap();
    let w: usize = iter.next().unwrap().parse().unwrap();
    let d: usize = iter.next().unwrap().parse().unwrap();
    let mut pos = vec![(0, 0); h * w].into_boxed_slice();
    for i in 0..h {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        for j in 0..w {
            let num = iter.next().unwrap().parse::<usize>().unwrap();
            pos[num - 1] = (j as i64, i as i64);
        }
    }
    let mut costs = vec![0; h * w].into_boxed_slice();
    for i in d..(h * w) {
        costs[i] = costs[i - d] + (pos[i].0 - pos[i - d].0).abs() + (pos[i].1 - pos[i - d].1).abs();
    }
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let q = buf.trim().parse::<usize>().unwrap();
    for _ in 0..q {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        let l = iter.next().unwrap().parse::<usize>().unwrap();
        let r = iter.next().unwrap().parse::<usize>().unwrap();
        println!("{}", costs[r - 1] - costs[l - 1]);
    }
}


Screen resolution of Polycarp's monitor is $$$a \times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \le x < a, 0 \le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows — from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

int solution() {
  int tc;
  int area1 = 0;
  int area2 = 0;
  int i;
  scanf("%d", &tc);
  int input[tc][4];
  for (i = 0; i < tc; i++) {
    scanf("%d", &input[i][0]);
    scanf("%d", &input[i][1]);
    scanf("%d", &input[i][2]);
    scanf("%d", &input[i][3]);
  }
  for (i = 0; i < tc; i++) {
    area1 = input[i][0] * (input[i][1] - input[i][3] - 1);
    area2 = input[i][0] * input[i][3];
    if (area2 > area1) {
      area1 = area2;
    }
    area2 = (input[i][0] - input[i][2] - 1) * input[i][1];
    if (area2 > area1) {
      area1 = area2;
    }
    area2 = input[i][2] * input[i][1];
    if (area2 > area1) {
      area1 = area2;
    }
    input[i][0] = area1;
  }
  for (i = 0; i < tc; i++) {
    printf("%d\n", input[i][0]);
  }
  return 0;
}

fn solution() {
    let t = {
        let mut buf = String::new();
        stdin().read_line(&mut buf).expect("Failed to read line");
        buf.trim().parse::<i32>().unwrap()
    };
    for _ in 0..t {
        let (a, b, x, y) = {
            let mut buf = String::new();
            stdin().read_line(&mut buf).expect("Failed to read");
            let nums: Vec<i32> = buf
                .trim()
                .split_ascii_whitespace()
                .map(|c| c.parse().unwrap())
                .collect();
            (nums[0], nums[1], nums[2], nums[3])
        };
        println!("{}", max(a * max(y, b - y - 1), max(x, a - x - 1) * b));
    }
}


Score : <var>200</var> points

Problem Statement

A shop sells <var>N</var> kinds of fruits, Fruit <var>1, \ldots, N</var>, at prices of <var>p_1, \ldots, p_N</var> yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose <var>K</var> kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>p_1</var> <var>p_2</var> <var>\ldots</var> <var>p_N</var>

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit <var>1</var>, <var>2</var>, <var>3</var>, <var>4</var>, and <var>5</var> for <var>50</var> yen, <var>100</var> yen, <var>80</var> yen, <var>120</var> yen, and <var>80</var> yen, respectively.

The minimum total price for three kinds of fruits is <var>50 + 80 + 80 = 210</var> yen when choosing Fruit <var>1</var>, <var>3</var>, and <var>5</var>.

Sample Input 2

1 1
1000

Sample Output 2

1000

int solution(void) {
  int n = 0;
  int k = 0;

  int p[1005] = {0};

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

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

  int min = 10000;
  int result = 0;
  int num = 0;
  for (int i = 0; i < k; i++) {
    min = 10000;
    for (int j = 0; j < n; j++) {
      if (p[j] < min && p[j] > 0) {
        min = p[j];
        num = j;
      }
    }
    p[num] = 0;
    result += min;
  }

  printf("%d", result);

  return 0;
}

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    let mut itr = is.split_whitespace().map(|e| e.parse().unwrap());
    let _n: usize = itr.next().unwrap();
    let k: usize = itr.next().unwrap();
    is.clear();
    stdin().read_line(&mut is).ok();
    let mut a = is
        .split_whitespace()
        .map(|e| e.parse::<usize>().unwrap())
        .collect::<Vec<_>>();
    a.sort();

    println!("{}", a.iter().take(k).sum::<usize>());
}


Score : <var>200</var> points

Problem Statement

Joisino is about to compete in the final round of a certain programming competition.
In this contest, there are <var>N</var> problems, numbered <var>1</var> through <var>N</var>.
Joisino knows that it takes her <var>T_i</var> seconds to solve problem <var>i(1≦i≦N)</var>.

Also, there are <var>M</var> kinds of drinks offered to the contestants, numbered <var>1</var> through <var>M</var>.
If Joisino takes drink <var>i(1≦i≦M)</var>, her brain will be stimulated and the time it takes for her to solve problem <var>P_i</var> will become <var>X_i</var> seconds.
It does not affect the time to solve the other problems.

A contestant is allowed to take exactly one of the drinks before the start of the contest.
For each drink, Joisino wants to know how many seconds it takes her to solve all the problems if she takes that drink.
Here, assume that the time it takes her to solve all the problems is equal to the sum of the time it takes for her to solve individual problems.
Your task is to write a program to calculate it instead of her.

Constraints

All input values are integers.

<var>1≦N≦100</var>

<var>1≦T_i≦10^5</var>

<var>1≦M≦100</var>

<var>1≦P_i≦N</var>

<var>1≦X_i≦10^5</var>

Input

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

<var>N</var>
<var>T_1</var> <var>T_2</var> <var>...</var> <var>T_N</var>
<var>M</var>
<var>P_1</var> <var>X_1</var>
<var>P_2</var> <var>X_2</var>
<var>:</var>
<var>P_M</var> <var>X_M</var>

Output

For each drink, calculate how many seconds it takes Joisino to solve all the problems if she takes that drink, and print the results, one per line.

Sample Input 1

3
2 1 4
2
1 1
2 3

Sample Output 1

6
9

If Joisino takes drink <var>1</var>, the time it takes her to solve each problem will be <var>1</var>, <var>1</var> and <var>4</var> seconds, respectively, totaling <var>6</var> seconds.

If Joisino takes drink <var>2</var>, the time it takes her to solve each problem will be <var>2</var>, <var>3</var> and <var>4</var> seconds, respectively, totaling <var>9</var> seconds.

Sample Input 2

5
7 2 3 8 5
3
4 2
1 7
4 13

Sample Output 2

19
25
30

int solution(void) {
  int n = 0;
  int m = 0;
  int t[110];
  int p = 0;
  int x = 0;
  int sum = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &t[i]);
    sum += t[i];
  }

  scanf("%d", &m);
  for (int i = 0; i < m; i++) {
    scanf("%d%d", &p, &x);
    printf("%d\n", sum - t[p - 1] + x);
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let _n: usize = s.trim().parse().unwrap();
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let t: Vec<usize> = s.split_whitespace().map(|e| e.parse().unwrap()).collect();
    let tot: usize = t.iter().sum();
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let m: usize = s.trim().parse().unwrap();
    for _ in 0..m {
        let mut s = String::new();
        stdin().read_line(&mut s).ok();
        let mut itr = s.split_whitespace().map(|e| e.parse().unwrap());
        let p: usize = itr.next().unwrap();
        let x: usize = itr.next().unwrap();

        println!("{}", tot + x - t[p - 1]);
    }
}


There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. n particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the distance in meters from the center of the collider, xi is the coordinate of the i-th particle and its position in the collider at the same time. All coordinates of particle positions are even integers.You know the direction of each particle movement — it will move to the right or to the left after the collider's launch start. All particles begin to move simultaneously at the time of the collider's launch start. Each particle will move straight to the left or straight to the right with the constant speed of 1 meter per microsecond. The collider is big enough so particles can not leave it in the foreseeable time.Write the program which finds the moment of the first collision of any two particles of the collider. In other words, find the number of microseconds before the first moment when any two particles are at the same point.

fn solution() {
    let cin = stdin();

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

    line.clear();
    cin.read_line(&mut line).unwrap();
    let dir = line.trim().as_bytes();

    let mut ans = i64::max_value();
    let mut last_r = -1;

    for (i, result) in cin.lock().split(b' ').enumerate() {
        let x = i64::from_str(str::from_utf8(result.unwrap().as_slice()).unwrap().trim()).unwrap();
        if dir[i] as char == 'L' && last_r != -1 {
            ans = min(ans, x - last_r);
        }
        if dir[i] as char == 'R' {
            last_r = x;
        }
    }

    println!("{}", if ans == i64::max_value() { -1 } else { ans / 2 });
}


Score : <var>100</var> points

Problem Statement

We have a sandglass that runs for <var>X</var> seconds. The sand drops from the upper bulb at a rate of <var>1</var> gram per second. That is, the upper bulb initially contains <var>X</var> grams of sand.

How many grams of sand will the upper bulb contains after <var>t</var> seconds?

Constraints

<var>1≤X≤10^9</var>

<var>1≤t≤10^9</var>

<var>X</var> and <var>t</var> are integers.

Input

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

<var>X</var> <var>t</var>

Output

Print the number of sand in the upper bulb after <var>t</var> second.

Sample Input 1

100 17

Sample Output 1

83

<var>17</var> out of the initial <var>100</var> grams of sand will be consumed, resulting in <var>83</var> grams.

Sample Input 2

48 58

Sample Output 2

0

All <var>48</var> grams of sand will be gone, resulting in <var>0</var> grams.

Sample Input 3

1000000000 1000000000

Sample Output 3

0

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let v: Vec<i32> = s
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect();
    let X = v[0];
    let t = v[1];
    println!("{}", std::cmp::max(X - t, 0));
}


Score : <var>100</var> points

Problem Statement

Smeke has decided to participate in AtCoder Beginner Contest (ABC) if his current rating is less than <var>1200</var>, and participate in AtCoder Regular Contest (ARC) otherwise.

You are given Smeke's current rating, <var>x</var>. Print ABC if Smeke will participate in ABC, and print ARC otherwise.

Constraints

<var>1 ≦ x ≦ 3{,}000</var>

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

Input

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

<var>x</var>

Output

Print the answer.

Sample Input 1

1000

Sample Output 1

ABC

Smeke's current rating is less than <var>1200</var>, thus the output should be ABC.

Sample Input 2

2000

Sample Output 2

ARC

Smeke's current rating is not less than <var>1200</var>, thus the output should be ARC.

int solution(void) {
  int num = 0;

  scanf("%d", &num);
  if (num >= 1200) {
    printf("ARC\n");
  } else {
    printf("ABC\n");
  }
}

fn solution() {
    let scan = std::io::stdin();
    let mut line = String::new();
    let _ = scan.read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();
    let x: u32 = vec[0].parse().unwrap_or(0);
    if x < 1200 {
        println!("ABC");
    } else {
        println!("ARC");
    }
}


Fibonacci Number

  Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:

\begin{equation*}
fib(n)= \left \{
\begin{array}{ll}
1　         &   (n = 0)          \\
1　         &  (n = 1) \\
fib(n - 1) + fib(n - 2)  & \\
\end{array}
\right.
\end{equation*}

Input

  An integer $n$ is given.

output

  Print the $n$-th fibonacci number in a line.

Constraints

$0 \leq n \leq 44$

Sample Input 1

3

Sample Output 1

3

int solution(void) {
  int a = 0;
  scanf("%d", &a);
  if (a == 0 || a == 1) {
    printf("1\n");
    return 0;
  }
  int i = 0;
  int m = 1;
  int n = 1;
  int ch = 0;
  for (i = 0; i < a - 1; i++) {
    n += m;
    ch = m;
    m = n;
    n = ch;
  }
  printf("%d\n", m);
  return 0;
}

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

    let mut fib = vec![1, 1];

    while fib.len() < n + 1 {
        let f1 = fib[fib.len() - 1];
        let f2 = fib[fib.len() - 2];
        fib.push(f1 + f2);
    }
    println!("{}", fib[n]);
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.)
The state of each piece is represented by a string <var>S</var> of length <var>N</var>.
If <var>S_i=</var>B, the <var>i</var>-th piece from the left is showing black;
If <var>S_i=</var>W, the <var>i</var>-th piece from the left is showing white.

Consider performing the following operation:

Choose <var>i</var> (<var>1 \leq i < N</var>) such that the <var>i</var>-th piece from the left is showing black and the <var>(i+1)</var>-th piece from the left is showing white, then flip both of those pieces. That is, the <var>i</var>-th piece from the left is now showing white and the <var>(i+1)</var>-th piece from the left is now showing black.

Find the maximum possible number of times this operation can be performed.

Constraints

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

<var>S_i=</var>B or W

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the maximum possible number of times the operation can be performed.

Sample Input 1

BBW

Sample Output 1

2

The operation can be performed twice, as follows:

Flip the second and third pieces from the left.

Flip the first and second pieces from the left.

Sample Input 2

BWBWBW

Sample Output 2

6

int solution(void) {
  char s[200000 + 1] = {'\0'};
  long cnt_turn = 0;
  long num_b = 0;
  char *sp = &s[0];

  scanf("%s", sp);

  while (*sp != '\0') {
    if (*sp == 'B') {
      num_b++;
    }
    if (*sp == 'W') {
      cnt_turn += num_b;
    }
    sp++;
  }

  printf("%ld\n", cnt_turn);

  return 0;
}

fn solution() {
    let s = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        s.trim_end().to_owned()
    };
    println!(
        "{}",
        s.chars()
            .skip_while(|&c| c == 'W')
            .enumerate()
            .fold((0, 0), |(n, mut state), (i, c)| if c == 'B' {
                (n, state)
            } else {
                state += i - n;
                (n + 1, state)
            })
            .1
    )
}


Score : <var>600</var> points

Problem Statement

Given is an integer sequence of length <var>N+1</var>: <var>A_0, A_1, A_2, \ldots, A_N</var>. Is there a binary tree of depth <var>N</var> such that, for each <var>d = 0, 1, \ldots, N</var>, there are exactly <var>A_d</var> leaves at depth <var>d</var>? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print <var>-1</var>.

Notes

A binary tree is a rooted tree such that each vertex has at most two direct children.

A leaf in a binary tree is a vertex with zero children.

The depth of a vertex <var>v</var> in a binary tree is the distance from the tree's root to <var>v</var>. (The root has the depth of <var>0</var>.)

The depth of a binary tree is the maximum depth of a vertex in the tree.

Constraints

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

<var>0 \leq A_i \leq 10^{8}</var> (<var>0 \leq i \leq N</var>)

<var>A_N \geq 1</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_0</var> <var>A_1</var> <var>A_2</var> <var>\cdots</var> <var>A_N</var>

Output

Print the answer as an integer.

Sample Input 1

3
0 1 1 2

Sample Output 1

7

Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print <var>7</var>.

Sample Input 2

4
0 0 1 0 2

Sample Output 2

10

Sample Input 3

2
0 3 1

Sample Output 3

-1

Sample Input 4

1
1 1

Sample Output 4

-1

Sample Input 5

10
0 0 1 1 2 3 5 8 13 21 34

Sample Output 5

264

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

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

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

    let mut ans = 0;
    let mut now = 1;
    for i in 0..n + 1 {
        if a[i] > now {
            println!("-1");
            return;
        }
        ans += now;

        let eda_max = (now - a[i]) << 1;

        let eda_min = s[i] - a[i];
        now = std::cmp::min(eda_max, eda_min);
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

You are given an integer <var>N</var>. Consider an infinite <var>N</var>-ary tree as shown below:

Figure: an infinite <var>N</var>-ary tree for the case <var>N = 3</var>

As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index <var>1</var>. For the remaining vertices, vertices in the upper row have smaller indices than those in the lower row. Among the vertices in the same row, a vertex that is more to the left has a smaller index.

Regarding this tree, process <var>Q</var> queries. The <var>i</var>-th query is as follows:

Find the index of the lowest common ancestor (see Notes) of Vertex <var>v_i</var> and <var>w_i</var>.

Notes

In a rooted tree, the lowest common ancestor (LCA) of Vertex <var>v</var> and <var>w</var> is the farthest vertex from the root that is an ancestor of both Vertex <var>v</var> and <var>w</var>. Here, a vertex is considered to be an ancestor of itself. For example, in the tree shown in Problem Statement, the LCA of Vertex <var>5</var> and <var>7</var> is Vertex <var>2</var>, the LCA of Vertex <var>8</var> and <var>11</var> is Vertex <var>1</var>, and the LCA of Vertex <var>3</var> and <var>9</var> is Vertex <var>3</var>.

Constraints

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

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

<var>1 ≤ v_i < w_i ≤ 10^9</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>Q</var>
<var>v_1</var> <var>w_1</var>
<var>:</var>
<var>v_Q</var> <var>w_Q</var>

Output

Print <var>Q</var> lines. The <var>i</var>-th line <var>(1 ≤ i ≤ Q)</var> must contain the index of the lowest common ancestor of Vertex <var>v_i</var> and <var>w_i</var>.

Sample Input 1

3 3
5 7
8 11
3 9

Sample Output 1

2
1
3

The queries in this case correspond to the examples shown in Notes.

Sample Input 2

100000 2
1 2
3 4

Sample Output 2

1
1

int solution() {
  int n;
  int q;
  scanf("%d %d", &n, &q);
  while (q--) {
    int t1;
    int t2;
    int i;
    scanf("%d %d", &t1, &t2);
    if (n == 1) {
      printf("%d\n", t1 > t2 ? t2 : t1);
      continue;
    }
    while (t1 != t2) {
      if (t1 > t2) {
        t1 = (t1 - 2) / n + 1;
      } else {
        t2 = (t2 - 2) / n + 1;
      }
    }
    printf("%d\n", t1);
  }
  return 0;
}

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

    let mut out = Vec::new();
    for _ in 0..q {
        let mut v = itr.next().unwrap().parse::<u64>().unwrap() - 1;
        let mut w = itr.next().unwrap().parse::<u64>().unwrap() - 1;
        if n == 1 {
            writeln!(out, "{}", v + 1).ok();
            continue;
        }
        while v != w {
            while v > w {
                v = (v - 1) / n;
            }
            while w > v {
                w = (w - 1) / n;
            }
        }
        writeln!(out, "{}", v + 1).ok();
    }
    stdout().write_all(&out).unwrap();
}


Score : <var>100</var> points

Problem Statement

Given is a lowercase English letter <var>C</var> that is not z. Print the letter that follows <var>C</var> in alphabetical order.

Constraints

<var>C</var> is a lowercase English letter that is not z.

Input

Input is given from Standard Input in the following format:

<var>C</var>

Output

Print the letter that follows <var>C</var> in alphabetical order.

Sample Input 1

a

Sample Output 1

b

a is followed by b.

Sample Input 2

y

Sample Output 2

z

y is followed by z.

fn solution() {
    let mut x = String::new();
    io::stdin().read_line(&mut x).unwrap();
    let x = x.trim().chars().next().unwrap();
    println!("{}", (x as u8 + 1) as char);
}


Score : <var>300</var> points

Problem Statement

<var>N</var> persons are standing in a row. The height of the <var>i</var>-th person from the front is <var>A_i</var>.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>\ldots</var> <var>A_N</var>

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights <var>0</var>, <var>1</var>, <var>0</var>, <var>1</var>, and <var>2</var>, respectively, their heights will be <var>2</var>, <var>2</var>, <var>5</var>, <var>5</var>, and <var>5</var>, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height <var>0</var> to everyone will work.

int solution(void) {
  int n = 0;
  int a = 0;
  int amin = 0;
  long int count = 0;

  scanf("%d", &n);
  while (n--) {
    scanf("%d", &a);
    if (a > amin) {
      amin = a;
    } else {
      count += amin - a;
    }
  }
  printf("%ld\n", count);
  return 0;
}

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

    io::stdin().read_line(&mut n).expect("Required Input");

    let _n: i128 = n.trim().parse().unwrap();

    let mut stol_height: i128 = 0;
    let mut input: String = String::new();
    let mut prev_height: i128 = 0;

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

    let values: Vec<i128> = input
        .split_whitespace()
        .map(|x| x.parse::<i128>())
        .collect::<Result<Vec<i128>, _>>()
        .unwrap();

    for i in values.iter() {
        if prev_height <= *i {
            prev_height = max(prev_height, *i);
            continue;
        }

        stol_height += prev_height - *i;
    }

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


Score : <var>200</var> points

Problem Statement

Katsusando loves omelette rice.

Besides, he loves crème brûlée, tenderloin steak and so on, and believes that these foods are all loved by everyone.

To prove that hypothesis, he conducted a survey on <var>M</var> kinds of foods and asked <var>N</var> people whether they like these foods or not.

The <var>i</var>-th person answered that he/she only likes the <var>A_{i1}</var>-th, <var>A_{i2}</var>-th, <var>...</var>, <var>A_{iK_i}</var>-th food.

Find the number of the foods liked by all the <var>N</var> people.

Constraints

All values in input are integers.

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

<var>1 \leq K_i \leq M</var>

<var>1 \leq A_{ij} \leq M</var>

For each <var>i</var> <var>(1 \leq i \leq N)</var>, <var>A_{i1}, A_{i2}, ..., A_{iK_i}</var> are distinct.

Constraints

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>K_1</var> <var>A_{11}</var> <var>A_{12}</var> <var>...</var> <var>A_{1K_1}</var>
<var>K_2</var> <var>A_{21}</var> <var>A_{22}</var> <var>...</var> <var>A_{2K_2}</var>
<var>:</var>
<var>K_N</var> <var>A_{N1}</var> <var>A_{N2}</var> <var>...</var> <var>A_{NK_N}</var>

Output

Print the number of the foods liked by all the <var>N</var> people.

Sample Input 1

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

Sample Output 1

1

As only the third food is liked by all the three people, <var>1</var> should be printed.

Sample Input 2

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

Sample Output 2

0

Katsusando's hypothesis turned out to be wrong.

Sample Input 3

1 30
3 5 10 30

Sample Output 3

3

int solution(void) {
  int N = 0;
  int M = 0;
  int cntM[31] = {0};
  int num = 0;
  int temp = 0;
  int suki = 0;

  scanf("%d %d", &N, &M);

  for (int cnt = 0; cnt < N; cnt++) {
    scanf("%d", &num);
    for (int cnt_num = 0; cnt_num < num; cnt_num++) {
      scanf("%d", &temp);
      cntM[temp]++;
    }
  }

  for (int cnt = 1; cnt <= M; cnt++) {
    if (cntM[cnt] == N) {
      suki++;
    }
  }
  printf("%d\n", suki);
  return 0;
}

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

    let mut iter = buf.lines();
    iter.next();

    let mut hm = HashMap::new();
    let mut count = 0;

    for l in iter {
        count += 1;
        let mut es = l.split_whitespace();
        es.next();
        for e in es {
            let mut val = 1;
            if let Some(&v) = hm.get(e) {
                val += v;
            }
            hm.insert(e, val);
        }
    }

    println!("{}", hm.values().filter(|&&v| v == count).count());
}


Since the giant heads have appeared in the sky all humanity is in danger, so all Ricks and Mortys from all parallel universes are gathering in groups to find a solution to get rid of them. There are n parallel universes participating in this event (n Ricks and n Mortys). I. e. each of n universes has one Rick and one Morty. They're gathering in m groups. Each person can be in many groups and a group can contain an arbitrary number of members.Ricks and Mortys have registered online in these groups. So, a person can have joined a group more than once (developer of this website hadn't considered this possibility).  Summer from universe #1 knows that in each parallel universe (including hers) exactly one of Rick and Morty from that universe is a traitor and is loyal, but no one knows which one. She knows that we are doomed if there's a group such that every member in that group is a traitor (they will plan and destroy the world). Summer knows that if there's a possibility that world ends (there's a group where all members are traitors) she should immediately cancel this event. So she wants to know if she should cancel the event. You have to tell her yes if and only if there's at least one scenario (among all 2n possible scenarios, 2 possible scenarios for who a traitor in each universe) such that in that scenario the world will end.

int solution() {
  int n;
  int m;
  scanf("%d %d", &n, &m);
  int t[m];
  for (int i = 0; i < m; i++) {
    t[i] = 0;
  }
  for (int i = 0; i < m; i++) {
    int c;
    scanf("%d", &c);
    int s[c];
    for (int j = 0; j < c; j++) {
      scanf("%d", &s[j]);
    }
    for (int j = 0; j < c; j++) {
      for (int k = j + 1; k < c; k++) {
        if (s[j] == -s[k]) {
          t[i] = 1;
        }
      }
    }
  }
  for (int i = 0; i < m; i++) {
    if (t[i] != 1) {
      printf("YES");
      return 0;
    }
  }
  printf("NO");
  return 0;
}

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

    let io = stdin();
    let mut io = io.lock().lines().map(|x| x.unwrap());

    let nm = io.next().unwrap();
    let mut nm = nm.split_whitespace();
    let n = nm.next().unwrap().parse::<usize>().unwrap();
    let m = nm.next().unwrap().parse::<usize>().unwrap();
    for _ in 0..m {
        let mut chk = vec![0; n + 1];
        let line = io.next().unwrap();
        let mut line = line.split_whitespace();
        let k = line.next().unwrap().parse::<usize>().unwrap();
        let mut possible_ruin = true;
        for _ in 0..k {
            let a = line.next().unwrap().parse::<isize>().unwrap();
            let b = a.unsigned_abs();
            chk[b] |= if a > 0 { 1 } else { 2 };
            if chk[b] == 3 {
                possible_ruin = false;
                break;
            }
        }
        if possible_ruin {
            println!("YES");
            return;
        }
    }
    println!("NO");
}


Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer $$$x$$$ as nearly prime if it can be represented as $$$p \cdot q$$$, where $$$1 < p < q$$$ and $$$p$$$ and $$$q$$$ are prime numbers. For example, integers $$$6$$$ and $$$10$$$ are nearly primes (since $$$2 \cdot 3 = 6$$$ and $$$2 \cdot 5 = 10$$$), but integers $$$1$$$, $$$3$$$, $$$4$$$, $$$16$$$, $$$17$$$ or $$$44$$$ are not.Captain Flint guessed an integer $$$n$$$ and asked you: can you represent it as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them should be nearly prime.Uncle Bogdan easily solved the task and joined the crew. Can you do the same?

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

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

        if n < 31 {
            println!("NO");
        } else if n == 36 || n == 40 || n == 44 {
            println!("YES");
            println!("6 10 15 {}", n - 31);
        } else {
            println!("YES");
            println!("6 10 14 {}", n - 30);
        }
    }
}


Score : <var>100</var> points

Problem Statement

AtCoDeer the deer recently bought three paint cans.
The color of the one he bought two days ago is <var>a</var>, the color of the one he bought yesterday is <var>b</var>, and the color of the one he bought today is <var>c</var>.
Here, the color of each paint can is represented by an integer between <var>1</var> and <var>100</var>, inclusive.

Since he is forgetful, he might have bought more than one paint can in the same color.
Count the number of different kinds of colors of these paint cans and tell him.

Constraints

<var>1≦a,b,c≦100</var>

Input

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

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

Output

Print the number of different kinds of colors of the paint cans.

Sample Input 1

3 1 4

Sample Output 1

3

Three different colors: <var>1</var>, <var>3</var>, and <var>4</var>.

Sample Input 2

3 3 33

Sample Output 2

2

Two different colors: <var>3</var> and <var>33</var>.

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let set: HashSet<usize> = s.split_whitespace().map(|e| e.parse().unwrap()).collect();

    println!("{}", set.len());
}


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

int solution() {
  int n = 0;
  int m = 0;
  while (scanf("%d %d", &n, &m) != EOF) {

    getchar();
    char a[55][55];
    memset(a, 0, sizeof(a));
    int Lup = 55;
    int Ldown = 0;
    int Cleft = 55;
    int Cright = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        a[i][j] = getchar();
        if (a[i][j] == '*') {
          if (i < Lup) {
            Lup = i;
          }
          if (i > Ldown) {
            Ldown = i;
          }
          if (j < Cleft) {
            Cleft = j;
          }
          if (j > Cright) {
            Cright = j;
          }
        }
      }

      if (i < n - 1) {
        getchar();
      }
    }
    for (int i = Lup; i <= Ldown; i++) {
      for (int j = Cleft; j <= Cright; j++) {
        putchar(a[i][j]);
      }
      putchar('\n');
    }
  }
  return 0;
}

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

    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");

    let mut line_words = line.split_whitespace();
    let n: usize = line_words
        .next()
        .unwrap()
        .parse()
        .expect("Not n parameter was given");
    let m: usize = line_words
        .next()
        .unwrap()
        .parse()
        .expect("Not m parameter was given");
    let (mut x_min, mut x_max, mut y_min, mut y_max) = (m, 0, n, 0);
    let mut paper: Vec<String> = Vec::with_capacity(n);
    for i in 0..n {
        line.clear();
        io::stdin()
            .read_line(&mut line)
            .expect("Failed to read line");
        paper.push(line.trim().to_string());
        let (mut min, mut max) = (None, None);
        for (j, c) in line.chars().enumerate() {
            if c == '*' {
                if min.is_none() {
                    min = Some(j);
                }
                max = Some(j);
            }
        }
        if min.is_some() {
            x_min = cmp::min(x_min, min.unwrap());
            if y_min == n {
                y_min = i;
            }
            y_max = i;
        }
        if max.is_some() {
            x_max = cmp::max(x_max, max.unwrap());
        }
    }
    for i in y_min..y_max + 1 {
        println!("{}", paper[i].get(x_min..x_max + 1).unwrap());
    }
}


Score : <var>200</var> points

Problem Statement

Determine if an <var>N</var>-sided polygon (not necessarily convex) with sides of length <var>L_1, L_2, ..., L_N</var> can be drawn in a two-dimensional plane.

You can use the following theorem:

Theorem: an <var>N</var>-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths of the other <var>N-1</var> sides.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>L_1</var> <var>L_2</var> <var>...</var> <var>L_N</var>

Output

If an <var>N</var>-sided polygon satisfying the condition can be drawn, print Yes; otherwise, print No.

Sample Input 1

4
3 8 5 1

Sample Output 1

Yes

Since <var>8 < 9 = 3 + 5 + 1</var>, it follows from the theorem that such a polygon can be drawn on a plane.

Sample Input 2

4
3 8 4 1

Sample Output 2

No

Since <var>8 \geq 8 = 3 + 4 + 1</var>, it follows from the theorem that such a polygon cannot be drawn on a plane.

Sample Input 3

10
1 8 10 5 8 12 34 100 11 3

Sample Output 3

No

int solution(void) {
  int N = 0;
  int L[101];
  int max = 0;
  int sum = 0;
  scanf("%d", &N);
  for (int i = 0; i < N; i++) {
    scanf("%d", &L[i]);
    if (max < L[i]) {
      max = L[i];
    }
    sum += L[i];
  }
  if (max < sum - max) {
    printf("Yes\n");
  } else {
    printf("No\n");
  }
  return 0;
}

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

    let mut ls = String::new();
    stdin().read_line(&mut ls).unwrap();
    let ls: Vec<isize> = ls.split_whitespace().flat_map(str::parse).collect();
    let lngst = ls.clone().into_iter().max().unwrap();
    let mut v = -lngst;
    for l in ls.into_iter() {
        v += l;
        if v > lngst {
            println!("Yes");
            return;
        }
    }
    println!("No");
}


This is the easy version of this problem. In this version, we do not have queries. Note that we have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.An array $$$b$$$ of length $$$m$$$ is good if for all $$$i$$$ the $$$i$$$-th element is greater than or equal to $$$i$$$. In other words, $$$b$$$ is good if and only if $$$b_i \geq i$$$ for all $$$i$$$ ($$$1 \leq i \leq m$$$).You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find the number of pairs of indices $$$(l, r)$$$, where $$$1 \le l \le r \le n$$$, such that the array $$$[a_l, a_{l+1}, \ldots, a_r]$$$ is good.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int p = 1;
    scanf("%d", &n);
    int a[n];
    long long r = 1;
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    for (int k = 1; k < n; k++) {
      ++p;
      p = p > a[k] ? a[k] : p;
      r += p;
    }
    printf("%lld\n", r);
  }
  return 0;
}

fn solution() {
    let mut lines = io::stdin().lines();
    let n_cases: usize = lines.next().unwrap().unwrap().parse().unwrap();
    'cases: for _ in 0..n_cases {
        lines.next();
        let array = lines
            .next()
            .unwrap()
            .unwrap()
            .split_whitespace()
            .map(|token| token.parse::<usize>().unwrap() - 1)
            .collect::<Vec<usize>>();
        let mut starts = Vec::with_capacity(array.len() + 1);
        let mut ends = Vec::with_capacity(array.len() + 1);
        let mut start_idx = 0;
        let len = array.len();
        for (idx, value) in array.into_iter().enumerate() {
            let backward = idx.saturating_sub(value);
            if backward > start_idx {
                starts.push(start_idx);
                ends.push(idx);
                start_idx = backward;
            }
        }
        starts.push(start_idx);
        ends.push(len);
        starts.push(len);
        ends.push(len + 1);

        let mut sum = 0;

        for lol in starts
            .into_iter()
            .zip(ends.into_iter())
            .collect::<Vec<_>>()
            .windows(2)
        {
            let [x, y] = lol else { panic!() };
            let a = y.0 - x.0;
            let b = x.1 - x.0;
            sum += a * b - ((a * (a - 1)) / 2);
        }

        println!("{sum}");
    }
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> consisting of lowercase English letters.
We will write down this string, starting a new line after every <var>w</var> letters. Print the string obtained by concatenating the letters at the beginnings of these lines from top to bottom.

Constraints

<var>1 \leq w \leq |S| \leq 1000</var>

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

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

Input

Input is given from Standard Input in the following format:

<var>S</var>
<var>w</var>

Output

Print the desired string in one line.

Sample Input 1

abcdefgh
3

Sample Output 1

adg

When we write down abcdefgh, starting a new line after every three letters, we get the following:

abc

def

gh

Concatenating the letters at the beginnings of these lines, we obtain adg.

Sample Input 2

lllll
1

Sample Output 2

lllll

Sample Input 3

souuundhound
2

Sample Output 3

suudon

int solution(void) {
  char s[30000];
  int w;
  int i = 0;
  scanf("%s", s);
  scanf("%d", &w);
  while (1) {
    printf("%c", s[i]);
    i += w;
    if (s[i] == '\0') {
      break;
    }
  }
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut w = String::new();
    io::stdin().read_line(&mut w).unwrap();
    let w: usize = w.trim().parse().unwrap();
    let mut uu: Vec<u8> = Vec::new();
    for (i, c) in buf.trim().bytes().enumerate() {
        if i % w == 0 {
            uu.push(c);
        }
    }
    println!("{}", String::from_utf8_lossy(uu.as_slice()));
}


AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $$$a$$$ and $$$b$$$, both consist of $$$n$$$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):  She chooses two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), then decreases the $$$i$$$-th element of array $$$a$$$ by $$$1$$$, and increases the $$$j$$$-th element of array $$$a$$$ by $$$1$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index of array $$$a$$$ are $$$a_i - 1$$$ and $$$a_j + 1$$$, respectively. Each element of array $$$a$$$ must be non-negative after each operation. If $$$i = j$$$ this operation doesn't change the array $$$a$$$. AquaMoon wants to make some operations to make arrays $$$a$$$ and $$$b$$$ equal. Two arrays $$$a$$$ and $$$b$$$ are considered equal if and only if $$$a_i = b_i$$$ for all $$$1 \leq i \leq n$$$.Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays $$$a$$$ and $$$b$$$ equal.Please note, that you don't have to minimize the number of operations.

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

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

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

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

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

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

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

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

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

        a.extend(it);

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

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

        b.extend(it);

        let asum = a.iter().cloned().sum::<usize>();
        let bsum = b.iter().cloned().sum::<usize>();

        if asum != bsum {
            writeln!(&mut output, "-1").unwrap();
        } else {
            let mut ans = Vec::new();

            for i in 0..n {
                while a[i] < b[i] {
                    let j = (i + 1..).find(|&i| a[i] > b[i]).unwrap();

                    ans.push((j, i));
                    a[i] += 1;
                    a[j] -= 1;
                }
                while a[i] > b[i] {
                    let j = (i + 1..).find(|&i| a[i] < b[i]).unwrap();

                    ans.push((i, j));
                    a[i] -= 1;
                    a[j] += 1;
                }
            }

            writeln!(&mut output, "{}", ans.len()).unwrap();
            for (i, j) in ans {
                writeln!(&mut output, "{} {}", i + 1, j + 1).unwrap();
            }
        }
    }
}


You have a string $$$s$$$ and a chip, which you can place onto any character of this string. After placing the chip, you move it to the right several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $$$i$$$, you move it to the position $$$i + 1$$$. Of course, moving the chip to the right is impossible if it is already in the last position.After moving the chip to the right, you move it to the left several (maybe zero) times, i. e. you perform the following operation several times: if the current position of the chip is $$$i$$$, you move it to the position $$$i - 1$$$. Of course, moving the chip to the left is impossible if it is already in the first position.When you place a chip or move it, you write down the character where the chip ends up after your action. For example, if $$$s$$$ is abcdef, you place the chip onto the $$$3$$$-rd character, move it to the right $$$2$$$ times and then move it to the left $$$3$$$ times, you write down the string cdedcb.You are given two strings $$$s$$$ and $$$t$$$. Your task is to determine whether it's possible to perform the described operations with $$$s$$$ so that you write down the string $$$t$$$ as a result.

int solution() {
  int t;
  int s;
  int m;
  int n;
  int flag;
  char a[505];
  char b[10005];
  scanf("%d", &t);
  while (t--) {
    scanf("%s", a);
    scanf("%s", b);
    flag = 0;
    int i;
    int j;
    int k;
    int l1 = strlen(a);
    int l2 = strlen(b);
    for (i = 0; i < l1; i++) {
      if (b[0] == a[i]) {
        if (l2 == 1) {
          flag = 1;
        } else {
          for (j = i + 1, k = 1; j < l1 && k < l2; j++, k++) {
            if (b[k] != a[j]) {
              break;
            }
          }
          if (k >= l2) {
            flag = 1;
            break;
          }
          for (n = 1; n <= j - i + 1; n++) {
            for (m = j - n, s = k - n; j >= 0 && k < l2; m--, s++) {
              if (b[s] != a[m]) {
                break;
              }
            }
            if (s >= l2) {
              flag = 1;
              break;
            }
          }
          if (flag) {
            break;
          }
          for (j = i - 1, k = 1; j >= 0 && k < l2; j--, k++) {
            if (b[k] != a[j])
              break;
          }
          if (k >= l2)
            flag = 1;
        }
      }
    }
    if (flag) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

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

    let stdout = io::stdout();
    let handle = stdout.lock();
    let mut buffer = BufWriter::with_capacity(65536, handle);
    for _q in 0..q {
        line.clear();
        stdin.read_line(&mut line).unwrap();
        let s = line.trim().to_string();

        line.clear();
        stdin.read_line(&mut line).unwrap();
        let t = line.trim().to_string();

        let start_right = t.len() / 2;
        let find_string = |original_string: &str, string_to_find: &str| -> bool {
            for i in start_right..string_to_find.len() {
                let mut is_reversion_point = true;
                for (left, right) in string_to_find[..i]
                    .chars()
                    .rev()
                    .zip(string_to_find[(i + 1)..].chars())
                {
                    if left != right {
                        is_reversion_point = false;
                        break;
                    }
                }
                if is_reversion_point && original_string.contains(&string_to_find[..=i]) {
                    return true;
                }
            }
            false
        };

        let t_reversed: String = t.chars().rev().collect();
        if find_string(&s, &t) || find_string(&s, &t_reversed) {
            writeln!(&mut buffer, "YES").unwrap();
        } else {
            writeln!(&mut buffer, "NO").unwrap();
        }
    }
    buffer.flush().unwrap();
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> pieces of source code. The characteristics of the <var>i</var>-th code is represented by <var>M</var> integers <var>A_{i1}, A_{i2}, ..., A_{iM}</var>.

Additionally, you are given integers <var>B_1, B_2, ..., B_M</var> and <var>C</var>.

The <var>i</var>-th code correctly solves this problem if and only if <var>A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0</var>.

Among the <var>N</var> codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

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

<var>-100 \leq A_{ij} \leq 100</var>

<var>-100 \leq B_i \leq 100</var>

<var>-100 \leq C \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>C</var>
<var>B_1</var> <var>B_2</var> <var>...</var> <var>B_M</var>
<var>A_{11}</var> <var>A_{12}</var> <var>...</var> <var>A_{1M}</var>
<var>A_{21}</var> <var>A_{22}</var> <var>...</var> <var>A_{2M}</var>
<var>\vdots</var>
<var>A_{N1}</var> <var>A_{N2}</var> <var>...</var> <var>A_{NM}</var>

Output

Print the number of codes among the given <var>N</var> codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since <var>3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0</var>, the first code does not solve this problem.

<var>1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0</var>, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.

int solution() {
  int n = 0;
  int m = 0;
  int c = 0;
  scanf("%d %d %d\n", &n, &m, &c);
  int count = 0;
  int b[m];
  for (int i = 0; i < m; i++) {
    scanf("%d", b + i);
  }
  int buf = 0;
  int add = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      scanf("%d", &buf);
      add += buf * b[j];
    }
    add += c;
    if (add > 0) {
      count++;
    }
    add = 0;
  }
  printf("%d\n", count);
  return 0;
}

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

    println!(
        "{}",
        (0..n)
            .filter(|_| {
                let mut a = String::new();
                stdin().read_line(&mut a).unwrap();
                a.split_whitespace()
                    .flat_map(str::parse::<isize>)
                    .zip(b.iter())
                    .map(|(aa, &bb)| aa * bb)
                    .sum::<isize>()
                    > -c
            })
            .count()
    );
}


Score : <var>200</var> points

Problem Statement

When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.

You, the smartwatch, has found <var>N</var> routes to his home.

If Mr. X uses the <var>i</var>-th of these routes, he will get home in time <var>t_i</var> at cost <var>c_i</var>.

Find the smallest cost of a route that takes not longer than time <var>T</var>.

Constraints

All values in input are integers.

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

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

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

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

The pairs <var>(c_i, t_i)</var> are distinct.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>T</var>
<var>c_1</var> <var>t_1</var>
<var>c_2</var> <var>t_2</var>
<var>:</var>
<var>c_N</var> <var>t_N</var>

Output

Print the smallest cost of a route that takes not longer than time <var>T</var>.

If there is no route that takes not longer than time <var>T</var>, print TLE instead.

Sample Input 1

3 70
7 60
1 80
4 50

Sample Output 1

4

The first route gets him home at cost <var>7</var>.

The second route takes longer than time <var>T = 70</var>.

The third route gets him home at cost <var>4</var>.

Thus, the cost <var>4</var> of the third route is the minimum.

Sample Input 2

4 3
1 1000
2 4
3 1000
4 500

Sample Output 2

TLE

There is no route that takes not longer than time <var>T = 3</var>.

Sample Input 3

5 9
25 8
5 9
4 10
1000 1000
6 1

Sample Output 3

5

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

    std::io::stdin().read_to_string(&mut buf).unwrap();

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let T: usize = iter.next().unwrap().parse().unwrap();
    let mut c = vec![0; n];
    let mut t = vec![0; n];
    for i in 0..n {
        c[i] = iter.next().unwrap().parse().unwrap();
        t[i] = iter.next().unwrap().parse().unwrap();
    }
    let ans = (0..n).filter(|i| t[*i] <= T).map(|i| c[i]).min();

    println!(
        "{}",
        match ans {
            Some(x) => x.to_string(),
            None => "TLE".to_string(),
        }
    );
}


You are given a multiset $$$S$$$ initially consisting of $$$n$$$ distinct non-negative integers. A multiset is a set, that can contain some elements multiple times.You will perform the following operation $$$k$$$ times:   Add the element $$$\lceil\frac{a+b}{2}\rceil$$$ (rounded up) into $$$S$$$, where $$$a = \operatorname{mex}(S)$$$ and $$$b = \max(S)$$$. If this number is already in the set, it is added again. Here $$$\operatorname{max}$$$ of a multiset denotes the maximum integer in the multiset, and $$$\operatorname{mex}$$$ of a multiset denotes the smallest non-negative integer that is not present in the multiset. For example:    $$$\operatorname{mex}(\{1,4,0,2\})=3$$$;   $$$\operatorname{mex}(\{2,5,1\})=0$$$. Your task is to calculate the number of distinct elements in $$$S$$$ after $$$k$$$ operations will be done.

int solution() {
  int t;
  int n;
  int k;
  int max;
  int i;
  int temp;
  int nums[100000];
  char *reg;
  scanf("%d", &t);

  while (t-- > 0) {
    scanf("%d %d", &n, &k);
    reg = (char *)calloc(n, 1);
    for (i = 0, max = 0; i < n; i++) {
      scanf("%d", &temp);
      nums[i] = temp;
      if (temp > max) {
        max = temp;
      }
      if (temp < n) {
        reg[temp] = 1;
      }
    }
    if (k == 0) {
      printf("%d\n", n);
    } else if (max == n - 1) {
      printf("%d\n", n + k);
    } else {
      for (i = 0; i < n; i++) {
        if (reg[i] == 0) {
          break;
        }
      }
      temp = (i + max + 1) / 2;
      for (i = 0; i < n; i++) {
        if (nums[i] == temp) {
          printf("%d\n", n);
          break;
        }
      }
      if (i == n) {
        printf("%d\n", n + 1);
      }
    }
    free(reg);
  }
}

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

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

    let t: usize = scan!(usize);
    for _ in 1..=t {
        let (n, k) = scan!(usize, usize);
        let a = scan!([usize; n]);

        use std::collections::BTreeSet;

        let mut s = BTreeSet::new();

        a.iter().for_each(|x| {
            s.insert(*x);
        });

        if k > 0 {
            let mut mex = s.len() + 1;
            for i in 0..s.len() {
                if !s.contains(&i) {
                    mex = i;
                    break;
                }
            }

            let max = *s.iter().last().unwrap();

            if max > mex {
                s.insert((mex + max).div_ceil(2));
                print!("{}", s.len());
            } else {
                print!("{}", s.len() + k);
            }
        } else {
            print!("{}", s.len());
        }
        print!("\n");
    }
}


Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible. Help Petya to split the integers. Each of n integers should be exactly in one group.

int solution() {
  int n;
  int Ans[60000];
  int cnt = 0;
  scanf("%d", &n);
  long long sum = (long long)n * (n + 1) / 2;
  puts(sum & 1 ? "1" : "0");
  sum /= 2;
  while (1) {
    if (sum >= n) {
      Ans[cnt++] = n;
      sum -= n;
    }
    if (sum == 0) {
      break;
    }
    --n;
  }
  printf("%d ", cnt);
  for (int i = 0; i < cnt; ++i) {
    printf("%d ", Ans[i]);
  }
  return 0;
}

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

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

    let mut g1 = Vec::new();
    let mut g2 = Vec::new();
    let mut s1 = 0;
    let mut s2 = 0;

    for i in (1..n + 1).rev() {
        if s1 < s2 {
            s1 += i;
            g1.push(i);
        } else {
            s2 += i;
            g2.push(i);
        }
    }

    let ans = std::cmp::max(s1, s2) - std::cmp::min(s1, s2);

    println!("{}", ans);

    let mut ans_str = format!("{} ", g1.len());
    for i in g1 {
        ans_str.push_str(&format!("{} ", i));
    }
    println!("{}", ans_str);
}


Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, second one is love, third one is hate and so on...For example if n = 1, then his feeling is "I hate it" or if n = 2 it's "I hate that I love it", and if n = 3 it's "I hate that I love that I hate it" and so on.Please help Dr. Banner.

int solution() {

  int n = 0;
  int cycle = 0;
  scanf("%d", &n);
  while (cycle != n) {
    if (cycle % 2 == 0) {
      printf("I hate ");
      if (cycle + 1 != n) {
        printf("that ");
      }
    } else {
      printf("I love ");
      if (cycle + 1 != n) {
        printf("that ");
      }
    }
    cycle++;
  }
  printf("it\n");
  return 0;
}

fn solution() -> Result<(), Box<dyn std::error::Error>> {
    let n = BufReader::new(std::io::stdin())
        .lines()
        .next()
        .unwrap()?
        .parse::<u8>()?;

    let stdout = std::io::stdout();
    let mut out = stdout.lock();

    if n == 1 {
        writeln!(&mut out, "I hate it")?;
        return Ok(());
    }

    let mut count: u8 = 1;
    write!(out, "I hate that ")?;

    while count < n - 1 {
        match count & 1 {
            1 => write!(out, "I love that ")?,
            0 => write!(out, "I hate that ")?,
            _ => unreachable!(),
        }
        count += 1;
    }

    write!(
        out,
        "{}",
        if count & 1 == 1 {
            "I love it\n"
        } else {
            "I hate it\n"
        }
    )?;
    Ok(())
}


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

int solution() {
  int k;
  int mid;
  int a[10] = {0};
  scanf("%d%*c", &k);
  int rest = k;
  while (~(mid = getchar()) && mid != '\n') {
    a[mid - '0']++;
    rest -= mid - '0';
  }
  int ans = 0;
  int p = 0;
  if (rest <= 0) {
    printf("0\n");
    return 0;
  }
  for (int i = 0; i < 10; i++) {
    if (rest <= (9 - i) * a[i]) {
      ans += (rest + 8 - i) / (9 - i);
      break;
    }
    ans += a[i];
    rest -= a[i] * (9 - i);
  }
  printf("%d\n", ans);
  return 0;
}

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

    let mut input = String::new();

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

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

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

    let mut tab = [0; 10];

    for ind in n.trim().chars().map(|c| c.to_digit(10).unwrap() as usize) {
        tab[ind] += 1;
    }

    let mut sum: usize = tab.iter().enumerate().map(|(i, k)| i * k).sum();
    let mut cnt = 0;

    if k <= sum {
        println!("{}", cnt);
        std::process::exit(0);
    }

    for (i, &p) in tab.iter().enumerate() {
        let i = 9 - i;
        if k > p * i + sum {
            sum += p * i;
            cnt += p;
        } else {
            let diff = k as i64 - sum as i64;
            let x = (diff - 1) / i as i64 + 1;
            cnt += x as usize;
            println!("{}", cnt);
            std::process::exit(0);
        }
    }
}


Score : <var>300</var> points

Problem Statement

<var>N</var> tiles are arranged in a row from left to right. The initial color of each tile is represented by a string <var>S</var> of length <var>N</var>.

The <var>i</var>-th tile from the left is painted black if the <var>i</var>-th character of <var>S</var> is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

<var>1 \leq |S| \leq 10^5</var>

<var>S_i</var> is 0 or 1.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0


List of Top 3 Hills

There is a data which provides heights (in meter) of mountains. The data is only for ten mountains.

Write a program which prints heights of the top three mountains in descending order.

Input

Height of mountain 1
Height of mountain 2
Height of mountain 3
 .
 .
Height of mountain 10

Constraints

0 ≤ height of mountain (integer) ≤ 10,000

Output

Height of the 1st mountain
Height of the 2nd mountain
Height of the 3rd mountain

Sample Input 1

1819
2003
876
2840
1723
1673
3776
2848
1592
922

Output for the Sample Input 1

3776
2848
2840

Sample Input 2

100
200
300
400
500
600
700
800
900
900

Output for the Sample Input 2

900
900
800

int solution() {
  int max = 0;
  int mid = 0;
  int min = 0;
  int h = 0;
  int i = 0;
  for (i = 0; i < 10; i++) {
    scanf("%d", &h);
    if (0 > h || h > 10000) {
      printf("error\n");
      return 0;
    }
    if (max < h) {
      min = mid;
      mid = max;
      max = h;
    } else if (mid < h) {
      min = mid;
      mid = h;
    } else if (min < h) {
      min = h;
    }
  }
  printf("%d\n%d\n%d\n", max, mid, min);
  return 0;
}

fn solution() {
    let mut height: Vec<i32> = Vec::new();
    for _i in 1..11 {
        let mut input = String::new();
        let _ = io::stdin().read_line(&mut input);
        let h = input.trim().parse::<i32>().unwrap();
        height.push(h);
    }

    height.sort_by(|a, b| b.cmp(a));

    for i in 0..3 {
        println!("{}", height.get(i).unwrap());
    }
}


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let t = s.trim().parse::<i32>().unwrap();
    for _ in 0..t {
        s = String::new();
        io::stdin().read_line(&mut s).unwrap();
        let n = s.trim().parse::<i32>().unwrap();
        let mut i = 1;
        while i * i <= n {
            i += 1;
        }
        i -= 1;
        let k = n - i * i;
        if k == 0 {
            println!("{} {}", i, 1);
        } else {
            if k < i + 1 {
                println!("{} {}", k, i + 1)
            } else if k > i + 1 {
                println!("{} {}", i + 1, (i + 1) * 2 - k);
            } else {
                println!("{} {}", i + 1, i + 1);
            }
        }
    }
}


Score : <var>100</var> points

Problem Statement

There is a grid with <var>H</var> rows and <var>W</var> columns.

The square at the <var>i</var>-th row and <var>j</var>-th column contains a string <var>S_{i,j}</var> of length <var>5</var>.

The rows are labeled with the numbers from <var>1</var> through <var>H</var>, and the columns are labeled with the uppercase English letters from A through the <var>W</var>-th letter of the alphabet.

Exactly one of the squares in the grid contains the string snuke. Find this square and report its location.

For example, the square at the <var>6</var>-th row and <var>8</var>-th column should be reported as H6.

Constraints

<var>1≦H, W≦26</var>

The length of <var>S_{i,j}</var> is <var>5</var>.

<var>S_{i,j}</var> consists of lowercase English letters (a-z).

Exactly one of the given strings is equal to snuke.

Input

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

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

Output

Print the labels of the row and the column of the square containing the string snuke, with no space inbetween.

Sample Input 1

15 10
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snuke snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake
snake snake snake snake snake snake snake snake snake snake

Sample Output 1

H6

Sample Input 2

1 1
snuke

Sample Output 2

A1

int solution() {
  int h;
  int w;
  scanf("%d%d", &h, &w);
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      char s[6];
      scanf("%s", s);
      if (strcmp(s, "snuke") == 0) {
        printf("%c%d", 'A' + j, i + 1);
        return 0;
      }
    }
  }
  printf("Hello World");

  return 0;
}

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

    let H = buf_it.next().unwrap().parse::<usize>().unwrap();
    let W = buf_it.next().unwrap().parse::<usize>().unwrap();

    let AZ = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars().collect::<Vec<_>>();

    for i in 1..H + 1 {
        for j in 0..W {
            let s = buf_it.next().unwrap();
            if s == "snuke" {
                println!("{}{}", AZ[j], i);
                return;
            }
        }
    }
}