You are given a grid with $$$n$$$ rows and $$$m$$$ columns. Rows and columns are numbered from $$$1$$$ to $$$n$$$, and from $$$1$$$ to $$$m$$$. The intersection of the $$$a$$$-th row and $$$b$$$-th column is denoted by $$$(a, b)$$$. Initially, you are standing in the top left corner $$$(1, 1)$$$. Your goal is to reach the bottom right corner $$$(n, m)$$$.You can move in four directions from $$$(a, b)$$$: up to $$$(a-1, b)$$$, down to $$$(a+1, b)$$$, left to $$$(a, b-1)$$$ or right to $$$(a, b+1)$$$.You cannot move in the same direction in two consecutive moves, and you cannot leave the grid. What is the minimum number of moves to reach $$$(n, m)$$$?

int solution() {
  int n;
  int m;
  int g = 0;
  while (scanf("%d", &g) != EOF) {
    while (g--) {
      scanf("%d%d", &n, &m);
      if (n > m) {
        int t = n;
        n = m;
        m = t;
      }
      if (n == 1) {
        if (m > 2) {
          printf("-1\n");
        } else {
          printf("%d\n", m - 1);
        }
        continue;
      }
      int c = (2 * n - 2) + (2 * (m - n)) - ((m - n) % 2);
      printf("%d\n", c);
    }
  }
}

fn solution() {
    let mut buffer = String::new();
    stdin().read_line(&mut buffer).expect("Failed");
    let entries = buffer.trim().parse::<i64>().unwrap();
    for _ in 0..entries {
        let mut accumulator = 0;
        buffer.clear();
        stdin().read_line(&mut buffer).expect("Failed");
        let inputs = buffer
            .trim()
            .split(" ")
            .map(|x| x.trim().parse::<i32>().expect("Failed") - 1)
            .collect::<Vec<i32>>();
        let inputs = (inputs[0], inputs[1]);

        if inputs == (0, 0) {
            println!("0")
        } else if inputs.0 == 0 || inputs.1 == 0 {
            if inputs.0 == 1 || inputs.1 == 1 {
                println!("1");
            } else {
                println!("-1");
            }
        } else {
            accumulator += min(inputs.0, inputs.1) * 2;
            let remainder = max(inputs.0, inputs.1) - min(inputs.0, inputs.1);
            if remainder % 2 == 0 {
                accumulator += remainder * 2
            } else {
                accumulator += (remainder - 1) * 2 + 1
            }

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


Score : <var>100</var> points

Problem Statement

There are <var>N</var> dishes, numbered <var>1, 2, \ldots, N</var>.
Initially, for each <var>i</var> (<var>1 \leq i \leq N</var>), Dish <var>i</var> has <var>a_i</var> (<var>1 \leq a_i \leq 3</var>) pieces of sushi on it.

Taro will perform the following operation repeatedly until all the pieces of sushi are eaten:

Roll a die that shows the numbers <var>1, 2, \ldots, N</var> with equal probabilities, and let <var>i</var> be the outcome. If there are some pieces of sushi on Dish <var>i</var>, eat one of them; if there is none, do nothing.

Find the expected number of times the operation is performed before all the pieces of sushi are eaten.

Constraints

All values in input are integers.

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

<var>1 \leq a_i \leq 3</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>a_2</var> <var>\ldots</var> <var>a_N</var>

Output

Print the expected number of times the operation is performed before all the pieces of sushi are eaten.
The output is considered correct when the relative difference is not greater than <var>10^{-9}</var>.

Sample Input 1

3
1 1 1

Sample Output 1

5.5

The expected number of operations before the first piece of sushi is eaten, is <var>1</var>.
After that, the expected number of operations before the second sushi is eaten, is <var>1.5</var>.
After that, the expected number of operations before the third sushi is eaten, is <var>3</var>.
Thus, the expected total number of operations is <var>1 + 1.5 + 3 = 5.5</var>.

Sample Input 2

1
3

Sample Output 2

3

Outputs such as 3.00, 3.000000003 and 2.999999997 will also be accepted.

Sample Input 3

2
1 2

Sample Output 3

4.5

Sample Input 4

10
1 3 2 3 3 2 3 2 1 3

Sample Output 4

54.48064457488221


Score : <var>200</var> points

Problem Statement

There are <var>N</var> children, numbered <var>1, 2, ..., N</var>.

Snuke has decided to distribute <var>x</var> sweets among them.
He needs to give out all the <var>x</var> sweets, but some of the children may get zero sweets.

For each <var>i</var> (<var>1 \leq i \leq N</var>), Child <var>i</var> will be happy if he/she gets exactly <var>a_i</var> sweets.
Snuke is trying to maximize the number of happy children by optimally distributing the sweets.
Find the maximum possible number of happy children.

Constraints

All values in input are integers.

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible number of happy children.

Sample Input 1

3 70
20 30 10

Sample Output 1

2

One optimal way to distribute sweets is <var>(20, 30, 20)</var>.

Sample Input 2

3 10
20 30 10

Sample Output 2

1

The optimal way to distribute sweets is <var>(0, 0, 10)</var>.

Sample Input 3

4 1111
1 10 100 1000

Sample Output 3

4

The optimal way to distribute sweets is <var>(1, 10, 100, 1000)</var>.

Sample Input 4

2 10
20 20

Sample Output 4

0

No children will be happy, no matter how the sweets are distributed.

int solution() {
  int n = 0;
  int x = 0;
  scanf("%d %d", &n, &x);

  int a[n];

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

  for (int i = 0; i < n; i++) {
    for (int j = n - 1; j > i; j--) {
      if (a[j] < a[j - 1]) {
        int temp = a[j];
        a[j] = a[j - 1];
        a[j - 1] = temp;
      }
    }
  }

  int count = 0;

  for (int i = 0; x > 0; i++) {
    if (a[i] > x || (n == count + 1 && x > a[i])) {
      break;
    }
    x -= a[i];

    count++;
  }

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

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let mut x = it.next().unwrap().parse::<i32>().unwrap();
    let mut a = (0..n)
        .map(|_| it.next().unwrap().parse::<i32>().unwrap())
        .collect::<Vec<_>>();
    a.sort();
    let mut res = 0;
    for &t in &a {
        if t <= x {
            x -= t;
            res += 1;
        }
    }
    if res == n && x != 0 {
        res -= 1;
    }
    println!("{}", res);
}


Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$).   If $$$a_i = a_j$$$, change one of them to $$$0$$$.  Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int zeros = 0;
    scanf("%d", &n);
    int arr[n];
    int binary[101];
    for (int i = 0; i < 101; ++i) {
      binary[i] = 0;
    }
    for (int i = 0; i < n; ++i) {
      scanf("%d", &arr[i]);
      binary[arr[i]]++;
      if (arr[i] == 0) {
        zeros++;
      }
    }
    int check = 0;
    if (zeros != 0 && check == 0) {
      printf("%d\n", n - zeros);
      check++;
    } else {
      for (int i = 0; i < 101; ++i) {
        if (binary[i] > 1 && check == 0) {
          printf("%d\n", n);
          check++;
        }
      }
      if (check == 0) {
        printf("%d\n", n + 1);
      }
    }
  }
}

fn solution() {
    let stdin = std::io::stdin();
    let mut inputs = String::new();
    stdin.lock().read_to_string(&mut inputs).ok();

    let mut scanner = inputs
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());

    let case = scanner.next().unwrap();

    for _ in 0..case {
        let n = scanner.next().unwrap();
        let mut cnt = vec![0; 101];

        for _ in 0..n {
            let idx = scanner.next().unwrap();
            if idx == 0 {
                cnt[0] += 1;
            } else {
                cnt[idx] = 2_i32.min(cnt[idx] + 1);
            }
        }
        if cnt[0] >= 1 {
            println!("{}", n - cnt[0] as usize);
        } else if cnt.contains(&2) {
            println!("{}", n);
        } else {
            println!("{}", n + 1);
        }
    }
}


Score : <var>100</var> points

Problem Statement

A biscuit making machine produces <var>B</var> biscuits at the following moments: <var>A</var> seconds, <var>2A</var> seconds, <var>3A</var> seconds and each subsequent multiple of <var>A</var> seconds after activation.

Find the total number of biscuits produced within <var>T + 0.5</var> seconds after activation.

Constraints

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the total number of biscuits produced within <var>T + 0.5</var> seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within <var>7.5</var> seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0

int solution() {
  int time = 0;
  int biscuit = 0;
  int t_limit = 0;
  int i = 0;
  int b_cnt = 0;
  scanf("%d%d%d", &time, &biscuit, &t_limit);
  for (i = 1; i * time < t_limit + 0.5; i++) {
    b_cnt += biscuit;
  }
  printf("%d", b_cnt);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let line: Vec<i32> = buf.split_whitespace().map(|s| s.parse().unwrap()).collect();
    let A = line[0];
    let B = line[1];
    let T = line[2];
    println!("{}", T / A * B);
}


Score : <var>600</var> points

Problem Statement

We have a grid with <var>A</var> horizontal rows and <var>B</var> vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation:

Assume that the grid currently has <var>a</var> horizontal rows and <var>b</var> vertical columns. Choose "vertical" or "horizontal".

If we choose "vertical", insert one row at the top of the grid, resulting in an <var>(a+1) \times b</var> grid.

If we choose "horizontal", insert one column at the right end of the grid, resulting in an <var>a \times (b+1)</var> grid.

Then, paint one of the added squares black, and the other squares white.

Assume the grid eventually has <var>C</var> horizontal rows and <var>D</var> vertical columns. Find the number of ways in which the squares can be painted in the end, modulo <var>998244353</var>.

Constraints

<var>1 \leq A \leq C \leq 3000</var>

<var>1 \leq B \leq D \leq 3000</var>

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of ways in which the squares can be painted in the end, modulo <var>998244353</var>.

Sample Input 1

1 1 2 2

Sample Output 1

3

Any two of the three squares other than the bottom-left square can be painted black.

Sample Input 2

2 1 3 4

Sample Output 2

65

Sample Input 3

31 41 59 265

Sample Output 3

387222020

int solution() {
  long long int a;
  long long int b;
  long long int c;
  long long int d;
  long long int i;
  long long int j;
  long long int x[3100][3100];
  long long int P = 998244353;
  scanf("%lld %lld %lld %lld", &a, &b, &c, &d);

  x[a][b] = 1;
  for (i = a; i <= c - 1; i++) {
    x[i + 1][b] = (x[i][b] * b) % P;
  }
  for (j = b; j <= d - 1; j++) {
    x[a][j + 1] = (x[a][j] * a) % P;
  }
  for (i = a; i <= c - 1; i++) {
    for (j = b; j <= d - 1; j++) {
      x[i + 1][j + 1] =
          (((x[i + 1][j] * (i + 1)) % P) + ((x[i][j + 1] * (j + 1)) % P) -
           ((x[i][j] * i * j) % P)) %
          P;
    }
  }

  if (x[c][d] >= 0) {
    printf("%lld\n", x[c][d]);
  } else {
    printf("%lld\n", x[c][d] + P);
  }
  return 0;
}

fn solution() {
    const MOD: usize = 998244353;

    let [a, b, c, d]: [usize; 4] = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        [
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        ]
    };

    let mut dp = vec![vec![vec![0; 2]; d + 1]; c + 1];
    dp[a][b][1] = 1;
    for i in a..(c + 1) {
        for j in b..(d + 1) {
            if i < c {
                dp[i + 1][j][0] = (dp[i][j][0] + dp[i][j][1]) * j % MOD;
            }
            if j < d {
                dp[i][j + 1][1] = (dp[i][j][0] + dp[i][j][1] * i) % MOD;
            }
        }
    }

    let ans = (dp[c][d][0] + dp[c][d][1]) % MOD;
    println!("{}", ans);
}


Score : <var>200</var> points

Problem Statement

Takahashi has a deposit of <var>100</var> yen (the currency of Japan) in AtCoder Bank.

The bank pays an annual interest rate of <var>1</var> % compounded annually. (A fraction of less than one yen is discarded.)

Assuming that nothing other than the interest affects Takahashi's balance, in how many years does the balance reach <var>X</var> yen or above for the first time?

Constraints

<var> 101 \le X \le 10^{18} </var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

Print the number of years it takes for Takahashi's balance to reach <var>X</var> yen or above for the first time.

Sample Input 1

103

Sample Output 1

3

The balance after one year is <var>101</var> yen.

The balance after two years is <var>102</var> yen.

The balance after three years is <var>103</var> yen.

Thus, it takes three years for the balance to reach <var>103</var> yen or above.

Sample Input 2

1000000000000000000

Sample Output 2

3760

Sample Input 3

1333333333

Sample Output 3

1706

int solution(void) {

  long X = 0;
  long i = 100;
  int count = 0;
  scanf("%ld", &X);

  while (i < X) {
    i *= 1.01;
    count++;
  }
  printf("%d\n", count);

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    buf.pop();
    let X = i64::from_str(&buf).unwrap();
    let mut money = 100;
    let mut cnt = 1;
    loop {
        money = money + (money / 100);
        if money >= X {
            println!("{}", cnt);
            return;
        }
        cnt += 1;
    }
}


You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijk we obtain the table:acdefghjk A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.

int solution() {
  int n;
  int m;
  char mat[105][105];
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%s", mat[i]);
  }
  int cnt = 0;
  int del[105] = {0};
  int les[105] = {0};

  for (int i = 0; i < m; i++) {
    int flag = 0;
    for (int j = 1; j < n; j++) {
      if (les[j] == 0 && mat[j][i] < mat[j - 1][i]) {

        del[i] = 1;
        flag = 1;
        break;
      }
    }
    if (flag) {
      cnt++;
    } else {
      for (int j = 1; j < n; j++) {
        if (mat[j - 1][i] < mat[j][i]) {
          les[j] = 1;
        }
      }
    }
  }

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

  return 0;
}

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

    let mut matrix = [[0u8; 100]; 100];
    let mut ok = [false; 99];

    for i in 0..n {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let line = line.trim().as_bytes();
        for j in 0..m {
            matrix[i][j] = line[j];
        }
    }

    let mut answ: usize = 0;
    for i in 0..m {
        let mut banned = false;
        let mut local_ok = [false; 99];

        for j in 1..n {
            if !ok[j - 1] && matrix[j - 1][i] > matrix[j][i] {
                banned = true;
                break;
            }
            if matrix[j - 1][i] < matrix[j][i] {
                local_ok[j - 1] = true;
            }
        }
        if banned {
            answ += 1;
        } else {
            for j in 0..99 {
                ok[j] |= local_ok[j];
            }
        }
    }

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


Score : <var>300</var> points

Problem Statement

A programming competition site AtCode provides algorithmic problems.
Each problem is allocated a score based on its difficulty.
Currently, for each integer <var>i</var> between <var>1</var> and <var>D</var> (inclusive), there are <var>p_i</var> problems with a score of <var>100i</var> points.
These <var>p_1 + … + p_D</var> problems are all of the problems available on AtCode.

A user of AtCode has a value called total score.
The total score of a user is the sum of the following two elements:

Base score: the sum of the scores of all problems solved by the user.

Perfect bonuses: when a user solves all problems with a score of <var>100i</var> points, he/she earns the perfect bonus of <var>c_i</var> points, aside from the base score <var>(1 ≤ i ≤ D)</var>.

Takahashi, who is the new user of AtCode, has not solved any problem.
His objective is to have a total score of <var>G</var> or more points.
At least how many problems does he need to solve for this objective?

Constraints

<var>1 ≤ D ≤ 10</var>

<var>1 ≤ p_i ≤ 100</var>

<var>100 ≤ c_i ≤ 10^6</var>

<var>100 ≤ G</var>

All values in input are integers.

<var>c_i</var> and <var>G</var> are all multiples of <var>100</var>.

It is possible to have a total score of <var>G</var> or more points.

Input

Input is given from Standard Input in the following format:

<var>D</var> <var>G</var>
<var>p_1</var> <var>c_1</var>
<var>:</var>
<var>p_D</var> <var>c_D</var>

Output

Print the minimum number of problems that needs to be solved in order to have a total score of <var>G</var> or more points. Note that this objective is always achievable (see Constraints).

Sample Input 1

2 700
3 500
5 800

Sample Output 1

3

In this case, there are three problems each with <var>100</var> points and five problems each with <var>200</var> points. The perfect bonus for solving all the <var>100</var>-point problems is <var>500</var> points, and the perfect bonus for solving all the <var>200</var>-point problems is <var>800</var> points. Takahashi's objective is to have a total score of <var>700</var> points or more.

One way to achieve this objective is to solve four <var>200</var>-point problems and earn a base score of <var>800</var> points. However, if we solve three <var>100</var>-point problems, we can earn the perfect bonus of <var>500</var> points in addition to the base score of <var>300</var> points, for a total score of <var>800</var> points, and we can achieve the objective with fewer problems.

Sample Input 2

2 2000
3 500
5 800

Sample Output 2

7

This case is similar to Sample Input 1, but the Takahashi's objective this time is <var>2000</var> points or more. In this case, we inevitably need to solve all five <var>200</var>-point problems, and by solving two <var>100</var>-point problems additionally we have the total score of <var>2000</var> points.

Sample Input 3

2 400
3 500
5 800

Sample Output 3

2

This case is again similar to Sample Input 1, but the Takahashi's objective this time is <var>400</var> points or more. In this case, we only need to solve two <var>200</var>-point problems to achieve the objective.

Sample Input 4

5 25000
20 1000
40 1000
50 1000
30 1000
1 1000

Sample Output 4

66

There is only one <var>500</var>-point problem, but the perfect bonus can be earned even in such a case.

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let d: usize = itr.next().unwrap().parse().unwrap();
    let g: usize = itr.next().unwrap().parse().unwrap();
    let mut p: Vec<usize> = vec![0; d];
    let mut c: Vec<usize> = vec![0; d];
    for i in 0..d {
        p[i] = itr.next().unwrap().parse().unwrap();
        c[i] = itr.next().unwrap().parse().unwrap();
    }

    let mut ans = 1 << 30;
    for bit in 0..1 << d {
        let mut cnt = 0;
        let mut tmp = 0;
        for i in 0..d {
            if bit >> i & 1 == 1 {
                tmp += p[i] * 100 * (i + 1) + c[i];
                cnt += p[i];
            }
        }
        if tmp >= g {
            ans = std::cmp::min(ans, cnt);
        } else {
            for i in (0..d).rev() {
                if bit >> i & 1 == 0 {
                    if tmp + p[i] * 100 * (i + 1) < g {
                        tmp += p[i] * 100 * (i + 1);
                        cnt += p[i];
                    } else {
                        cnt += (g - tmp + 100 * i) / (100 * (i + 1));
                        tmp = g + 1;
                        break;
                    }
                }
            }
            if tmp >= g {
                ans = std::cmp::min(ans, cnt);
            }
        }
    }
    println!("{}", ans);
}


Qpwoeirut has taken up architecture and ambitiously decided to remodel his city.Qpwoeirut's city can be described as a row of $$$n$$$ buildings, the $$$i$$$-th ($$$1 \le i \le n$$$) of which is $$$h_i$$$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $$$i$$$ is taller than the building $$$j$$$ if and only if the number of floors $$$h_i$$$ in building $$$i$$$ is larger than the number of floors $$$h_j$$$ in building $$$j$$$.Building $$$i$$$ is cool if it is taller than both building $$$i-1$$$ and building $$$i+1$$$ (and both of them exist). Note that neither the $$$1$$$-st nor the $$$n$$$-th building can be cool.To remodel the city, Qpwoeirut needs to maximize the number of cool buildings. To do this, Qpwoeirut can build additional floors on top of any of the buildings to make them taller. Note that he cannot remove already existing floors.Since building new floors is expensive, Qpwoeirut wants to minimize the number of floors he builds. Find the minimum number of floors Qpwoeirut needs to build in order to maximize the number of cool buildings.


Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string $$$s$$$ of lowercase Latin letters. She considers a string $$$t$$$ as hidden in string $$$s$$$ if $$$t$$$ exists as a subsequence of $$$s$$$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $$$1$$$, $$$3$$$, and $$$5$$$, which form an arithmetic progression with a common difference of $$$2$$$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $$$S$$$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden $$$3$$$ times, b is hidden $$$2$$$ times, ab is hidden $$$6$$$ times, aa is hidden $$$3$$$ times, bb is hidden $$$1$$$ time, aab is hidden $$$2$$$ times, aaa is hidden $$$1$$$ time, abb is hidden $$$1$$$ time, aaab is hidden $$$1$$$ time, aabb is hidden $$$1$$$ time, and aaabb is hidden $$$1$$$ time. The number of occurrences of the secret message is $$$6$$$.

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

    let arr = buffer.split_whitespace().collect::<Vec<_>>();

    let mut c1 = [0u64; 26];
    let mut c2 = [[0u64; 26]; 26];
    for i in arr.get(0).unwrap().chars() {
        let a = i as u32 - 'a' as u32;
        for j in 0..26 {
            c2[j][a as usize] += c1[j];
        }
        c1[a as usize] += 1;
    }
    let b = *c1.iter().max().unwrap();
    let c = c2.iter().map(|x| *x.iter().max().unwrap()).max().unwrap();
    let ans = cmp::max(b, c);
    println!("{}", ans);
}


You are given a decimal representation of an integer $$$x$$$ without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in $$$x$$$ and replace them with their sum without leading zeros (if the sum is $$$0$$$, it's represented as a single $$$0$$$).For example, if $$$x = 10057$$$, the possible reductions are:   choose the first and the second digits $$$1$$$ and $$$0$$$, replace them with $$$1+0=1$$$; the result is $$$1057$$$;  choose the second and the third digits $$$0$$$ and $$$0$$$, replace them with $$$0+0=0$$$; the result is also $$$1057$$$;  choose the third and the fourth digits $$$0$$$ and $$$5$$$, replace them with $$$0+5=5$$$; the result is still $$$1057$$$;  choose the fourth and the fifth digits $$$5$$$ and $$$7$$$, replace them with $$$5+7=12$$$; the result is $$$10012$$$. What's the largest number that can be obtained?

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let cs: Vec<char> = lines.next().unwrap().unwrap().chars().collect();
        let l = cs.len();
        let mut d = None;
        for i in (1..l).rev() {
            let a = (cs[i] as usize - '0' as usize) + (cs[i - 1] as usize - '0' as usize);
            if a >= 10 {
                d = Some(i);
                break;
            }
        }
        match d {
            None => {
                print!(
                    "{}",
                    (cs[0] as usize - '0' as usize) + (cs[1] as usize) - '0' as usize
                );
                println!("{}", cs[2..l].iter().cloned().collect::<String>());
            }
            Some(e) => {
                print!("{}", cs[0..(e - 1)].iter().cloned().collect::<String>());
                print!(
                    "{}",
                    (cs[e - 1] as usize - '0' as usize) + (cs[e] as usize) - '0' as usize
                );
                println!("{}", cs[(e + 1)..l].iter().cloned().collect::<String>());
            }
        }
    }
}


Score : <var>500</var> points

Problem Statement

Takahashi has a string <var>S</var> of length <var>N</var> consisting of digits from 0 through 9.

He loves the prime number <var>P</var>. He wants to know how many non-empty (contiguous) substrings of <var>S</var> - there are <var>N \times (N + 1) / 2</var> of them - are divisible by <var>P</var> when regarded as integers written in base ten.

Here substrings starting with a 0 also count, and substrings originated from different positions in <var>S</var> are distinguished, even if they are equal as strings or integers.

Compute this count to help Takahashi.

Constraints

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

<var>S</var> consists of digits.

<var>|S| = N</var>

<var>2 \leq P \leq 10000</var>

<var>P</var> is a prime number.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of non-empty (contiguous) substrings of <var>S</var> that are divisible by <var>P</var> when regarded as an integer written in base ten.

Sample Input 1

4 3
3543

Sample Output 1

6

Here <var>S</var> = 3543. There are ten non-empty (contiguous) substrings of <var>S</var>:

3: divisible by <var>3</var>.

35: not divisible by <var>3</var>.

354: divisible by <var>3</var>.

3543: divisible by <var>3</var>.

5: not divisible by <var>3</var>.

54: divisible by <var>3</var>.

543: divisible by <var>3</var>.

4: not divisible by <var>3</var>.

43: not divisible by <var>3</var>.

3: divisible by <var>3</var>.

Six of these are divisible by <var>3</var>, so print <var>6</var>.

Sample Input 2

4 2
2020

Sample Output 2

10

Here <var>S</var> = 2020. There are ten non-empty (contiguous) substrings of <var>S</var>, all of which are divisible by <var>2</var>, so print <var>10</var>.

Note that substrings beginning with a 0 also count.

Sample Input 3

20 11
33883322005544116655

Sample Output 3

68

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let p: usize = itr.next().unwrap().parse().unwrap();
    let mut s: Vec<usize> = itr
        .next()
        .unwrap()
        .chars()
        .map(|c| c.to_digit(10).unwrap() as usize)
        .collect();

    let mut ans = 0;
    if p == 2 {
        for i in 0..n {
            if s[i].is_multiple_of(2) {
                ans += i + 1;
            }
        }
    } else if p == 5 {
        for i in 0..n {
            if s[i].is_multiple_of(5) {
                ans += i + 1;
            }
        }
    } else {
        s.reverse();
        let mut cnt: Vec<usize> = vec![0; n + 1];
        let mut memo: Vec<usize> = vec![0; p + 1];
        let mut ten = 1;
        for i in 0..n {
            cnt[i + 1] = (cnt[i] + s[i] * ten) % p;
            ten = ten * 10 % p;
        }
        for i in 0..n + 1 {
            ans += memo[cnt[i]];
            memo[cnt[i]] += 1;
        }
    }
    println!("{}", ans);
}


Score : <var>400</var> points

Problem Statement

You are given an undirected connected weighted graph with <var>N</var> vertices and <var>M</var> edges that contains neither self-loops nor double edges.

The <var>i</var>-th <var>(1≤i≤M)</var> edge connects vertex <var>a_i</var> and vertex <var>b_i</var> with a distance of <var>c_i</var>.

Here, a self-loop is an edge where <var>a_i = b_i (1≤i≤M)</var>, and double edges are two edges where <var>(a_i,b_i)=(a_j,b_j)</var> or <var>(a_i,b_i)=(b_j,a_j) (1≤i<j≤M)</var>.

A connected graph is a graph where there is a path between every pair of different vertices.

Find the number of the edges that are not contained in any shortest path between any pair of different vertices.

Constraints

<var>2≤N≤100</var>

<var>N-1≤M≤min(N(N-1)/2,1000)</var>

<var>1≤a_i,b_i≤N</var>

<var>1≤c_i≤1000</var>

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

The given graph contains neither self-loops nor double edges.

The given graph is connected.

Input

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

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

Output

Print the number of the edges in the graph that are not contained in any shortest path between any pair of different vertices.

Sample Input 1

3 3
1 2 1
1 3 1
2 3 3

Sample Output 1

1

In the given graph, the shortest paths between all pairs of different vertices are as follows:

The shortest path from vertex <var>1</var> to vertex <var>2</var> is: vertex <var>1</var> → vertex <var>2</var>, with the length of <var>1</var>.

The shortest path from vertex <var>1</var> to vertex <var>3</var> is: vertex <var>1</var> → vertex <var>3</var>, with the length of <var>1</var>.

The shortest path from vertex <var>2</var> to vertex <var>1</var> is: vertex <var>2</var> → vertex <var>1</var>, with the length of <var>1</var>.

The shortest path from vertex <var>2</var> to vertex <var>3</var> is: vertex <var>2</var> → vertex <var>1</var> → vertex <var>3</var>, with the length of <var>2</var>.

The shortest path from vertex <var>3</var> to vertex <var>1</var> is: vertex <var>3</var> → vertex <var>1</var>, with the length of <var>1</var>.

The shortest path from vertex <var>3</var> to vertex <var>2</var> is: vertex <var>3</var> → vertex <var>1</var> → vertex <var>2</var>, with the length of <var>2</var>.

Thus, the only edge that is not contained in any shortest path, is the edge of length <var>3</var> connecting vertex <var>2</var> and vertex <var>3</var>, hence the output should be <var>1</var>.

Sample Input 2

3 2
1 2 1
2 3 1

Sample Output 2

0

Every edge is contained in some shortest path between some pair of different vertices.

int solution(void) {

  int n;
  int m;
  scanf("%d %d", &n, &m);

  int pass[101][101] = {0};
  int x[m];
  int y[m];
  int z[m];

  for (int i = 0; i <= n; i++) {
    for (int j = 0; j <= n; j++) {
      if (i != j) {
        pass[i][j] = -1;
      }
    }
  }

  for (int i = 0; i < m; i++) {
    scanf("%d %d %d", &x[i], &y[i], &z[i]);
    pass[x[i]][y[i]] = z[i];
    pass[y[i]][x[i]] = z[i];
  }

  int count = 0;
  int flag = 0;

  while (1) {
    flag = 0;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= n; j++) {
        for (int k = 1; k <= n; k++) {
          if (pass[i][k] == -1 || pass[k][j] == -1) {
            continue;
          }
          if (pass[i][j] == -1 || pass[i][k] + pass[k][j] < pass[i][j]) {
            pass[i][j] = pass[i][k] + pass[k][j];
            pass[j][i] = pass[i][j];
            flag = 1;
          }
        }
      }
    }
    if (flag == 0) {
      break;
    }
  }
  for (int i = 0; i < m; i++) {
    flag = 0;
    for (int j = 0; j <= n; j++) {
      if (pass[j][x[i]] + z[i] == pass[j][y[i]]) {
        flag = 1;
        break;
      }
    }
    if (flag == 1) {
      count++;
    }
  }

  printf("%d\n", m - count);

  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 m: usize = itr.next().unwrap().parse().unwrap();
    let mut g = vec![vec![1 << 30; n]; n];
    let mut edges = Vec::new();
    for _ in 0..m {
        let a: usize = itr.next().unwrap().parse::<usize>().unwrap() - 1;
        let b: usize = itr.next().unwrap().parse::<usize>().unwrap() - 1;
        let c: usize = itr.next().unwrap().parse().unwrap();
        g[a][b] = c;
        g[b][a] = c;
        edges.push((a, b, c));
    }
    for i in 0..n {
        g[i][i] = 0;
    }
    for k in 0..n {
        for i in 0..n {
            for j in 0..n {
                g[i][j] = min(g[i][j], g[i][k] + g[k][j]);
            }
        }
    }

    let mut ans = 0;
    for i in 0..m {
        if g[edges[i].0][edges[i].1] != edges[i].2 {
            ans += 1;
        }
    }
    println!("{}", ans);
}


Pay attention to the non-standard memory limit in this problem.In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solution.The array $$$a=[a_1, a_2, \ldots, a_n]$$$ ($$$1 \le a_i \le n$$$) is given. Its element $$$a_i$$$ is called special if there exists a pair of indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$) such that $$$a_i = a_l + a_{l+1} + \ldots + a_r$$$. In other words, an element is called special if it can be represented as the sum of two or more consecutive elements of an array (no matter if they are special or not).Print the number of special elements of the given array $$$a$$$.For example, if $$$n=9$$$ and $$$a=[3,1,4,1,5,9,2,6,5]$$$, then the answer is $$$5$$$:  $$$a_3=4$$$ is a special element, since $$$a_3=4=a_1+a_2=3+1$$$;  $$$a_5=5$$$ is a special element, since $$$a_5=5=a_2+a_3=1+4$$$;  $$$a_6=9$$$ is a special element, since $$$a_6=9=a_1+a_2+a_3+a_4=3+1+4+1$$$;  $$$a_8=6$$$ is a special element, since $$$a_8=6=a_2+a_3+a_4=1+4+1$$$;  $$$a_9=5$$$ is a special element, since $$$a_9=5=a_2+a_3=1+4$$$. Please note that some of the elements of the array $$$a$$$ may be equal — if several elements are equal and special, then all of them should be counted in the answer.

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

    io::stdin().read_line(&mut input)?;
    let n = input.trim().parse().unwrap();
    for _ in 0..n {
        input.clear();
        io::stdin().read_line(&mut input)?;

        input.clear();
        io::stdin().read_line(&mut input)?;
        let numbers: Vec<u32> = input
            .trim()
            .split(" ")
            .map(|x| x.parse::<u32>().unwrap())
            .collect();

        let mut special = 0;
        for (i, target) in numbers.clone().into_iter().enumerate() {
            let mut cum = 0;
            let mut vals = 0;
            for (j, current) in numbers.clone().into_iter().enumerate() {
                if i == j {
                    cum = 0;
                    vals = 0;
                    continue;
                }
                cum += current;
                vals += 1;
                while cum > target {
                    cum -= numbers[j + 1 - vals];
                    vals -= 1;
                }
                if cum == target && vals > 1 {
                    special += 1;
                    break;
                }
            }
        }

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

    Ok(())
}


Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be $$$n$$$ participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took $$$x$$$-th place and in the second round — $$$y$$$-th place. Then the total score of the participant A is sum $$$x + y$$$. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every $$$i$$$ from $$$1$$$ to $$$n$$$ exactly one participant took $$$i$$$-th place in first round and exactly one participant took $$$i$$$-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got $$$x$$$-th place in first round and $$$y$$$-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    int a = 0;
    int b = 0;
    int c = 0;
    int d = 0;
    int e = 0;
    scanf("%d%d%d", &n, &a, &b);

    if (a + b <= n) {
      printf("1 ");
    } else {
      c = a + b;
      d = n - 1;
      e = c - d;
      if (e >= n) {
        printf("%d ", n);
      } else {
        printf("%d ", e);
      }
    }

    if (a + b <= n) {
      printf("%d\n", a + b - 1);
    } else {
      printf("%d\n", n);
    }
  }
  return 0;
}

fn solution() {
    let t = {
        let mut buf = String::new();
        stdin().read_line(&mut buf).expect("Failed to read line");
        buf.trim().parse::<i32>().unwrap()
    };
    for _ in 0..t {
        let stuff = {
            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])
        };
        let best_place = max(1, min(stuff.0, stuff.1 + stuff.2 - stuff.0 + 1));
        let worst_place = min(stuff.0, stuff.1 + stuff.2 - 1);
        println!("{} {}", best_place, worst_place);
    }
}


You are given an array $$$a_1, a_2, \dots, a_n$$$, which is sorted in non-descending order. You decided to perform the following steps to create array $$$b_1, b_2, \dots, b_n$$$:   Create an array $$$d$$$ consisting of $$$n$$$ arbitrary non-negative integers.  Set $$$b_i = a_i + d_i$$$ for each $$$b_i$$$.  Sort the array $$$b$$$ in non-descending order. You are given the resulting array $$$b$$$. For each index $$$i$$$, calculate what is the minimum and maximum possible value of $$$d_i$$$ you can choose in order to get the given array $$$b$$$.Note that the minimum (maximum) $$$d_i$$$-s are independent of each other, i. e. they can be obtained from different possible arrays $$$d$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    if (n == 1) {
      long long int n1;
      long long int n2;
      scanf("%lld %lld", &n1, &n2);
      printf("%lld\n%lld\n", n2 - n1, n2 - n1);
      continue;
    }
    long long int a[n];
    long long int b[n];
    long long int min[n];
    long long int max[n];
    long long int val = 0;
    long long int ind = 0;
    for (int i = 0; i < n; i++) {
      scanf("%lld", &a[i]);
    }
    for (int i = 0; i < n; i++) {
      scanf("%lld", &b[i]);
    }
    for (int i = 0, k = 0; i < n;) {
      if (b[k] >= a[i]) {
        min[i] = b[k] - a[i];
        i++;
      } else {
        k++;
      }
    }
    val = b[n - 1];
    for (int i = n - 1, k = n - 2; i > 0, k >= 0; i--, k--) {
      max[i] = val - a[i];
      if (b[k] < a[i]) {
        val = b[i - 1];
      }
    }
    max[0] = val - a[0];
    for (int i = 0; i < n; i++) {
      printf("%lld ", min[i]);
    }
    printf("\n");
    for (int i = 0; i < n; i++) {
      printf("%lld ", max[i]);
    }
    printf("\n");
  }
  return 0;
}

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

    for _tests in 0..t {
        let n: usize = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        };
        let A: Vec<i64> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.parse().unwrap())
                .collect()
        };
        let B: Vec<i64> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.split_whitespace()
                .map(|x| x.parse().unwrap())
                .collect()
        };

        let mut ind_vec = vec![0; n];
        let mut ans1 = vec![0; n];
        let mut ans2 = vec![0; n];

        let mut ind = 0;

        for i in 0..n {
            while B[ind] < A[i] {
                ind += 1;
            }
            ans1[i] = B[ind] - A[i];
            ind_vec[i] = ind;
        }

        let mut maxind = n - 1;

        for i in 0..n {
            let ix = n - 1 - i;

            ans2[ix] = B[maxind] - A[ix];

            if ind_vec[ix] == ix && ix >= 1 {
                maxind = ix - 1;
            }
        }

        println!(
            "{}",
            ans1.iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        );

        println!(
            "{}",
            ans2.iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        );
    }
}


You have a card deck of $$$n$$$ cards, numbered from top to bottom, i. e. the top card has index $$$1$$$ and bottom card — index $$$n$$$. Each card has its color: the $$$i$$$-th card has color $$$a_i$$$.You should process $$$q$$$ queries. The $$$j$$$-th query is described by integer $$$t_j$$$. For each query you should:   find the highest card in the deck with color $$$t_j$$$, i. e. the card with minimum index;  print the position of the card you found;  take the card and place it on top of the deck.

int solution() {
  int n;
  int q;
  scanf("%d %d", &n, &q);
  int sol[q];
  int arrn[n];
  int arrq[q];
  for (int i = 0; i < n; i++) {
    scanf("%d", &arrn[i]);
  }
  for (int i = 0; i < q; i++) {
    scanf("%d", &arrq[i]);
  }
  for (int i = 0; i < q; i++) {
    int f = arrq[i];
    for (int j = 0; j < n; j++) {
      if (arrn[j] == f) {
        sol[i] = j + 1;
        for (int k = 0; k < j; k++) {
          int temp = arrn[j];
          arrn[j] = arrn[k];
          arrn[k] = temp;
        }
        break;
      }
    }
  }
  for (int i = 0; i < q; i++) {
    printf("%d ", sol[i]);
  }
}

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

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

    let n = words[0];
    let _q = words[1];

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

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

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

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

    let mut deck = [0; 51];
    for idx in 0..n {
        if deck[a[idx as usize] as usize] == 0 {
            deck[a[idx as usize] as usize] = idx + 1;
        }
    }

    for color in t {
        print!("{} ", deck[color as usize]);
        for idx in 1..51 {
            if deck[idx as usize] < deck[color as usize] {
                deck[idx as usize] += 1;
            }
        }
        deck[color as usize] = 1;
    }
    println!();
}


The sequence of $$$m$$$ integers is called the permutation if it contains all integers from $$$1$$$ to $$$m$$$ exactly once. The number $$$m$$$ is called the length of the permutation.Dreamoon has two permutations $$$p_1$$$ and $$$p_2$$$ of non-zero lengths $$$l_1$$$ and $$$l_2$$$.Now Dreamoon concatenates these two permutations into another sequence $$$a$$$ of length $$$l_1 + l_2$$$. First $$$l_1$$$ elements of $$$a$$$ is the permutation $$$p_1$$$ and next $$$l_2$$$ elements of $$$a$$$ is the permutation $$$p_2$$$. You are given the sequence $$$a$$$, and you need to find two permutations $$$p_1$$$ and $$$p_2$$$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)

int solution() {
  long long int t;
  scanf("%lld", &t);

  do {
    long long int n;
    scanf("%lld", &n);
    long long int a[n];
    long long int i;
    long long int st = 0;
    long long int freq2[n];
    for (int i = 0; i < n; ++i) {
      freq2[i] = 0;
    }
    for (i = 0; i < n; ++i) {
      scanf("%lld", &a[i]);
      st += a[i];
      freq2[a[i] - 1] += 1;
    }
    long long int sp = 0;
    long long int alfa = 0;
    long long int beta = 0;
    long long int r = 0;
    long long int uno[n];
    long long int dos[n];
    long long int freq[n];

    for (i = 0; i < n; ++i) {
      freq[i] = 0;
    }

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

      freq[a[i] - 1] += 1;
      freq2[a[i] - 1] -= 1;

      alfa = (i + 1) * (i + 2) / 2;
      beta = (n - i - 1) * (n - i) / 2;
      sp += a[i];
      if (sp == alfa && st - sp == beta) {
        long long int cen = 0;
        for (long long int j = 0; j < n; ++j) {
          if (freq[j] > 1 || freq2[j] > 1) {
            cen = 1;
          }
        }

        if (cen == 0) {
          uno[r] = i + 1;
          dos[r] = n - (i + 1);
          ++r;
        }
      }
    }

    printf("%lld\n", r);
    for (i = 0; i < r; ++i) {
      printf("%lld %lld\n", uno[i], dos[i]);
    }

    --t;
  } while (t != 0);
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .map(|x: usize| x - 1)
            .collect();
        let mut p: usize = 0;
        let mut bs: Vec<bool> = vec![false; n];
        let mut ixs: Vec<usize> = Vec::new();
        for i in 0..n {
            bs[xs[i]] = true;
            while p < n && bs[p] {
                p += 1;
            }
            if i + 1 == p {
                ixs.push(p);
            }
        }
        let mut p: usize = 0;
        let mut bs: Vec<bool> = vec![false; n];
        let mut jxs: Vec<usize> = Vec::new();
        for i in (0..n).rev() {
            bs[xs[i]] = true;
            while p < n && bs[p] {
                p += 1;
            }
            if n - i == p {
                jxs.push(p);
            }
        }
        jxs.reverse();
        let mut i: usize = 0;
        let mut j: usize = 0;
        let mut ans: Vec<(usize, usize)> = Vec::new();
        while i < ixs.len() && j < jxs.len() {
            if ixs[i] + jxs[j] == n {
                ans.push((ixs[i], jxs[j]));
                i += 1;
                j += 1;
            } else if ixs[i] + jxs[j] < n {
                i += 1;
            } else {
                j += 1;
            }
        }
        println!("{}", ans.len());
        for (i, j) in ans {
            println!("{} {}", i, j);
        }
    }
}


Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

int solution() {
  int t;
  scanf("%i", &t);
  getchar();
  while (t--) {
    char str[101];
    scanf("%s", str);
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
      if (i == 0 || i % 2 == 1) {
        printf("%c", str[i]);
      }
    }
    printf("\n");
  }
  return 0;
}

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

    let mut iterator = stdin.lock().lines();
    let mut line: String;
    let mut original: Vec<String> = Vec::new();

    line = iterator.next().unwrap().unwrap();
    let t: i32 = line.parse().unwrap();

    for _ in 0..t {
        original.clear();
        line = iterator.next().unwrap().unwrap();
        for (i, c) in line.chars().enumerate() {
            if i <= 1 || i % 2 == 1 {
                original.push(c.to_string());
            }
        }
        println!("{}", original.join(""));
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi has two positive integers <var>A</var> and <var>B</var>.

It is known that <var>A</var> plus <var>B</var> equals <var>N</var>.
Find the minimum possible value of "the sum of the digits of <var>A</var>" plus "the sum of the digits of <var>B</var>" (in base <var>10</var>).

Constraints

<var>2 ≤ N ≤ 10^5</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the minimum possible value of "the sum of the digits of <var>A</var>" plus "the sum of the digits of <var>B</var>".

Sample Input 1

15

Sample Output 1

6

When <var>A=2</var> and <var>B=13</var>, the sums of their digits are <var>2</var> and <var>4</var>, which minimizes the value in question.

Sample Input 2

100000

Sample Output 2

10

int solution(void) {
  char n[100000];
  scanf("%s", n);

  int ans = 0;
  for (int i = 0; n[i] != '\0'; i++) {
    ans += (int)n[i] - 48;
  }
  if (ans == 1) {
    ans = 10;
  }
  printf("%d\n", ans);
  return 0;
}

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

    let mut m = n;
    let mut ans = 0;
    while m > 0 {
        ans += m % 10;
        m /= 10;
    }

    let mut f = false;
    for i in 1..6 {
        if n == 10usize.pow(i) {
            f = true;
        }
    }

    if f {
        println!("10");
    } else {
        println!("{}", ans);
    }
}


Score : <var>600</var> points

Problem Statement

We have a tree with <var>N</var> vertices numbered <var>1</var> to <var>N</var>.
The <var>i</var>-th edge in this tree connects Vertex <var>a_i</var> and Vertex <var>b_i</var>.

Consider painting each of these edges white or black. There are <var>2^{N-1}</var> such ways to paint the edges. Among them, how many satisfy all of the following <var>M</var> restrictions?

The <var>i</var>-th <var>(1 \leq i \leq M)</var> restriction is represented by two integers <var>u_i</var> and <var>v_i</var>, which mean that the path connecting Vertex <var>u_i</var> and Vertex <var>v_i</var> must contain at least one edge painted black.

Constraints

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

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

The graph given in input is a tree.

<var>1 \leq M \leq \min(20,\frac{N(N-1)}{2})</var>

<var>1 \leq u_i < v_i \leq N</var>

If <var>i \not= j</var>, either <var>u_i \not=u_j</var> or <var>v_i\not=v_j</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>b_1</var>
<var>:</var>
<var>a_{N-1}</var> <var>b_{N-1}</var>
<var>M</var>
<var>u_1</var> <var>v_1</var>
<var>:</var>
<var>u_M</var> <var>v_M</var>

Output

Print the number of ways to paint the edges that satisfy all of the <var>M</var> conditions.

Sample Input 1

3
1 2
2 3
1
1 3

Sample Output 1

3

The tree in this input is shown below:

All of the <var>M</var> restrictions will be satisfied if Edge <var>1</var> and <var>2</var> are respectively painted (white, black), (black, white), or (black, black), so the answer is <var>3</var>.

Sample Input 2

2
1 2
1
1 2

Sample Output 2

1

The tree in this input is shown below:

All of the <var>M</var> restrictions will be satisfied only if Edge <var>1</var> is painted black, so the answer is <var>1</var>.

Sample Input 3

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

Sample Output 3

9

The tree in this input is shown below:

Sample Input 4

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

Sample Output 4

62

The tree in this input is shown below:

int solution() {
  int i;
  int u;
  int w;
  int N;
  int M;
  int s[21];
  int t[21];
  int adj[51][51] = {};
  scanf("%d", &N);
  for (i = 1; i < N; i++) {
    scanf("%d %d", &u, &w);
    adj[u][w] = i;
    adj[w][u] = i;
  }
  scanf("%d", &M);
  for (i = 0; i < M; i++) {
    scanf("%d %d", &(s[i]), &(t[i]));
  }

  int prev[51];
  int q[51];
  int head;
  int tail;
  long long bit[51] = {1};
  long long P[21] = {};
  for (i = 1; i <= 50; i++) {
    bit[i] = bit[i - 1] << 1;
  }
  for (i = 0; i < M; i++) {
    for (u = 1; u <= N; u++) {
      prev[u] = -1;
    }
    q[0] = s[i];
    prev[s[i]] = s[i];
    for (head = 0, tail = 1; head < tail; head++) {
      u = q[head];
      for (w = 1; w <= N; w++) {
        if (adj[u][w] == 0) {
          continue;
        }
        if (w == t[i]) {
          break;
        }
        if (prev[w] == -1) {
          prev[w] = u;
          q[tail++] = w;
        }
      }
      if (w <= N) {
        break;
      }
    }
    for (; w != u; w = u, u = prev[u]) {
      P[i] |= bit[adj[u][w]];
    }
  }

  int j;
  int sum[2];
  long long n;
  long long ans = (long long)1 << N - 1;
  long long white;
  for (n = 1; n < bit[M]; n++) {
    white = 0;
    for (i = 0; i < M; i++) {
      if ((n | bit[i]) == n) {
        white |= P[i];
      }
    }
    for (j = 1, sum[0] = 0; j < N; j++) {
      sum[0] += white / bit[j] % 2;
    }
    for (i = 0, sum[1] = 0; i < M; i++) {
      sum[1] += n / bit[i] % 2;
    }
    if (sum[1] % 2 == 1) {
      ans -= bit[N - 1 - sum[0]];
    } else {
      ans += bit[N - 1 - sum[0]];
    }
  }

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

fn solution() {
    let N: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let (a, b): (Vec<usize>, Vec<usize>) = {
        let (mut a, mut b) = (vec![], vec![]);
        for _ in 0..(N - 1) {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            a.push(iter.next().unwrap().parse().unwrap());
            b.push(iter.next().unwrap().parse().unwrap());
        }
        (a, b)
    };
    let M: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let (u, v): (Vec<usize>, Vec<usize>) = {
        let (mut u, mut v) = (vec![], vec![]);
        for _ in 0..M {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            u.push(iter.next().unwrap().parse().unwrap());
            v.push(iter.next().unwrap().parse().unwrap());
        }
        (u, v)
    };

    let G = {
        let mut G = vec![std::collections::HashMap::new(); N + 1];
        for i in 0..(N - 1) {
            G[a[i]].insert(b[i], i);
            G[b[i]].insert(a[i], i);
        }
        G
    };

    let mut dp = vec![std::collections::HashSet::new(); M];
    for i in 0..M {
        let mut prev = vec![(0, 0); N + 1];
        let mut q = std::collections::VecDeque::new();
        q.push_back(u[i]);
        while let Some(j) = q.pop_front() {
            for (&x, &e) in &G[j] {
                if prev[x].0 == 0 {
                    prev[x] = (j, e);
                    q.push_back(x);
                }
            }
        }
        let mut j = v[i];
        while j != u[i] {
            dp[i].insert(prev[j].1);
            j = prev[j].0;
        }
    }

    let mut res = 0i64;
    for i in 1..(1 << M) {
        let mut x = 0;
        let mut used = vec![false; N + 1];
        let mut s = 0;
        for j in 0..M {
            if (i >> j) & 1 == 1 {
                x += 1;
                for &y in &dp[j] {
                    if !used[y] {
                        s += 1;
                    }
                    used[y] = true;
                }
            }
        }
        let d = 1i64 << (N - 1 - s);

        if x % 2 == 1 {
            res += d;
        } else {
            res -= d;
        }
    }
    let ans = (1i64 << (N - 1)) - res;
    println!("{}", ans);
}


Given three distinct integers $$$a$$$, $$$b$$$, and $$$c$$$, find the medium number between all of them.The medium number is the number that is neither the minimum nor the maximum of the given three numbers. For example, the median of $$$5,2,6$$$ is $$$5$$$, since the minimum is $$$2$$$ and the maximum is $$$6$$$.

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("");
    let t: i32 = line.trim().parse().expect("");
    for _ in 0..t {
        let reader = io::stdin();
        let mut numbers: Vec<i32> = reader
            .lock()
            .lines()
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|s| s.parse().unwrap())
            .collect();
        numbers.sort();
        println!("{:?}", numbers[1]);
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $$$2$$$) or determine that there is no such subset.Both the given array and required subset may contain equal values.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int a[10010];
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%d", &a[i]);
    }
    int place = -1;

    for (int i = 1; i <= n; i++) {
      if (a[i] % 2 == 0) {
        place = i;
        break;
      }
    }
    if (place != -1) {
      printf("1\n%d\n", place);
    } else if (place == -1 && n == 1) {
      printf("-1\n");
    } else {
      printf("2\n1 2\n");
    }
  }
  return 0;
}

fn solution() {
    let mut quantity = String::new();
    stdin().read_line(&mut quantity).unwrap();
    let quantity = quantity.trim().parse::<u32>().unwrap();
    for _i in 0..quantity {
        let mut arr = String::new();
        stdin().read_line(&mut arr).unwrap();
        arr = String::new();
        stdin().read_line(&mut arr).unwrap();
        let arr: Vec<_> = arr
            .trim()
            .split(' ')
            .map(|i| i.parse::<u8>().unwrap())
            .collect();
        if arr[0] & 1 == 0 {
            println!("1\n1");
            continue;
        }
        if arr.len() != 1 {
            if arr[1] & 1 == 0 {
                println!("1\n2")
            } else {
                println!("2\n1 2")
            }
        } else {
            println!("-1")
        }
    }
}


Score : <var>400</var> points

Problem Statement

We have a string <var>S</var> of length <var>N</var> consisting of R, G, and B.

Find the number of triples <var>(i,~j,~k)~(1 \leq i < j < k \leq N)</var> that satisfy both of the following conditions:

<var>S_i \neq S_j</var>, <var>S_i \neq S_k</var>, and <var>S_j \neq S_k</var>.

<var>j - i \neq k - j</var>.

Constraints

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

<var>S</var> is a string of length <var>N</var> consisting of R, G, and B.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of triplets in question.

Sample Input 1

4
RRGB

Sample Output 1

1

Only the triplet <var>(1,~3,~4)</var> satisfies both conditions. The triplet <var>(2,~3,~4)</var> satisfies the first condition but not the second, so it does not count.

Sample Input 2

39
RBRBGRBGGBBRRGBBRRRBGGBRBGBRBGBRBBBGBBB

Sample Output 2

1800

int solution() {
  int n;
  char s[4000];
  long long int sum = 0;
  scanf("%d", &n);
  scanf("%s", s);
  long long int rnum = 0;
  long long int gnum = 0;
  long long int bnum = 0;
  for (int i = 0; i < n; i++) {
    if (s[i] == 'R') {
      rnum++;
      continue;
    }
    if (s[i] == 'G') {
      gnum++;
      continue;
    }
    bnum++;
    continue;
  }
  sum = rnum * gnum * bnum;
  for (int i = 1; i < n - 1; i++) {
    for (int j = 1; i - j >= 0 && i + j < n; j++) {
      if (s[i] != s[i - j] && s[i] != s[i + j] && s[i - j] != s[i + j]) {
        sum--;
      }
    }
  }
  printf("%lld", sum);
  return 0;
}

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

    let s: Vec<usize> = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        buf.trim_end()
            .chars()
            .map(|c| {
                if c == 'R' {
                    0
                } else if c == 'G' {
                    1
                } else {
                    2
                }
            })
            .collect()
    };

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

    let mut ans = 0usize;
    for i in 0..(n - 2) {
        for j in (i + 1)..(n - 1) {
            if s[i] == s[j] {
                continue;
            }
            ans += count[j + 1][3 - s[i] - s[j]];
            if j - i + j < n && s[j - i + j] == 3 - s[i] - s[j] {
                ans -= 1;
            }
        }
    }
    println!("{}", ans);
}


Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

int solution() {
  int n;
  int bra = 0;
  int count = 0;
  int check = 0;
  scanf("%d", &n);
  char a[n];

  for (int i = 0; i < n; i++) {
    scanf(" %c", &a[i]);
  }
  for (int i = 0; i < n; i++) {
    if (a[i] == '(') {
      count++;
    } else if (a[i] == ')') {
      count--;
    }
    if (count < 0) {
      check = 1;
    }
    if (count < -1) {
      bra = 1;
    }
  }
  if (count == 0 && check == 0) {
    printf("Yes");
  } else if (count == 0 && check == 1) {
    if (bra == 0) {
      printf("Yes");
    } else {
      printf("No");
    }
  } else {
    printf("No");
  }
}

fn solution() {
    let mut _buffer = String::new();
    io::stdin()
        .read_line(&mut _buffer)
        .expect("failed to read input");
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read input");
    let vec = buffer
        .trim()
        .chars()
        .map(|c| if c == '(' { 1 } else { -1 })
        .collect::<Vec<i8>>();

    let mut acc: i32 = 0;
    let mut changed = false;
    for i in vec {
        acc += i as i32;
        if acc == -1 {
            if changed {
                break;
            }
            changed = true;
            acc = 0;
        }
    }
    if changed {
        acc -= 1;
    }
    println!("{}", if acc == 0 { "Yes" } else { "No" });
}


Score : <var>300</var> points

Problem Statement

We have a string <var>X</var>, which has an even number of characters. Half the characters are S, and the other half are T.

Takahashi, who hates the string ST, will perform the following operation <var>10^{10000}</var> times:

Among the occurrences of ST in <var>X</var> as (contiguous) substrings, remove the leftmost one. If there is no occurrence, do nothing.

Find the eventual length of <var>X</var>.

Constraints

<var>2 ≦ |X| ≦ 200,000</var>

The length of <var>X</var> is even.

Half the characters in <var>X</var> are S, and the other half are T.

Partial Scores

In test cases worth <var>200</var> points, <var>|X| ≦ 200</var>.

Input

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

<var>X</var>

Output

Print the eventual length of <var>X</var>.

Sample Input 1

TSTTSS

Sample Output 1

4

In the <var>1</var>-st operation, the <var>2</var>-nd and <var>3</var>-rd characters of TSTTSS are removed.
<var>X</var> becomes TTSS, and since it does not contain ST anymore, nothing is done in the remaining <var>10^{10000}-1</var> operations.
Thus, the answer is <var>4</var>.

Sample Input 2

SSTTST

Sample Output 2

0

<var>X</var> will eventually become an empty string: SSTTST ⇒ STST ⇒ ST ⇒ ``.

Sample Input 3

TSSTTTSS

Sample Output 3

4

<var>X</var> will become: TSSTTTSS ⇒ TSTTSS ⇒ TTSS.

int solution() {
  int s_cnt = 0;
  int ans = 0;
  while (1) {
    char c = getchar();
    if (c == 'S') {
      s_cnt++;
      ans++;
    } else if (c == 'T' && s_cnt > 0) {
      s_cnt--;
      ans--;
    } else if (c == 'T') {
      ans++;
    } else {
      break;
    }
  }
  printf("%d\n", ans);
  return 0;
}

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

    let mut cnt = 0;
    let mut del = 0;
    for &x in v.iter() {
        if x == 'S' {
            cnt += 1;
        } else if cnt > 0 {
            cnt -= 1;
            del += 2;
        }
    }
    println!("{}", v.len() - del);
}


Score : <var>300</var> points

Problem Statement

We have a <var>2 \times N</var> grid. We will denote the square at the <var>i</var>-th row and <var>j</var>-th column (<var>1 \leq i \leq 2</var>, <var>1 \leq j \leq N</var>) as <var>(i, j)</var>.

You are initially in the top-left square, <var>(1, 1)</var>.
You will travel to the bottom-right square, <var>(2, N)</var>, by repeatedly moving right or down.

The square <var>(i, j)</var> contains <var>A_{i, j}</var> candies.
You will collect all the candies you visit during the travel.
The top-left and bottom-right squares also contain candies, and you will also collect them.

At most how many candies can you collect when you choose the best way to travel?

Constraints

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

<var>1 \leq A_{i, j} \leq 100</var> (<var>1 \leq i \leq 2</var>, <var>1 \leq j \leq N</var>)

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_{1, 1}</var> <var>A_{1, 2}</var> <var>...</var> <var>A_{1, N}</var>
<var>A_{2, 1}</var> <var>A_{2, 2}</var> <var>...</var> <var>A_{2, N}</var>

Output

Print the maximum number of candies that can be collected.

Sample Input 1

5
3 2 2 4 1
1 2 2 2 1

Sample Output 1

14

The number of collected candies will be maximized when you:

move right three times, then move down once, then move right once.

Sample Input 2

4
1 1 1 1
1 1 1 1

Sample Output 2

5

You will always collect the same number of candies, regardless of how you travel.

Sample Input 3

7
3 3 4 5 4 5 3
5 3 4 4 2 3 2

Sample Output 3

29

Sample Input 4

1
2
3

Sample Output 4

5

int solution(void) {
  int N = 0;
  int count = 0;
  int max = 0;
  scanf("%d", &N);
  int A[N][2];
  for (int i = 0; i < N; i++) {
    scanf("%d", &A[i][0]);
  }
  for (int i = 0; i < N; i++) {
    scanf("%d", &A[i][1]);
  }
  for (int i = 0; i < N; i++) {
    count = 0;
    for (int k = 0; k <= i; k++) {
      count += A[k][0];
    }
    for (int j = i; j < N; j++) {
      count += A[j][1];
    }
    if (max < count) {
      max = count;
    }
  }

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

  return 0;
}

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

    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let squares: Vec<Vec<u32>> = vec![
        (0..n)
            .map(|_| iter.next().unwrap().parse().unwrap())
            .collect(),
        (0..n)
            .map(|_| iter.next().unwrap().parse().unwrap())
            .collect(),
    ];

    let mut answers = Vec::new();
    for i in 0..n {
        answers
            .push(squares[0][0..(i + 1)].iter().sum::<u32>() + squares[1][i..].iter().sum::<u32>());
    }

    println!("{}", answers.iter().max().unwrap());
}


Your favorite shop sells $$$n$$$ Kinder Surprise chocolate eggs. You know that exactly $$$s$$$ stickers and exactly $$$t$$$ toys are placed in $$$n$$$ eggs in total.Each Kinder Surprise can be one of three types:  it can contain a single sticker and no toy;  it can contain a single toy and no sticker;  it can contain both a single sticker and a single toy. But you don't know which type a particular Kinder Surprise has. All eggs look identical and indistinguishable from each other.What is the minimum number of Kinder Surprise Eggs you have to buy to be sure that, whichever types they are, you'll obtain at least one sticker and at least one toy?Note that you do not open the eggs in the purchasing process, that is, you just buy some number of eggs. It's guaranteed that the answer always exists.

int solution() {
  int T;
  scanf("%d", &T);
  while (T--) {
    long long int n;
    long long int s;
    long long int t;
    scanf("%lld %lld %lld", &n, &s, &t);
    if (n == s && n == t) {
      printf("1\n");
    }

    else {
      if (s >= t) {
        printf("%lld\n", n - t + 1);
      } else {
        printf("%lld\n", n - s + 1);
      }
    }
  }
  return 0;
}

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

    stdin.lock().read_line(&mut line)?;

    let trimmed_line = line.trim();
    let number_of_queries: u8 = trimmed_line.parse().unwrap();

    let queries: Vec<_> = stdin
        .lock()
        .lines()
        .filter_map(Result::ok)
        .take(number_of_queries as usize)
        .collect();

    for query in queries {
        let query: Vec<_> = query.split(' ').collect();

        let n: u64 = query[0].parse().unwrap();
        let s: u64 = query[1].parse().unwrap();
        let t: u64 = query[2].parse().unwrap();

        let b = cmp::max(s, t) - (n - cmp::min(s, t));
        println!("{}", cmp::max(s - b, t - b) + 1);
    }

    Ok(())
}


Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

fn solution() {
    let (r, d) = {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace().map(|k| k.parse::<f64>().unwrap());
        (it.next().unwrap(), it.next().unwrap())
    };

    let n = {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();
        input.trim().parse::<usize>().unwrap()
    };

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

    for _ in 0..n {
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).unwrap();
        let mut it = input.split_whitespace().map(|k| k.parse::<f64>().unwrap());
        pp.push((it.next().unwrap(), it.next().unwrap(), it.next().unwrap()));
    }

    let ans = pp
        .into_iter()
        .filter(|&(x, y, ri)| {
            let di = (x.powi(2) + y.powi(2)).sqrt();
            di - ri >= r - d && di + ri <= r
        })
        .count();

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


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

int solution() {
  int n;
  char values[200005];

  scanf("%d", &n);
  scanf("%s", values);
  int one = 0;
  int zero = 0;
  for (int i = 0; i < n; i++) {
    if (values[i] == '0') {
      zero++;
    } else {
      one++;
    }
  }
  if (one < zero) {
    printf("%d\n", n - (2 * one));
  } else {
    printf("%d\n", n - (2 * zero));
  }

  return 0;
}

fn solution() {
    let mut text = String::new();
    io::stdin().read_to_string(&mut text).unwrap();
    let mut iter = text.split_whitespace();
    let _n = iter.next().unwrap();
    let s = iter.next().unwrap();
    let mut count = 0i32;
    for c in s.chars() {
        if c == '1' {
            count += 1;
        } else {
            count -= 1;
        }
    }
    println!("{}", count.abs());
}


A magic island Geraldion, where Gerald lives, has its own currency system. It uses banknotes of several values. But the problem is, the system is not perfect and sometimes it happens that Geraldionians cannot express a certain sum of money with any set of banknotes. Of course, they can use any number of banknotes of each value. Such sum is called unfortunate. Gerald wondered: what is the minimum unfortunate sum?

fn solution() {
    let inputstatus = 1;

    let mut buf = String::new();
    let filename = "inputrust.txt";

    if inputstatus == 0 {
        let mut f = File::open(filename).expect("file not found");
        f.read_to_string(&mut buf)
            .expect("something went wrong reading the file");
    } else {
        std::io::stdin().read_to_string(&mut buf).unwrap();
    }

    let mut iter = buf.split_whitespace();
    let _n: usize = iter.next().unwrap().parse().unwrap();
    let mut num = [100000; 100000];
    for (i, v) in iter.enumerate() {
        num[i] = v.parse().unwrap();
    }
    num.sort();

    let ans = match num[0] {
        1 => -1,
        _ => 1,
    };
    println!("{}", ans);
}


After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if:   $$$i = j$$$, that is, they are at the same index.  $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times:   choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

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

  long long int arr[n + 1];
  long long int brr[n + 1];
  long long int ais[n + 1];
  long long int bis[n + 1];
  long long int dist[n + 1];
  for (long long int i = 1; i <= n; i++) {
    scanf("%lld", &arr[i]);
    ais[arr[i]] = i;
  }

  for (long long int i = 1; i <= n; i++) {
    scanf("%lld", &brr[i]);
    bis[brr[i]] = i;
  }

  for (int i = 0; i <= n; i++) {
    dist[i] = 0;
  }

  for (int i = 1; i <= n; i++) {
    int x = ais[i];
    int y = bis[i];
    if (x <= y) {
      dist[y - x]++;
    } else {
      dist[n - x + y]++;
    }
  }

  int mx = -1;
  for (int i = 0; i < n; i++) {
    if (dist[i] > mx) {
      mx = dist[i];
    }
  }

  printf("%d\n", mx);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
    let xs: Vec<usize> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|x| x.parse().unwrap())
        .collect();
    let mut ys: Vec<usize> = lines
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|x| x.parse().unwrap())
        .collect();
    let mut ixs: Vec<(usize, usize)> = xs.iter().cloned().enumerate().collect();
    ixs.sort_by(|a, b| a.1.cmp(&b.1));
    for i in 0..ys.len() {
        ys[i] = ixs[ys[i] - 1].0;
    }
    let mut counts: Vec<usize> = vec![0; n];
    for i in 0..ys.len() {
        let j = (ys[i] + n - i) % n;
        counts[j] += 1;
    }
    let ans = counts.iter().max().unwrap();
    println!("{}", ans);
}


Lee is going to fashionably decorate his house for a party, using some regular convex polygons...Lee thinks a regular $$$n$$$-sided (convex) polygon is beautiful if and only if he can rotate it in such a way that at least one of its edges is parallel to the $$$OX$$$-axis and at least one of its edges is parallel to the $$$OY$$$-axis at the same time.Recall that a regular $$$n$$$-sided polygon is a convex polygon with $$$n$$$ vertices such that all the edges and angles are equal.Now he is shopping: the market has $$$t$$$ regular polygons. For each of them print YES if it is beautiful and NO otherwise.

int solution() {
  int n;
  scanf("%d\n", &n);
  int p[n];
  for (int i = 0; i < n; i++) {
    scanf("%d\n", &p[i]);
    if (((p[i]) % 4) == 0) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
}

fn solution() {
    let mut t = String::new();
    io::stdin().read_line(&mut t).expect("");
    let t: u32 = t.trim().parse().expect("");
    for _ in 0..t {
        let mut n = String::new();
        io::stdin().read_line(&mut n).expect("");
        let n: u64 = n.trim().parse().expect("");
        if n.is_multiple_of(4) {
            println!("Yes");
        } else {
            println!("No");
        }
    }
}


Score : <var>100</var> points

Problem Statement

You are given a <var>4</var>-character string <var>S</var> consisting of uppercase English letters.
Determine if <var>S</var> consists of exactly two kinds of characters which both appear twice in <var>S</var>.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> consists of exactly two kinds of characters which both appear twice in <var>S</var>, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

<var>S</var> consists of A and S which both appear twice in <var>S</var>.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No

int solution(void) {
  char S[5];
  scanf("%s", S);
  char a = S[0];
  char b = S[1];
  char c = S[2];
  char d = S[3];
  bool ok = false;
  if (a == b && c == d && a != c) {
    ok = true;
  }
  if (a == c && b == d && a != d) {
    ok = true;
  }
  if (a == d && b == c && a != b) {
    ok = true;
  }
  if (ok) {
    printf("Yes");
  } else {
    printf("No");
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    s = s.trim_end().to_owned();
    let mut s_vec: Vec<char> = s.chars().collect();
    s_vec.sort();
    if s_vec[0] == s_vec[1] && s_vec[1] != s_vec[2] && s_vec[2] == s_vec[3] {
        println!("Yes");
    } else {
        println!("No");
    }
}


You have a list of numbers from $$$1$$$ to $$$n$$$ written from left to right on the blackboard.You perform an algorithm consisting of several steps (steps are $$$1$$$-indexed). On the $$$i$$$-th step you wipe the $$$i$$$-th number (considering only remaining numbers). You wipe the whole number (not one digit).  When there are less than $$$i$$$ numbers remaining, you stop your algorithm. Now you wonder: what is the value of the $$$x$$$-th remaining number after the algorithm is stopped?

int solution() {

  int T;
  scanf("%d", &T);
  int x[T];
  int n;

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

  for (int i = 0; i < T; ++i) {
    printf("%d\n", 2 * x[i]);
  }

  return 0;
}

fn solution() {
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read input");
    let t: u16 = buffer.trim().parse().expect("invalid input");

    for _ in 0..t {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let l: u64 = input.split_whitespace().last().unwrap().parse().unwrap();

        println!("{}", 2 * l);
    }
}


Score : <var>100</var> points

Problem Statement

AtCoDeer has three cards, one red, one green and one blue.

An integer between <var>1</var> and <var>9</var> (inclusive) is written on each card: <var>r</var> on the red card, <var>g</var> on the green card and <var>b</var> on the blue card.

We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.

Is this integer a multiple of <var>4</var>?

Constraints

<var>1 ≤ r, g, b ≤ 9</var>

Input

Input is given from Standard Input in the following format:

<var>r</var> <var>g</var> <var>b</var>

Output

If the three-digit integer is a multiple of <var>4</var>, print YES (case-sensitive); otherwise, print NO.

Sample Input 1

4 3 2

Sample Output 1

YES

<var>432</var> is a multiple of <var>4</var>, and thus YES should be printed.

Sample Input 2

2 3 4

Sample Output 2

NO

<var>234</var> is not a multiple of <var>4</var>, and thus NO should be printed.

int solution() {

  int r = 0;
  int g = 0;
  int b = 0;

  int number = 0;

  scanf("%d %d %d", &r, &g, &b);

  number = 100 * r + 10 * g + b;

  if (number % 4 == 0) {
    printf("YES");
  } else {
    printf("NO");
  }

  return 0;
}

fn solution() {
    use std::io;
    let mut input = String::new();
    let _ = io::stdin().read_line(&mut input);
    let inputs = input
        .split_whitespace()
        .map(|x| x.parse::<isize>().unwrap())
        .collect::<Vec<isize>>();
    let num = inputs[1] * 10 + inputs[2];
    if num % 4 == 0 {
        println!("YES");
    } else {
        println!("NO");
    }
}


Finding Missing Cards

  Taro is going to play a card game. However, now he has only <var>n</var> cards, even though there should be 52 cards (he has no Jokers).

The 52 cards include 13 ranks of each of the four suits: spade, heart, club and diamond.

Input

  In the first line, the number of cards <var>n</var> (<var>n</var> ≤ 52) is given.

  In the following <var>n</var> lines, data of the <var>n</var> cards are given. Each card is given by a pair of a character and an integer which represent its suit and rank respectively. A suit is represented by 'S', 'H', 'C' and 'D' for spades, hearts, clubs and diamonds respectively. A rank is represented by an integer from 1 to 13.

Output

  Print the missing cards. The same as the input format, each card should be printed with a character and an integer separated by a space character in a line.
 Arrange the missing cards in the following priorities:

Print cards of spades, hearts, clubs and diamonds in this order.

If the suits are equal, print cards with lower ranks first.

Sample Input

47
S 10
S 11
S 12
S 13
H 1
H 2
S 6
S 7
S 8
S 9
H 6
H 8
H 9
H 10
H 11
H 4
H 5
S 2
S 3
S 4
S 5
H 12
H 13
C 1
C 2
D 1
D 2
D 3
D 4
D 5
D 6
D 7
C 3
C 4
C 5
C 6
C 7
C 8
C 9
C 10
C 11
C 13
D 9
D 10
D 11
D 12
D 13

Sample Output

S 1
H 3
H 7
C 12
D 8

Note

      解説

int solution(void) {

  int repeatNumber = 0;
  scanf("%d", &repeatNumber);
  int spade[13] = {0};
  int heart[13] = {0};
  int chulab[13] = {0};
  int dia[13] = {0};
  char judge1 = 'A';
  int judge2 = 0;

  for (int i = 0; i < repeatNumber; i++) {
    scanf(" %c %d", &judge1, &judge2);

    if (judge1 == 'S') {
      spade[judge2 - 1]++;
    } else if (judge1 == 'H') {
      heart[judge2 - 1]++;
    } else if (judge1 == 'C') {
      chulab[judge2 - 1]++;
    } else if (judge1 == 'D') {
      dia[judge2 - 1]++;
    }
  }

  for (int i = 0; i < 13; i++) {
    if (spade[i] != 1) {
      printf("S %d\n", i + 1);
    }
  }

  for (int i = 0; i < 13; i++) {
    if (heart[i] != 1) {
      printf("H %d\n", i + 1);
    }
  }

  for (int i = 0; i < 13; i++) {
    if (chulab[i] != 1) {
      printf("C %d\n", i + 1);
    }
  }

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

    if (dia[i] != 1) {
      printf("D %d\n", i + 1);
    }
  }

  return 0;
}

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

    let design = ['S', 'H', 'C', 'D'];
    let mut trump = HashMap::new();

    for d in &design {
        trump.insert(d, [false; 13]);
    }

    let _ = stdin.read_line(&mut buf);
    let n = i64::from_str(buf.trim()).unwrap();

    for _ in 0..n {
        buf.clear();
        let _ = stdin.read_line(&mut buf);
        let vec: Vec<&str> = buf.split_whitespace().collect();
        let (d, r) = (
            vec[0].chars().next().unwrap(),
            usize::from_str(vec[1]).unwrap(),
        );

        trump.get_mut(&d).unwrap()[r - 1] = true;
    }

    for d in &design {
        for (i, r) in trump[d].iter().enumerate() {
            if !r {
                println!("{} {}", d, i + 1);
            }
        }
    }
}


Score: <var>300</var> points

Problem Statement

In Republic of Atcoder, there are <var>N</var> prefectures, and a total of <var>M</var> cities that belong to those prefectures.

City <var>i</var> is established in year <var>Y_i</var> and belongs to Prefecture <var>P_i</var>.

You can assume that there are no multiple cities that are established in the same year.

It is decided to allocate a <var>12</var>-digit ID number to each city.

If City <var>i</var> is the <var>x</var>-th established city among the cities that belong to Prefecture <var>i</var>, the first six digits of the ID number of City <var>i</var> is <var>P_i</var>, and the last six digits of the ID number is <var>x</var>.

Here, if <var>P_i</var> or <var>x</var> (or both) has less than six digits, zeros are added to the left until it has six digits.

Find the ID numbers for all the cities.

Note that there can be a prefecture with no cities.

Constraints

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

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

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

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

<var>Y_i</var> are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>P_1</var> <var>Y_1</var>
<var>:</var>
<var>P_M</var> <var>Y_M</var>

Output

Print the ID numbers for all the cities, in ascending order of indices (City <var>1</var>, City <var>2</var>, <var>...</var>).

Sample Input 1

2 3
1 32
2 63
1 12

Sample Output 1

000001000002
000002000001
000001000001

As City <var>1</var> is the second established city among the cities that belong to Prefecture <var>1</var>, its ID number is <var>000001000002</var>.

As City <var>2</var> is the first established city among the cities that belong to Prefecture <var>2</var>, its ID number is <var>000002000001</var>.

As City <var>3</var> is the first established city among the cities that belong to Prefecture <var>1</var>, its ID number is <var>000001000001</var>.

Sample Input 2

2 3
2 55
2 77
2 99

Sample Output 2

000002000001
000002000002
000002000003

int solution() {
  long long N;
  long long M;
  long long i;
  scanf("%lld%lld", &N, &M);
  long long P[M];
  long long Y[M];
  long long C[M];
  long long A[M];
  long long count[N + 1];
  for (i = 0; i < M; i++) {
    scanf("%lld%lld", &P[i], &Y[i]);
    C[i] = i;
  }
  for (i = 0; i <= N; i++) {
    count[i] = 0;
  }

  long long h = M;
  long long swapped = 0;
  while (h > 1 || swapped == 1) {
    if (h > 1) {
      h = h * 10 / 13;
    }
    swapped = 0;
    for (i = 0; i < M - h; i++) {
      if (Y[i] > Y[i + h]) {
        long long tmp = Y[i];
        Y[i] = Y[i + h];
        Y[i + h] = tmp;
        tmp = P[i];
        P[i] = P[i + h];
        P[i + h] = tmp;
        tmp = C[i];
        C[i] = C[i + h];
        C[i + h] = tmp;
        swapped = 1;
      }
    }
  }

  for (i = 0; i < M; i++) {
    count[P[i]]++;
    A[C[i]] = P[i] * 1000000 + count[P[i]];
  }
  for (i = 0; i < M; i++) {
    if (A[i]) {
      printf("%012lld\n", A[i]);
    }
  }
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let m = it.next().unwrap().parse::<usize>().unwrap();
    let mut c = vec![Vec::new(); n];
    for i in 0..m {
        let p = it.next().unwrap().parse::<usize>().unwrap() - 1;
        let y = it.next().unwrap().parse::<i32>().unwrap();
        c[p].push((y, i));
    }
    let mut id = vec![(0, 0); m];
    for i in 0..n {
        c[i].sort();
        for j in 0..c[i].len() {
            id[c[i][j].1] = (i + 1, j + 1);
        }
    }
    for &p in &id {
        println!("{:06}{:06}", p.0, p.1);
    }
}


Score : <var>500</var> points

Problem Statement

You are given a string <var>S</var> consisting of 0 and 1.
Find the maximum integer <var>K</var> not greater than <var>|S|</var> such that we can turn all the characters of <var>S</var> into 0 by repeating the following operation some number of times.

Choose a contiguous segment <var>[l,r]</var> in <var>S</var> whose length is at least <var>K</var> (that is, <var>r-l+1\geq K</var> must be satisfied). For each integer <var>i</var> such that <var>l\leq i\leq r</var>, do the following: if <var>S_i</var> is 0, replace it with 1; if <var>S_i</var> is 1, replace it with 0.

Constraints

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

<var>S_i(1\leq i\leq N)</var> is either 0 or 1.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the maximum integer <var>K</var> such that we can turn all the characters of <var>S</var> into 0 by repeating the operation some number of times.

Sample Input 1

010

Sample Output 1

2

We can turn all the characters of <var>S</var> into 0 by the following operations:

Perform the operation on the segment <var>S[1,3]</var> with length <var>3</var>. <var>S</var> is now 101.

Perform the operation on the segment <var>S[1,2]</var> with length <var>2</var>. <var>S</var> is now 011.

Perform the operation on the segment <var>S[2,3]</var> with length <var>2</var>. <var>S</var> is now 000.

Sample Input 2

100000000

Sample Output 2

8

Sample Input 3

00001111

Sample Output 3

4

int solution() {
  char S[100000];
  scanf("%s", S);

  int length = strlen(S);
  int K = strlen(S);

  for (int i = 0; i < length - 1; i++) {
    if (S[i + 1] != S[i]) {
      if (2 * (i + 1) < length && length - (i + 1) < K) {
        K = length - (i + 1);
      } else if (i + 1 < K) {
        K = i + 1;
      }
    }
  }
  printf("%d", K);
}

fn solution() {
    let stdin = stdin();
    let mut lock = stdin.lock();
    let mut str1 = String::new();
    lock.read_line(&mut str1).unwrap();
    let vec: Vec<_> = str1.split_whitespace().next().unwrap().bytes().collect();
    let mut sanjo = vec.len();
    for (i, j) in vec.iter().enumerate() {
        if i == 0 {
            continue;
        }
        if *j != vec[i - 1] {
            if i < vec.len() - i && vec.len() - i < sanjo {
                sanjo = vec.len() - i;
            } else if i < sanjo {
                sanjo = i;
            }
        }
    }
    println!("{}", sanjo);
}


Score : <var>800</var> points

Problem Statement

There are <var>N</var> towns in Snuke Kingdom, conveniently numbered <var>1</var> through <var>N</var>.
Town <var>1</var> is the capital.

Each town in the kingdom has a Teleporter, a facility that instantly transports a person to another place.
The destination of the Teleporter of town <var>i</var> is town <var>a_i</var> (<var>1≤a_i≤N</var>).
It is guaranteed that one can get to the capital from any town by using the Teleporters some number of times.

King Snuke loves the integer <var>K</var>.
The selfish king wants to change the destination of the Teleporters so that the following holds:

Starting from any town, one will be at the capital after using the Teleporters exactly <var>K</var> times in total.

Find the minimum number of the Teleporters whose destinations need to be changed in order to satisfy the king's desire.

Constraints

<var>2≤N≤10^5</var>

<var>1≤a_i≤N</var>

One can get to the capital from any town by using the Teleporters some number of times.

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

Input

The 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 minimum number of the Teleporters whose destinations need to be changed in order to satisfy King Snuke's desire.

Sample Input 1

3 1
2 3 1

Sample Output 1

2

Change the destinations of the Teleporters to <var>a = (1,1,1)</var>.

Sample Input 2

4 2
1 1 2 2

Sample Output 2

0

There is no need to change the destinations of the Teleporters, since the king's desire is already satisfied.

Sample Input 3

8 2
4 1 2 3 1 2 3 4

Sample Output 3

3

For example, change the destinations of the Teleporters to <var>a = (1,1,2,1,1,2,2,4)</var>.

int solution() {
  int i;
  int N;
  int K;
  int a[100001];
  scanf("%d %d", &N, &K);
  for (i = 1; i <= N; i++) {
    scanf("%d", &(a[i]));
  }

  int ans = 0;
  if (a[1] != 1) {
    a[1] = 1;
    ans++;
  }

  list *adj[100001];
  list e[100001];
  for (i = 2; i <= N; i++) {
    e[i].v = i;
    e[i].next = adj[a[i]];
    adj[a[i]] = &(e[i]);
  }

  int height[100001] = {};
  int q[100001];
  int head;
  int tail;
  list *p;
  q[0] = 1;
  for (head = 0, tail = 1; head < tail; head++) {
    for (p = adj[q[head]]; p != NULL; p = p->next) {
      q[tail++] = p->v;
    }
  }
  for (head--; head > 0; head--) {
    i = q[head];
    if (height[i] == K - 1 && a[i] != 1) {
      height[i] = -1;
      a[i] = 1;
      ans++;
    }
    if (height[a[i]] < height[i] + 1) {
      height[a[i]] = height[i] + 1;
    }
  }
  printf("%d\n", ans);
  fflush(stdout);
  return 0;
}

fn solution() {
    input!(n: usize, k: usize, a: [usize1; n]);
    let mut ans = 0;
    let mut a = a;
    if a[0] != 0 {
        ans += 1;
        a[0] = 0;
    }
    let mut tree = vec![vec![]; n];
    for child in 0..n {
        let parent = a[child];
        tree[parent].push(child);
    }

    let mut dist_from_leaf = vec![0; n];
    let mut finished_count = vec![0; n];
    let mut q = VecDeque::new();
    for i in 0..n {
        if tree[i].is_empty() {
            q.push_back(i);
        }
    }

    while let Some(v) = q.pop_front() {
        let parent = a[v];
        finished_count[parent] += 1;
        if dist_from_leaf[v] == k - 1 {
            if parent != 0 {
                ans += 1;
            }
        } else {
            dist_from_leaf[parent] = cmp::max(dist_from_leaf[parent], dist_from_leaf[v] + 1);
        };

        if finished_count[parent] == tree[parent].len() {
            q.push_back(parent);
        }
    }

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