Score : <var>200</var> points

Problem Statement

We have a string <var>S</var> of length <var>N</var> consisting of uppercase English letters.

How many times does ABC occur in <var>S</var> as contiguous subsequences (see Sample Inputs and Outputs)?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print number of occurrences of ABC in <var>S</var> as contiguous subsequences.

Sample Input 1

10
ZABCDBABCQ

Sample Output 1

2

Two contiguous subsequences of <var>S</var> are equal to ABC: the <var>2</var>-nd through <var>4</var>-th characters, and the <var>7</var>-th through <var>9</var>-th characters.

Sample Input 2

19
THREEONEFOURONEFIVE

Sample Output 2

0

No contiguous subsequences of <var>S</var> are equal to ABC.

Sample Input 3

33
ABCCABCBABCCABACBCBBABCBCBCBCABCB

Sample Output 3

5

int solution(void) {

  int N = 0;
  int count = 0;

  scanf("%d", &N);

  char S[N];

  scanf("%s", S);

  for (int i = 0; i < (N - 2); i++) {

    if (S[i] == 'A' && S[i + 1] == 'B' && S[i + 2] == 'C') {

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

  return 0;
}

fn solution() {
    let (_n, s): (i32, String) = {
        let mut buf = String::new();
        std::io::stdin().read_to_string(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().to_string(),
        )
    };

    println!("{}", s.matches("ABC").collect::<Vec<&str>>().len());
}


Score : <var>200</var> points

Problem Statement

Kurohashi has never participated in AtCoder Beginner Contest (ABC).

The next ABC to be held is ABC <var>N</var> (the <var>N</var>-th ABC ever held).
Kurohashi wants to make his debut in some ABC <var>x</var> such that all the digits of <var>x</var> in base ten are the same.

What is the earliest ABC where Kurohashi can make his debut?

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If the earliest ABC where Kurohashi can make his debut is ABC <var>n</var>, print <var>n</var>.

Sample Input 1

111

Sample Output 1

111

The next ABC to be held is ABC <var>111</var>, where Kurohashi can make his debut.

Sample Input 2

112

Sample Output 2

222

The next ABC to be held is ABC <var>112</var>, which means Kurohashi can no longer participate in ABC <var>111</var>.
Among the ABCs where Kurohashi can make his debut, the earliest one is ABC <var>222</var>.

Sample Input 3

750

Sample Output 3

777

fn solution() {
    let handle = std::io::stdin();
    let mut buf = String::new();
    handle.lock().read_line(&mut buf).unwrap();
    let num: usize = usize::from_str(buf.trim()).unwrap();
    if num < 112 {
        println!("111");
    } else if num < 223 {
        println!("222");
    } else if num < 334 {
        println!("333");
    } else if num < 445 {
        println!("444");
    } else if num < 556 {
        println!("555");
    } else if num < 667 {
        println!("666");
    } else if num < 778 {
        println!("777");
    } else if num < 889 {
        println!("888");
    } else if num < 1000 {
        println!("999");
    } else {
        println!("u r wrong");
    }
}


Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t = 0;
  int a = 0;
  int b = 0;
  int c = 0;
  int n = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; ++i) {
    scanf("%d %d %d %d", &a, &b, &c, &n);
    if (a >= b && a >= c) {
      if (n < a - b + a - c) {
        printf("NO\n");
        continue;
      }
      printf(((n - (a - b) - (a - c)) % 3 == 0) ? "YES\n" : "NO\n");
    } else if (b >= a && b >= c) {
      if (n < b - a + b - c) {
        printf("NO\n");
        continue;
      }
      printf(((n - (b - a) - (b - c)) % 3 == 0) ? "YES\n" : "NO\n");
    } else {
      if (n < c - b + c - a) {
        printf("NO\n");
        continue;
      }
      printf(((n - (c - b) - (c - a)) % 3 == 0) ? "YES\n" : "NO\n");
    }
  }
}

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

    for t in stdin.lock().lines().skip(1) {
        let t: Vec<i64> = t.unwrap().split(' ').map(|x| x.parse().unwrap()).collect();

        if let [a, b, c, n] = t[..] {
            let m = std::cmp::max(a, std::cmp::max(b, c));
            let r = n - (m - a) - (m - b) - (m - c);

            if r >= 0 && r % 3 == 0 {
                println!("YES");
            } else {
                println!("NO");
            }
        }
    }
}


Score : <var>400</var> points

Problem Statement

Along a road running in an east-west direction, there are <var>A</var> shrines and <var>B</var> temples.
The <var>i</var>-th shrine from the west is located at a distance of <var>s_i</var> meters from the west end of the road, and the <var>i</var>-th temple from the west is located at a distance of <var>t_i</var> meters from the west end of the road.

Answer the following <var>Q</var> queries:

Query <var>i</var> (<var>1 \leq i \leq Q</var>): If we start from a point at a distance of <var>x_i</var> meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

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

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

<var>1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}</var>

<var>1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}</var>

<var>1 \leq x_i \leq 10^{10}</var>

<var>s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q</var> are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var> <var>Q</var>
<var>s_1</var>
<var>:</var>
<var>s_A</var>
<var>t_1</var>
<var>:</var>
<var>t_B</var>
<var>x_1</var>
<var>:</var>
<var>x_Q</var>

Output

Print <var>Q</var> lines. The <var>i</var>-th line should contain the answer to the <var>i</var>-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of <var>100, 600</var> meters from the west end of the road, and the temples are located at distances of <var>400, 900, 1000</var> meters from the west end of the road.

Query <var>1</var>: If we start from a point at a distance of <var>150</var> meters from the west end of the road, the optimal move is first to walk <var>50</var> meters west to visit a shrine, then to walk <var>300</var> meters east to visit a temple.

Query <var>2</var>: If we start from a point at a distance of <var>2000</var> meters from the west end of the road, the optimal move is first to walk <var>1000</var> meters west to visit a temple, then to walk <var>400</var> meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query <var>3</var>: If we start from a point at a distance of <var>899</var> meters from the west end of the road, the optimal move is first to walk <var>1</var> meter east to visit a temple, then to walk <var>300</var> meters west to visit a shrine.

Query <var>4</var>: If we start from a point at a distance of <var>799</var> meters from the west end of the road, the optimal move is first to walk <var>199</var> meters west to visit a shrine, then to walk <var>200</var> meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a <var>32</var>-bit integer.

fn solution() {
    input!(
        a: usize,
        b: usize,
        q: usize,
        s: [i64; a],
        t: [i64; b],
        query: [i64; q],
    );

    let shrine: Vec<i64> = vec![std::i64::MIN]
        .into_iter()
        .chain(s)
        .chain(vec![std::i64::MAX])
        .collect();

    let temple: Vec<i64> = vec![std::i64::MIN]
        .into_iter()
        .chain(t)
        .chain(vec![std::i64::MAX])
        .collect();

    for qi in query.iter() {
        let sh = shrine.binary_search(qi);
        let tm = temple.binary_search(qi);

        let mut scand = vec![];
        let mut tcand = vec![];

        match sh {
            Ok(x) => {
                scand.push(shrine[x]);
            }
            Err(x) => {
                if x - 1 != 0 {
                    scand.push(shrine[x - 1]);
                }
                if x != a + 1 {
                    scand.push(shrine[x]);
                }
            }
        }

        match tm {
            Ok(x) => {
                tcand.push(temple[x]);
            }
            Err(x) => {
                if x - 1 != 0 {
                    tcand.push(temple[x - 1]);
                }
                if x != b + 1 {
                    tcand.push(temple[x]);
                }
            }
        }

        let mut ans: i64 = std::i64::MAX;
        for si in scand.iter() {
            for ti in tcand.iter() {
                if si < qi && ti < qi {
                    ans = cmp::min(ans, qi - cmp::min(si, ti));
                } else if si >= qi && ti < qi {
                    ans = cmp::min(ans, si - ti + cmp::min(si - qi, qi - ti));
                } else if si < qi && ti >= qi {
                    ans = cmp::min(ans, ti - si + cmp::min(ti - qi, qi - si));
                } else {
                    ans = cmp::min(ans, cmp::max(si, ti) - qi);
                }
            }
        }

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


Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

int solution()

{
  int n;
  int i;
  int j;
  int sum = 0;
  int c = 0;
  int min;
  int a = 0;
  int k;

  scanf("%d", &n);

  int x[n];

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

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

    min = 1000000001;

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

      if (x[i] >= sum && x[i] - sum < min) {
        min = x[i] - sum;
        k = i;
        a = 1;
        if (!min) {
          break;
        }
      }
    }

    if (!a) {
      break;
    }
    c++;
    sum += x[k];
    x[k] = 0;
    a = 0;
  }

  printf("%d", c);
}

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

    let mut line = String::new();

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

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

    words.sort();

    let mut suma = 0;
    let mut answer = 0;
    for i in words {
        if suma <= i {
            suma += i;
            answer += 1;
        }
    }

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


Score : <var>100</var> points

Problem Statement

You are given integers <var>A</var> and <var>B</var>, each between <var>1</var> and <var>3</var> (inclusive).

Determine if there is an integer <var>C</var> between <var>1</var> and <var>3</var> (inclusive) such that <var>A \times B \times C</var> is an odd number.

Constraints

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

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

Output

If there is an integer <var>C</var> between <var>1</var> and <var>3</var> that satisfies the condition, print Yes; otherwise, print No.

Sample Input 1

3 1

Sample Output 1

Yes

Let <var>C = 3</var>. Then, <var>A \times B \times C = 3 \times 1 \times 3 = 9</var>, which is an odd number.

Sample Input 2

1 2

Sample Output 2

No

Sample Input 3

2 2

Sample Output 3

No

int solution(void) {
  int a = 0;
  int b = 0;
  scanf("%d %d", &a, &b);
  if ((a * b % 2) == 0) {
    printf("No");
  } else {
    printf("Yes");
  }
}

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

    let mut s = String::new();
    let _ = reader.read_line(&mut s);
    let v: Vec<u32> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();

    if v[0] % 2 == 1 && v[1] % 2 == 1 {
        println!("Yes");
    } else {
        println!("No");
    }
}


Score: <var>300</var> points

Problem Statement

As AtCoder Beginner Contest 100 is taking place, the office of AtCoder, Inc. is decorated with a sequence of length <var>N</var>, <var>a = </var>{<var>a_1, a_2, a_3, ..., a_N</var>}.

Snuke, an employee, would like to play with this sequence.

Specifically, he would like to repeat the following operation as many times as possible:

For every <var>i</var> satisfying <var>1 \leq i \leq N</var>, perform one of the following: "divide <var>a_i</var> by <var>2</var>" and "multiply <var>a_i</var> by <var>3</var>".
Here, choosing "multiply <var>a_i</var> by <var>3</var>" for every <var>i</var> is not allowed, and the value of <var>a_i</var> after the operation must be an integer.

At most how many operations can be performed?

Constraints

<var>N</var> is an integer between <var>1</var> and <var>10 \ 000</var> (inclusive).

<var>a_i</var> is an integer between <var>1</var> and <var>1 \ 000 \ 000 \ 000</var> (inclusive).

Input

Input is given from Standard Input in the following format:

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

Output

Print the maximum number of operations that Snuke can perform.

Sample Input 1

3
5 2 4

Sample Output 1

3

The sequence is initially <var>{5, 2, 4}</var>. Three operations can be performed as follows:

First, multiply <var>a_1</var> by <var>3</var>, multiply <var>a_2</var> by <var>3</var> and divide <var>a_3</var> by <var>2</var>. The sequence is now <var>{15, 6, 2}</var>.

Next, multiply <var>a_1</var> by <var>3</var>, divide <var>a_2</var> by <var>2</var> and multiply <var>a_3</var> by <var>3</var>. The sequence is now <var>{45, 3, 6}</var>.

Finally, multiply <var>a_1</var> by <var>3</var>, multiply <var>a_2</var> by <var>3</var> and divide <var>a_3</var> by <var>2</var>. The sequence is now <var>{135, 9, 3}</var>.

Sample Input 2

4
631 577 243 199

Sample Output 2

0

No operation can be performed since all the elements are odd. Thus, the answer is <var>0</var>.

Sample Input 3

10
2184 2126 1721 1800 1024 2528 3360 1945 1280 1776

Sample Output 3

39

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

fn solution() {
    let mut count_line = String::new();
    std::io::stdin().read_line(&mut count_line).ok();
    let mut values_line = String::new();
    std::io::stdin().read_line(&mut values_line).ok();
    let it = values_line.split_whitespace();
    let mut dividable_count = 0;

    for i in it {
        let mut u: u64 = i.parse().unwrap();
        let mut current_divide = 0;
        while u.is_multiple_of(2) {
            u /= 2;
            current_divide += 1;
        }
        dividable_count += current_divide;
    }
    println!("{}", dividable_count);
}


A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!You are given integers $$$n,k$$$. Construct a grid $$$A$$$ with size $$$n \times n$$$ consisting of integers $$$0$$$ and $$$1$$$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $$$k$$$. In other words, the number of $$$1$$$ in the grid is equal to $$$k$$$.Let's define:  $$$A_{i,j}$$$ as the integer in the $$$i$$$-th row and the $$$j$$$-th column.  $$$R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$$$ (for all $$$1 \le i \le n$$$).  $$$C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$$$ (for all $$$1 \le j \le n$$$).  In other words, $$$R_i$$$ are row sums and $$$C_j$$$ are column sums of the grid $$$A$$$.  For the grid $$$A$$$ let's define the value $$$f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$$$ (here for an integer sequence $$$X$$$ we define $$$\max(X)$$$ as the maximum value in $$$X$$$ and $$$\min(X)$$$ as the minimum value in $$$X$$$). Find any grid $$$A$$$, which satisfies the following condition. Among such grids find any, for which the value $$$f(A)$$$ is the minimum possible. Among such tables, you can find any.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let (n, k) = (xs[0], xs[1]);
        println!("{}", if k % n == 0 { 0 } else { 2 });
        let mut m: Vec<Vec<bool>> = vec![vec![false; n]; n];
        for i in 0..k {
            let j = i % n;
            let l = (i + (i / n)) % n;
            m[j][l] = true;
        }
        for i in 0..n {
            let s: Vec<u8> = m[i].iter().map(|&b| if b { b'1' } else { b'0' }).collect();
            println!("{}", String::from_utf8(s).unwrap());
        }
    }
}


Score : <var>300</var> points

Problem Statement

You are given four integers <var>A</var>, <var>B</var>, <var>C</var>, and <var>D</var>. Find the number of integers between <var>A</var> and <var>B</var> (inclusive) that can be evenly divided by neither <var>C</var> nor <var>D</var>.

Constraints

<var>1\leq A\leq B\leq 10^{18}</var>

<var>1\leq C,D\leq 10^9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of integers between <var>A</var> and <var>B</var> (inclusive) that can be evenly divided by neither <var>C</var> nor <var>D</var>.

Sample Input 1

4 9 2 3

Sample Output 1

2

<var>5</var> and <var>7</var> satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368

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

  long long bC = 0;
  long long bD = 0;
  long long bCD = 0;
  long long aC = 0;
  long long aD = 0;
  long long aCD = 0;
  long long sumB = 0;
  long long sumA = 0;
  long long max = 0;
  long long min = 0;
  long long amari = 0;
  long long lcm = 0;
  scanf("%lld %lld %lld %lld", &A, &B, &C, &D);
  bC = B / C;
  bD = B / D;
  aC = (A - 1) / C;
  aD = (A - 1) / D;
  if (C < D) {
    max = D;
    min = C;
  } else {
    max = C;
    min = D;
  }
  while (1) {
    amari = max % min;
    if (amari == 0) {
      break;
    }
    max = min;
    min = amari;
  }

  lcm = C * D / min;

  bCD = B / (lcm);
  aCD = (A - 1) / (lcm);

  sumB = B - bC - bD + bCD;
  sumA = (A - 1) - aC - aD + aCD;

  printf("%lld\n", sumB - sumA);

  return 0;
}

fn solution() {
    input! {
        a:u64,
        b:u64,
        c:u64,
        d:u64
    }

    let mut temp: u64;

    let mut m = d;
    let mut n = c;

    while m % n != 0 {
        temp = n;
        n = m % n;
        m = temp;
    }

    let min_multi = d * c / n;

    let diff_c = b / c - (a - 1) / c;
    let diff_d = b / d - (a - 1) / d;
    let diff_mulit = b / min_multi - (a - 1) / min_multi;

    let muti_num = diff_c + diff_d - diff_mulit;

    let ans = b - a + 1 - muti_num;
    println!("{}", ans)
}


Score : <var>200</var> points

Problem Statement

An integer <var>X</var> is called a Harshad number if <var>X</var> is divisible by <var>f(X)</var>, where <var>f(X)</var> is the sum of the digits in <var>X</var> when written in base <var>10</var>.

Given an integer <var>N</var>, determine whether it is a Harshad number.

Constraints

<var>1?N?10^8</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print Yes if <var>N</var> is a Harshad number; print No otherwise.

Sample Input 1

12

Sample Output 1

Yes

<var>f(12)=1+2=3</var>. Since <var>12</var> is divisible by <var>3</var>, <var>12</var> is a Harshad number.

Sample Input 2

57

Sample Output 2

No

<var>f(57)=5+7=12</var>. Since <var>57</var> is not divisible by <var>12</var>, <var>12</var> is not a Harshad number.

Sample Input 3

148

Sample Output 3

No

int solution(void) {
  int n;
  scanf("%d", &n);
  int x = 0;
  int ten = 1;
  for (int i = 0; i <= 8; i++) {
    x += n / ten % 10;
    ten *= 10;
  }
  if (n % x == 0) {
    printf("Yes\n");
  } else {
    printf("No\n");
  }
  return 0;
}

fn solution() {
    let stdin = stdin();
    let mut stdinlock = stdin.lock();
    let mut str1 = String::new();
    stdinlock.read_line(&mut str1).unwrap();
    let mut it1 = str1.split_whitespace().map(|x| u32::from_str(x).unwrap());
    let n = it1.next().unwrap();
    let mut na = n;
    let mut j = 0;
    for _ in 0..9 {
        j += na % 10u32;
        na /= 10;
    }
    if n % j == 0 {
        println!("Yes");
    } else {
        println!("No");
    }
}


Score : <var>100</var> points

Problem Statement

You are given two positive integers <var>a</var> and <var>b</var>.
Let <var>x</var> be the average of <var>a</var> and <var>b</var>.
Print <var>x</var> rounded up to the nearest integer.

Constraints

<var>a</var> and <var>b</var> are integers.

<var>1 \leq a, b \leq 100</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print <var>x</var> rounded up to the nearest integer.

Sample Input 1

1 3

Sample Output 1

2

The average of <var>1</var> and <var>3</var> is <var>2.0</var>, and it will be rounded up to the nearest integer, <var>2</var>.

Sample Input 2

7 4

Sample Output 2

6

The average of <var>7</var> and <var>4</var> is <var>5.5</var>, and it will be rounded up to the nearest integer, <var>6</var>.

Sample Input 3

5 5

Sample Output 3

5

int solution(void) {
  int a = 0;
  int b = 0;
  int answer = 0;
  scanf("%d %d", &a, &b);
  answer = (a + b) / 2;
  if ((a + b) % 2 != 0) {
    answer++;
  }
  printf("%d\n", answer);
  return 0;
}

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


Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.You are a new applicant for his company. Boboniu will test you with the following chess question:Consider a $$$n\times m$$$ grid (rows are numbered from $$$1$$$ to $$$n$$$, and columns are numbered from $$$1$$$ to $$$m$$$). You have a chess piece, and it stands at some cell $$$(S_x,S_y)$$$ which is not on the border (i.e. $$$2 \le S_x \le n-1$$$ and $$$2 \le S_y \le m-1$$$).From the cell $$$(x,y)$$$, you can move your chess piece to $$$(x,y')$$$ ($$$1\le y'\le m, y' \neq y$$$) or $$$(x',y)$$$ ($$$1\le x'\le n, x'\neq x$$$). In other words, the chess piece moves as a rook. From the cell, you can move to any cell on the same row or column.Your goal is to visit each cell exactly once. Can you find a solution?Note that cells on the path between two adjacent cells in your route are not counted as visited, and it is not required to return to the starting point.

int solution() {
  int x;
  int y;
  int n;
  int m;
  scanf("%d%d%d%d", &n, &m, &x, &y);
  printf("%d %d\n", x, y);
  printf("%d %d\n", 1, y);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m && i % 2; j++) {
      if ((i == x && j == y) || (i == 1 && j == y)) {
        continue;
      }
      printf("%d %d\n", i, j);
    }
    for (int j = m; j >= 1 && !(i % 2); j--) {
      if (i == x && j == y) {
        continue;
      }
      printf("%d %d\n", i, j);
    }
  }
  return 0;
}

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

    let (n, m, mut sx, mut sy): (usize, usize, usize, usize) = {
        let mut buf = String::new();
        reader.read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };

    sx -= 1;
    sy -= 1;
    for i in 0..n {
        for j in 0..m {
            writeln!(writer, "{} {}", (sx + i) % n + 1, (sy + j) % m + 1,).unwrap();
        }
        sy = (sy + m - 1) % m;
    }
}


Score : <var>500</var> points

Problem Statement

AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side <var>K</var>.
Here, a checked pattern of side <var>K</var> is a pattern where each square is painted black or white so that each connected component of each color is a <var>K</var> <var>×</var> <var>K</var> square.
Below is an example of a checked pattern of side <var>3</var>:

AtCoDeer has <var>N</var> desires.
The <var>i</var>-th desire is represented by <var>x_i</var>, <var>y_i</var> and <var>c_i</var>.
If <var>c_i</var> is B, it means that he wants to paint the square <var>(x_i,y_i)</var> black; if <var>c_i</var> is W, he wants to paint the square <var>(x_i,y_i)</var> white.
At most how many desires can he satisfy at the same time?

Constraints

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

<var>1</var> <var>≤</var> <var>K</var> <var>≤</var> <var>1000</var>

<var>0</var> <var>≤</var> <var>x_i</var> <var>≤</var> <var>10^9</var>

<var>0</var> <var>≤</var> <var>y_i</var> <var>≤</var> <var>10^9</var>

If <var>i</var> <var>≠</var> <var>j</var>, then <var>(x_i,y_i)</var> <var>≠</var> <var>(x_j,y_j)</var>.

<var>c_i</var> is B or W.

<var>N</var>, <var>K</var>, <var>x_i</var> and <var>y_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>x_1</var> <var>y_1</var> <var>c_1</var>
<var>x_2</var> <var>y_2</var> <var>c_2</var>
<var>:</var>
<var>x_N</var> <var>y_N</var> <var>c_N</var>

Output

Print the maximum number of desires that can be satisfied at the same time.

Sample Input 1

4 3
0 1 W
1 2 W
5 3 B
5 4 B

Sample Output 1

4

He can satisfy all his desires by painting as shown in the example above.

Sample Input 2

2 1000
0 0 B
0 1 W

Sample Output 2

2

Sample Input 3

6 2
1 2 B
2 1 W
2 2 B
1 0 B
0 6 W
4 5 W

Sample Output 3

4

int solution(void) {

  int n;
  int m;
  int x;
  int y;
  char c;
  static int map[2010][2010];
  static int ruiseki[2010][2010];
  static int ruisekitemp[2010][2010];

  int i;
  int j;
  int k;
  int l;
  int flag = 0;
  int ans = 0;
  int count = 0;
  int sum = 0;
  int temp;
  int temp1;
  int temp2;

  int len;

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

  for (i = 0; i <= 2000; i++) {
    for (j = 0; j <= 2000; j++) {
      map[i][j] = 0;
    }
  }

  for (i = 0; i < n; i++) {
    scanf("%d %d %c", &x, &y, &c);
    if (c == 'W') {
      x = x + m;
    }
    x = x % (2 * m);
    y = y % (2 * m);
    map[x][y] = map[x][y] + 1;
  }

  for (i = 0; i < 2 * m; i++) {
    for (j = 0; j < 2 * m; j++) {
      if (j == 0) {
        ruisekitemp[i][0] = map[i][0];
      } else {
        ruisekitemp[i][j] = ruisekitemp[i][j - 1] + map[i][j];
      }
    }
  }

  for (j = 0; j < 2 * m; j++) {
    for (i = 0; i < 2 * m; i++) {
      if (i == 0) {
        ruiseki[0][j] = ruisekitemp[0][j];
      } else {
        ruiseki[i][j] = ruiseki[i - 1][j] + ruisekitemp[i][j];
      }
    }
  }

  for (i = 0; i < m; i++) {
    for (j = 0; j < m; j++) {
      temp = 0;
      temp = temp + ruiseki[i + m][j + m] - ruiseki[i + m][j] -
             ruiseki[i][j + m] + ruiseki[i][j];
      temp = temp + ruiseki[i][j];
      temp = temp + ruiseki[(2 * m) - 1][(2 * m) - 1] -
             ruiseki[i + m][(2 * m) - 1] - ruiseki[(2 * m) - 1][j + m] +
             ruiseki[i + m][j + m];
      temp = temp + ruiseki[(2 * m) - 1][j] - ruiseki[i + m][j];
      temp = temp + ruiseki[i][(2 * m) - 1] - ruiseki[i][j + m];
      if (temp < n - temp) {
        temp = n - temp;
      }
      if (temp > ans) {
        ans = temp;
      }
    }
  }

  printf("%d", ans);

  return 0;
}

fn solution() {
    input! {
      n: usize,
      k: usize,
      query: [(usize, usize, chars); n],
    }
    let m = k * 2;
    let mut field = vec![vec![0i64; k * 3]; k * 2];
    for &(x, y, ref c) in &query {
        let y = match *c.first().unwrap() {
            'B' => y,
            _ => y + k,
        };
        let (x, y) = if (x % m) < k {
            (x % m, y % m)
        } else {
            ((x + k) % m, (y + k) % m)
        };
        field[y][x] += 1;
        field[(y + k) % m][x + k] += 1;
        field[y][x + m] += 1;
    }
    for i in 1..2 * k {
        for j in 0..3 * k {
            field[i][j] += field[i - 1][j];
        }
    }
    for i in 0..2 * k {
        for j in 1..3 * k {
            field[i][j] += field[i][j - 1];
        }
    }
    let mut ans = 0;
    for i in 0..k {
        for j in 0..2 * k {
            ans = cmp::max(
                ans,
                field[i + k][j + k] - field[i][j + k] - field[i + k][j] + field[i][j],
            );
        }
    }

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


You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.

int solution() {
  int x;
  int y;
  int n;
  int N = 0;

  scanf("%d", &N);

  while (N > 0) {

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

    if (x == 0) {
      printf("%s\n", "x is zero, no answer");
      return -1;
    }

    int k = (n / x) * x;

    if (k + y <= n) {

      printf("%d\n", k + y);
    } else {

      printf("%d\n", k - x + y);
    }

    N--;
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut count: u16 = line.trim().parse().unwrap();
    while count > 0 {
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        let module: i32 = iter.next().unwrap().parse().unwrap();
        let least: i32 = iter.next().unwrap().parse().unwrap();
        let max: i32 = iter.next().unwrap().parse().unwrap();
        let (mut whole, rest) = (max / module, max % module);
        if rest < least {
            whole -= 1;
        }
        println!("{}", module * whole + least);
        count -= 1;
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Initially all elements of $$$a$$$ are either $$$0$$$ or $$$1$$$. You need to process $$$q$$$ queries of two kinds:  1 x : Assign to $$$a_x$$$ the value $$$1 - a_x$$$.  2 k : Print the $$$k$$$-th largest value of the array. As a reminder, $$$k$$$-th largest value of the array $$$b$$$ is defined as following: Sort the array in the non-increasing order, return $$$k$$$-th element from it. For example, the second largest element in array $$$[0, 1, 0, 1]$$$ is $$$1$$$, as after sorting in non-increasing order it becomes $$$[1, 1, 0, 0]$$$, and the second element in this array is equal to $$$1$$$.

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

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

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

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

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

    let mut a = Vec::with_capacity(n);
    let mut nones = 0;
    a.extend(
        lines
            .next()
            .unwrap()
            .split_whitespace()
            .map(|s| s == "1")
            .inspect(|&a| {
                if a {
                    nones += 1;
                }
            }),
    );

    for _ in 0..q {
        let s = lines.next().unwrap();
        let mut it = s.split_whitespace();

        let t = it.next().unwrap();
        match t {
            "1" => {
                let x: usize = it.next().unwrap().parse::<usize>().unwrap() - 1;
                nones += if a[x] { -1 } else { 1 };
                a[x] = !a[x];
            }
            _ => {
                let k: i64 = it.next().unwrap().parse().unwrap();
                let ans = if k <= nones { 1 } else { 0 };
                writeln!(&mut output, "{}", ans).unwrap();
            }
        }
    }
}


Standard Deviation

  You have final scores of an examination for <var>n</var> students. Calculate standard deviation of the scores <var>s1</var>, <var>s2</var> ... <var>sn</var>.

The variance α2 is defined by

α2  = (∑ni=1(si - m)2)/n

  where <var>m</var> is an average of <var>si</var>.

  The standard deviation of the scores is the square root of their variance.

Input

  The input consists of multiple datasets. Each dataset is given in the following format:

<var>n</var>
<var>s</var>1 <var>s</var>2 ... <var>s</var><var>n</var>

  The input ends with single zero for <var>n</var>.

Output

  For each dataset, print the standard deviation in a line. The output should not contain an absolute error greater than 10-4.

Constraints

<var>n</var> ≤ 1000

0 ≤ <var>si</var> ≤ 100

Sample Input

5
70 80 100 90 20
3
80 80 80
0

Sample Output

27.85677655
0.00000000

int solution(void) {
  int i;
  double n;
  double s[1000] = {0};
  double a = 0;
  double m = 0;
  scanf("%lf", &n);

  while (n != 0) {

    for (i = 0; i < n; i++) {
      scanf("%lf", &s[i]);

      m = m + s[i];
    }

    m = m / n;

    for (i = 0; i < n; i++) {
      a = a + (s[i] - m) * (s[i] - m);

      s[i] = 0;
    }

    printf("%lf\n", sqrt(a / n));

    a = 0;
    m = 0;

    scanf("%lf", &n);
  }
  return 0;
}

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

    loop {
        let n = lines.next().unwrap().unwrap().parse::<f64>().unwrap();

        if n == 0. {
            break;
        }

        let v = lines
            .next()
            .unwrap()
            .unwrap()
            .split_whitespace()
            .map(|x| x.parse::<f64>().unwrap())
            .collect::<Vec<_>>();

        let average = v.iter().sum::<f64>() / n;
        let deviation = v.iter().map(|x| (x - average).powi(2)).sum::<f64>() / n;

        println!("{}", deviation.sqrt());
    }
}


There are $$$n$$$ piles of sand where the $$$i$$$-th pile has $$$a_i$$$ blocks of sand. The $$$i$$$-th pile is called too tall if $$$1 < i < n$$$ and $$$a_i > a_{i-1} + a_{i+1}$$$. That is, a pile is too tall if it has more sand than its two neighbours combined. (Note that piles on the ends of the array cannot be too tall.)You are given an integer $$$k$$$. An operation consists of picking $$$k$$$ consecutive piles of sand and adding one unit of sand to them all. Formally, pick $$$1 \leq l,r \leq n$$$ such that $$$r-l+1=k$$$. Then for all $$$l \leq i \leq r$$$, update $$$a_i \gets a_i+1$$$.What is the maximum number of piles that can simultaneously be too tall after some (possibly zero) operations?

fn solution() {
    let mut content = String::new();
    io::stdin()
        .read_to_string(&mut content)
        .expect("Unable to read from stdin");

    let mut lines = content.lines();
    let num_tests: usize = lines.next().unwrap().parse().unwrap();
    for _ in 0..num_tests {
        let arr: Vec<usize> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse::<usize>().unwrap())
            .collect();
        let n = arr[0];
        let k = arr[1];
        let a: Vec<usize> = lines
            .next()
            .unwrap()
            .split(" ")
            .map(|token| token.parse::<usize>().unwrap())
            .collect();
        if k == 1 {
            println!("{}", (n - 1) / 2);
        } else {
            let mut result = 0usize;
            for i in 1..n - 1 {
                if a[i] > a[i - 1] + a[i + 1] {
                    result += 1;
                }
            }
            println!("{result}");
        }
    }
}


You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries.

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");
    let t = input.trim().parse::<u16>().unwrap();
    for _ in 0..t {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let n = input.trim().parse::<usize>().unwrap();

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let mut sticks: Vec<u32> = input
            .split_whitespace()
            .map(|n| n.parse().expect("invalid input"))
            .collect();
        sticks.sort();

        let prod = sticks[0] * sticks[4 * n - 1];
        let mut possible = true;
        for (i, ri) in (0..(2 * n))
            .step_by(2)
            .zip(((2 * n)..(4 * n)).rev().step_by(2))
        {
            if sticks[i] != sticks[i + 1]
                || sticks[ri] != sticks[ri - 1]
                || sticks[i] * sticks[ri] != prod
            {
                possible = false;
                break;
            }
        }
        println!("{}", if possible { "YES" } else { "NO" });
    }
}


Score : <var>400</var> points

Problem Statement

You are given an integer <var>N</var>. Find the number of strings of length <var>N</var> that satisfy the following conditions, modulo <var>10^9+7</var>:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

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

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

Constraints

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of strings of length <var>N</var> that satisfy the following conditions, modulo <var>10^9+7</var>.

Sample Input 1

3

Sample Output 1

61

There are <var>4^3 = 64</var> strings of length <var>3</var> that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is <var>64 - 3 = 61</var>.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

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


You are given two matrices $$$A$$$ and $$$B$$$. Each matrix contains exactly $$$n$$$ rows and $$$m$$$ columns. Each element of $$$A$$$ is either $$$0$$$ or $$$1$$$; each element of $$$B$$$ is initially $$$0$$$.You may perform some operations with matrix $$$B$$$. During each operation, you choose any submatrix of $$$B$$$ having size $$$2 \times 2$$$, and replace every element in the chosen submatrix with $$$1$$$. In other words, you choose two integers $$$x$$$ and $$$y$$$ such that $$$1 \le x < n$$$ and $$$1 \le y < m$$$, and then set $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ and $$$B_{x + 1, y + 1}$$$ to $$$1$$$.Your goal is to make matrix $$$B$$$ equal to matrix $$$A$$$. Two matrices $$$A$$$ and $$$B$$$ are equal if and only if every element of matrix $$$A$$$ is equal to the corresponding element of matrix $$$B$$$.Is it possible to make these matrices equal? If it is, you have to come up with a sequence of operations that makes $$$B$$$ equal to $$$A$$$. Note that you don't have to minimize the number of operations.

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

    let mut buf = String::new();
    stdin.read_line(&mut buf).unwrap();
    let mut w = buf.split_whitespace();
    let (n, m): (usize, usize) = (
        w.next().unwrap().parse().unwrap(),
        w.next().unwrap().parse().unwrap(),
    );
    let mut eta = vec![vec![false; m]; n];
    for i in 0..n {
        buf.clear();
        stdin.read_line(&mut buf).unwrap();
        let v = buf
            .split_whitespace()
            .map(|w| w.parse::<i64>().unwrap())
            .collect::<Vec<_>>();
        for j in 0..m {
            eta[i][j] = v[j] == 1;
        }
    }
    let mut maj = vec![vec![false; m]; n];
    let mut ans = Vec::new();
    for i in 0..n - 1 {
        for j in 0..m - 1 {
            if eta[i][j] && eta[i + 1][j] && eta[i][j + 1] && eta[i + 1][j + 1] {
                maj[i][j] = true;
                maj[i][j + 1] = true;
                maj[i + 1][j] = true;
                maj[i + 1][j + 1] = true;
                ans.push((i, j));
            }
        }
    }
    for i in 0..n {
        for j in 0..m {
            if eta[i][j] && !maj[i][j] {
                println!("-1");
                return;
            }
        }
    }
    println!("{}", ans.len());
    for a in ans {
        println!("{} {}", a.0 + 1, a.1 + 1);
    }
}


After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).  You are given an array $$$h_1, h_2, \dots, h_n$$$, where $$$h_i$$$ is the height of the $$$i$$$-th mountain, and $$$k$$$ — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $$$h_i$$$):   if $$$h_i \ge h_{i + 1}$$$, the boulder will roll to the next mountain;  if $$$h_i < h_{i + 1}$$$, the boulder will stop rolling and increase the mountain height by $$$1$$$ ($$$h_i = h_i + 1$$$);  if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $$$k$$$-th boulder or determine that it will fall into the waste collection system.

fn solution() {
    let k = std::io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i32>()
        .unwrap();
    for _ele in 0..k {
        let mut l = String::new();
        std::io::stdin().read_line(&mut l).unwrap();
        let mut l = l
            .trim()
            .split(" ")
            .flat_map(str::parse::<i32>)
            .collect::<Vec<i32>>();
        let mut m = String::new();
        std::io::stdin().read_line(&mut m).unwrap();
        let mut m = m
            .trim()
            .split(" ")
            .flat_map(str::parse::<i32>)
            .collect::<Vec<i32>>();
        let _o_vals: Vec<i32> = vec![];
        let swch = true;
        let mut ans_pos: Vec<i32> = vec![];
        'rest: while swch {
            let j = m.clone();
            'jest: for (index, its) in m.iter_mut().enumerate() {
                if index == j.len() - 1 {
                    break 'rest;
                }
                if *its < j[index + 1] && l[1] > 0 {
                    *its += 1;
                    l[1] -= 1;
                    ans_pos.push(index as i32 + 1);
                    break 'jest;
                }
            }
        }
        if l[1] > 0 {
            ans_pos.push(-1)
        };
        println!("{:?}", ans_pos[ans_pos.len() - 1]);
    }
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> boxes arranged in a row from left to right. The <var>i</var>-th box from the left contains <var>A_i</var> candies.

You will take out the candies from some consecutive boxes and distribute them evenly to <var>M</var> children.

Such being the case, find the number of the pairs <var>(l, r)</var> that satisfy the following:

<var>l</var> and <var>r</var> are both integers and satisfy <var>1 \leq l \leq r \leq N</var>.

<var>A_l + A_{l+1} + ... + A_r</var> is a multiple of <var>M</var>.

Constraints

All values in input are integers.

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

<var>2 \leq M \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>M</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>

Output

Print the number of the pairs <var>(l, r)</var> that satisfy the conditions.

Note that the number may not fit into a <var>32</var>-bit integer type.

Sample Input 1

3 2
4 1 5

Sample Output 1

3

The sum <var>A_l + A_{l+1} + ... + A_r</var> for each pair <var>(l, r)</var> is as follows:

Sum for <var>(1, 1)</var>: <var>4</var>

Sum for <var>(1, 2)</var>: <var>5</var>

Sum for <var>(1, 3)</var>: <var>10</var>

Sum for <var>(2, 2)</var>: <var>1</var>

Sum for <var>(2, 3)</var>: <var>6</var>

Sum for <var>(3, 3)</var>: <var>5</var>

Among these, three are multiples of <var>2</var>.

Sample Input 2

13 17
29 7 5 7 9 51 7 13 8 55 42 9 81

Sample Output 2

6

Sample Input 3

10 400000000
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 3

25

int solution() {
  int n;
  int m;
  scanf("%d%d", &n, &m);
  int a[n];
  int i;
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  long long int ans = 0;
  int tmp[n + 1];
  tmp[0] = 0;
  int j = 0;
  for (i = 0; i < n; i++) {
    tmp[i + 1] = (tmp[i] + a[i]) % m;
    for (j = 0; j <= i; j++) {
      if (tmp[i + 1] == tmp[j]) {
        ans++;
      }
    }
  }
  printf("%lld\n", ans);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut s = String::new();
    let mut nums: Vec<i64> = Vec::new();
    {
        stdin.read_line(&mut s).ok();
        let it = s.split_whitespace();
        for arg in it {
            nums.push(i64::from_str(arg).expect("e1"));
        }
    }
    let _n = nums[0];
    let m = nums[1];
    let mut a: Vec<i64> = Vec::new();
    s = String::new();
    stdin.read_line(&mut s).ok();
    let it = s.split_whitespace();
    for arg in it {
        a.push(i64::from_str(arg).expect("e2") % m);
    }
    let mut sum: Vec<i64> = Vec::new();
    sum.push(0);
    let mut s: i64 = 0;
    for i in 0..a.len() {
        s += a[i];
        s %= m;
        sum.push(s);
    }
    sum.sort();
    let mut ans: i64 = 0;
    let mut temp = sum[0];
    let mut c = 1;
    for i in 1..sum.len() {
        if temp == sum[i] {
            c += 1;
        } else {
            ans += c * (c - 1) / 2;
            c = 1;
            temp = sum[i];
        }
    }
    ans += c * (c - 1) / 2;
    println!("{}", ans);
}


Score : <var>400</var> points

Problem Statement

There are <var>N</var> towns located in a line, conveniently numbered <var>1</var> through <var>N</var>. Takahashi the merchant is going on a travel from town <var>1</var> to town <var>N</var>, buying and selling apples.

Takahashi will begin the travel at town <var>1</var>, with no apple in his possession. The actions that can be performed during the travel are as follows:

Move: When at town <var>i</var> (<var>i < N</var>), move to town <var>i + 1</var>.

Merchandise: Buy or sell an arbitrary number of apples at the current town. Here, it is assumed that one apple can always be bought and sold for <var>A_i</var> yen (the currency of Japan) at town <var>i</var> (<var>1 ≦ i ≦ N</var>), where <var>A_i</var> are distinct integers. Also, you can assume that he has an infinite supply of money.

For some reason, there is a constraint on merchandising apple during the travel: the sum of the number of apples bought and the number of apples sold during the whole travel, must be at most <var>T</var>. (Note that a single apple can be counted in both.)

During the travel, Takahashi will perform actions so that the profit of the travel is maximized. Here, the profit of the travel is the amount of money that is gained by selling apples, minus the amount of money that is spent on buying apples. Note that we are not interested in apples in his possession at the end of the travel.

Aoki, a business rival of Takahashi, wants to trouble Takahashi by manipulating the market price of apples. Prior to the beginning of Takahashi's travel, Aoki can change <var>A_i</var> into another arbitrary non-negative integer <var>A_i'</var> for any town <var>i</var>, any number of times. The cost of performing this operation is <var>|A_i - A_i'|</var>. After performing this operation, different towns may have equal values of <var>A_i</var>.

Aoki's objective is to decrease Takahashi's expected profit by at least <var>1</var> yen. Find the minimum total cost to achieve it. You may assume that Takahashi's expected profit is initially at least <var>1</var> yen.

Constraints

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

<var>1 ≦ A_i ≦ 10^9</var> (<var>1 ≦ i ≦ N</var>)

<var>A_i</var> are distinct.

<var>2 ≦ T ≦ 10^9</var>

In the initial state, Takahashi's expected profit is at least <var>1</var> yen.

Input

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

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

Output

Print the minimum total cost to decrease Takahashi's expected profit by at least <var>1</var> yen.

Sample Input 1

3 2
100 50 200

Sample Output 1

1

In the initial state, Takahashi can achieve the maximum profit of <var>150</var> yen as follows:

Move from town <var>1</var> to town <var>2</var>.

Buy one apple for <var>50</var> yen at town <var>2</var>.

Move from town <var>2</var> to town <var>3</var>.

Sell one apple for <var>200</var> yen at town <var>3</var>.

If, for example, Aoki changes the price of an apple at town <var>2</var> from <var>50</var> yen to <var>51</var> yen, Takahashi will not be able to achieve the profit of <var>150</var> yen. The cost of performing this operation is <var>1</var>, thus the answer is <var>1</var>.

There are other ways to decrease Takahashi's expected profit, such as changing the price of an apple at town <var>3</var> from <var>200</var> yen to <var>199</var> yen.

Sample Input 2

5 8
50 30 40 10 20

Sample Output 2

2

Sample Input 3

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

Sample Output 3

2

int solution(void) {
  int n;
  int t;
  int max = 0;
  int min = INT_MAX;
  int ans = 0;
  scanf("%d%d", &n, &t);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  for (int i = 0; i < n; i++) {
    if (min > a[i]) {
      min = a[i];
    }
    if (max < a[i] - min) {
      max = a[i] - min;
    }
  }
  min = INT_MAX;
  for (int i = 0; i < n; i++) {
    if (min > a[i]) {
      min = a[i];
    }
    if (max == a[i] - min) {
      ans++;
    }
  }
  printf("%d\n", ans);
  return 0;
}

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

    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();

    let (_, res, _) = s.trim().split(' ').rev().fold((0, 0, 0), |(v, n, x), y| {
        let z = y.parse().unwrap();
        let d = x - z;

        if z > x {
            (v, n, z)
        } else if v < d {
            (d, 1, x)
        } else if v == d {
            (v, n + 1, x)
        } else {
            (v, n, x)
        }
    });

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


Michael and Joe are playing a game. The game is played on a grid with $$$n$$$ rows and $$$m$$$ columns, filled with distinct integers. We denote the square on the $$$i$$$-th ($$$1\le i\le n$$$) row and $$$j$$$-th ($$$1\le j\le m$$$) column by $$$(i, j)$$$ and the number there by $$$a_{ij}$$$.Michael starts by saying two numbers $$$h$$$ ($$$1\le h \le n$$$) and $$$w$$$ ($$$1\le w \le m$$$). Then Joe picks any $$$h\times w$$$ subrectangle of the board (without Michael seeing).Formally, an $$$h\times w$$$ subrectangle starts at some square $$$(a,b)$$$ where $$$1 \le a \le n-h+1$$$ and $$$1 \le b \le m-w+1$$$. It contains all squares $$$(i,j)$$$ for $$$a \le i \le a+h-1$$$ and $$$b \le j \le b+w-1$$$.    Possible move by Joe if Michael says $$$3\times 2$$$ (with maximum of $$$15$$$). Finally, Michael has to guess the maximum number in the subrectangle. He wins if he gets it right.Because Michael doesn't like big numbers, he wants the area of the chosen subrectangle (that is, $$$h \cdot w$$$), to be as small as possible, while still ensuring that he wins, not depending on Joe's choice. Help Michael out by finding this minimum possible area. It can be shown that Michael can always choose $$$h, w$$$ for which he can ensure that he wins.

int solution() {
  int t = 0;
  int i = 0;
  int j = 0;
  int k = 0;
  int n = 0;
  int m = 0;
  int a[40];
  int x[40];
  int temporary = 0;
  int key = 0;
  int var1 = 0;
  int var2 = 0;

  scanf("%d\n", &t);
  i = t;

  while (i > 0) {
    scanf("%d %d\n", &n, &m);

    for (j = 0; j < n; j++) {
      scanf("%d", &a[j]);
      x[j] = 0;
      for (k = 1; k < m; k++) {
        scanf("%d", &temporary);
        if (temporary > a[j]) {
          a[j] = temporary;
          x[j] = k;
        }
      }
      scanf("\n");
    }

    key = a[0];
    var2 = 0;
    var1 = x[0];

    for (j = 1; j < n; j++) {
      if (a[j] > key) {
        key = a[j];
        var1 = x[j];
        var2 = j;
      }
    }

    var1 = var1 + 1;

    if ((m - var1 + 1) > (var1)) {
      var1 = (m - var1 + 1);
    }

    var2 = var2 + 1;

    if ((n - var2 + 1) > (var2)) {
      var2 = (n - var2 + 1);
    }

    printf("%d\n", (var1 * var2));
    i = i - 1;
  }
}

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

    let (mut n, mut m): (i32, i32);
    let mut num: Vec<i32>;
    let (mut best, mut best_i, mut best_j): (i32, i32, i32);

    stdin.read_line(&mut input).expect("bruh");
    let tests: i32 = input.trim().parse::<i32>().unwrap();

    for _ in 0..tests {
        input.clear();
        stdin.read_line(&mut input).expect("bruh");
        num = input
            .trim()
            .split(' ')
            .map(|x| x.parse::<i32>().unwrap())
            .collect();

        n = num[0];
        m = num[1];
        best = i32::MIN;
        best_i = 1;
        best_j = 1;

        for i in 0..n {
            input.clear();
            stdin.read_line(&mut input).expect("bruh");
            num = input
                .trim()
                .split(' ')
                .map(|x| x.parse::<i32>().unwrap())
                .collect();
            if n == 0 {
                best = num[0];
                best_i = 1;
                best_j = 1;
            }
            for j in 0..num.len() {
                if num[j] > best {
                    best = num[j];
                    best_i = i + 1;
                    best_j = j as i32 + 1;
                }
            }
        }
        println!(
            "{}",
            cmp::max(best_i, n - best_i + 1) * cmp::max(best_j, m - best_j + 1)
        );
    }
}


Score : <var>500</var> points

Problem Statement

There are <var>N</var> cards placed face down in a row. On each card, an integer <var>1</var> or <var>2</var> is written.

Let <var>A_i</var> be the integer written on the <var>i</var>-th card.

Your objective is to guess <var>A_1, A_2, ..., A_N</var> correctly.

You know the following facts:

For each <var>i = 1, 2, ..., M</var>, the value <var>A_{X_i} + A_{Y_i} + Z_i</var> is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer <var>A_i</var> written on it. The cost of using this magic is <var>1</var>.

What is the minimum cost required to determine all of <var>A_1, A_2, ..., A_N</var>?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

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

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

<var>1 \leq X_i < Y_i \leq N</var>

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

The pairs <var>(X_i, Y_i)</var> are distinct.

There is no contradiction in input. (That is, there exist integers <var>A_1, A_2, ..., A_N</var> that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>X_1</var> <var>Y_1</var> <var>Z_1</var>
<var>X_2</var> <var>Y_2</var> <var>Z_2</var>
<var>\vdots</var>
<var>X_M</var> <var>Y_M</var> <var>Z_M</var>

Output

Print the minimum total cost required to determine all of <var>A_1, A_2, ..., A_N</var>.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of <var>A_1, A_2, A_3</var> by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999

int solution() {
  int i;
  int u;
  int w;
  int z;
  int N;
  int M;
  scanf("%d %d", &N, &M);
  list **adj = (list **)malloc(sizeof(list *) * (N + 1));
  list *d = (list *)malloc(sizeof(list) * M * 2);
  for (i = 1; i <= N; i++) {
    adj[i] = NULL;
  }
  for (i = 0; i < M; i++) {
    scanf("%d %d %d", &u, &w, &z);
    d[i * 2].v = w;
    d[(i * 2) + 1].v = u;
    d[i * 2].next = adj[u];
    d[(i * 2) + 1].next = adj[w];
    adj[u] = &(d[i * 2]);
    adj[w] = &(d[(i * 2) + 1]);
  }

  int k;
  int flag[100001] = {};
  int q[100001];
  int head;
  int tail;
  list *p;
  for (i = 1, k = 0; i <= N; i++) {
    if (flag[i] != 0) {
      continue;
    }
    flag[i] = ++k;
    q[0] = i;
    for (head = 0, tail = 1; head < tail; head++) {
      for (p = adj[q[head]]; p != NULL; p = p->next) {
        if (flag[p->v] == 0) {
          flag[p->v] = k;
          q[tail++] = p->v;
        }
      }
    }
  }

  printf("%d\n", k);
  fflush(stdout);
  return 0;
}

fn solution() {
    input! {
        n: usize,
        m: usize,
        xyz: [(usize1, usize1, usize); m]
    }
    let mut graph = vec![vec![]; n];
    for &(x, y, _) in &xyz {
        graph[x].push(y);
        graph[y].push(x);
    }
    let mut count = 0;
    let mut dist = vec![false; n];

    for i in 0..n {
        if dist[i] {
            continue;
        }
        dist[i] = true;
        count += 1;
        let mut queue = VecDeque::new();
        queue.push_back(i);
        while let Some(x) = queue.pop_front() {
            for &p in &graph[x] {
                if dist[p] {
                    continue;
                }
                dist[p] = true;
                queue.push_back(p);
            }
        }
    }
    println!("{}", count);
}


You're given an array of $$$n$$$ integers between $$$0$$$ and $$$n$$$ inclusive.In one operation, you can choose any element of the array and replace it by the MEX of the elements of the array (which may change after the operation).For example, if the current array is $$$[0, 2, 2, 1, 4]$$$, you can choose the second element and replace it by the MEX of the present elements  — $$$3$$$. Array will become $$$[0, 3, 2, 1, 4]$$$.You must make the array non-decreasing, using at most $$$2n$$$ operations.It can be proven that it is always possible. Please note that you do not have to minimize the number of operations. If there are many solutions, you can print any of them. –An array $$$b[1 \ldots n]$$$ is non-decreasing if and only if $$$b_1 \le b_2 \le \ldots \le b_n$$$.The MEX (minimum excluded) of an array is the smallest non-negative integer that does not belong to the array. For instance:  The MEX of $$$[2, 2, 1]$$$ is $$$0$$$, because $$$0$$$ does not belong to the array.  The MEX of $$$[3, 1, 0, 1]$$$ is $$$2$$$, because $$$0$$$ and $$$1$$$ belong to the array, but $$$2$$$ does not.  The MEX of $$$[0, 3, 1, 2]$$$ is $$$4$$$ because $$$0$$$, $$$1$$$, $$$2$$$ and $$$3$$$ belong to the array, but $$$4$$$ does not. It's worth mentioning that the MEX of an array of length $$$n$$$ is always between $$$0$$$ and $$$n$$$ inclusive.

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 mut xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let mut ans: Vec<usize> = Vec::new();
        for _ in 0..(2 * n) {
            let mut bs: Vec<bool> = vec![false; n + 1];
            let mut sorted = true;
            bs[xs[0]] = true;
            for i in 1..n {
                bs[xs[i]] = true;
                sorted = sorted && xs[i - 1] <= xs[i];
            }
            let k = bs.iter().position(|b| !b).unwrap();
            if k == n {
                if sorted {
                    break;
                } else {
                    for i in 0..n {
                        if xs[i] != i {
                            xs[i] = n;
                            ans.push(i + 1);
                            break;
                        }
                    }
                }
            } else {
                for i in k..n {
                    if xs[i] != i {
                        xs[i] = k;
                        ans.push(i + 1);
                        break;
                    }
                }
            }
        }
        println!("{}", ans.len());
        for i in 0..ans.len() {
            print!("{} ", ans[i]);
        }
        println!();
    }
}


Score : <var>400</var> points

Problem Statement

Snuke has a string <var>S</var> consisting of three kinds of letters: a, b and c.

He has a phobia for palindromes, and wants to permute the characters in <var>S</var> so that <var>S</var> will not contain a palindrome of length <var>2</var> or more as a substring. Determine whether this is possible.

Constraints

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

<var>S</var> consists of a, b and c.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If the objective is achievable, print YES; if it is unachievable, print NO.

Sample Input 1

abac

Sample Output 1

YES

As it stands now, <var>S</var> contains a palindrome aba, but we can permute the characters to get acba, for example, that does not contain a palindrome of length <var>2</var> or more.

Sample Input 2

aba

Sample Output 2

NO

Sample Input 3

babacccabab

Sample Output 3

YES

int solution() {
  int S_length = 0;
  int count_a = 0;
  int count_b = 0;
  int count_c = 0;
  char S[100001];
  scanf("%s", S);
  while (S[S_length] != '\0') {
    S_length++;
  }

  for (int i = 0; i < S_length; i++) {
    switch (S[i]) {
    case 'a':
      count_a++;
      break;
    case 'b':
      count_b++;
      break;
    case 'c':
      count_c++;
      break;
    }
  }

  if (abs(count_a - count_b) < 2 && abs(count_a - count_c) < 2 &&
      abs(count_b - count_c) < 2) {
    puts("YES");
  } else {
    puts("NO");
  }

  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 s: Vec<char> = itr.next().unwrap().chars().collect();
    let n = s.len();
    if n == 1 {
        println!("YES");
    } else if n == 2 {
        if s[0] == s[1] {
            println!("NO");
        } else {
            println!("YES");
        }
    } else {
        let mut na = 0;
        let mut nb = 0;
        let mut nc = 0;
        for &c in s.iter() {
            if c == 'a' {
                na += 1;
            } else if c == 'b' {
                nb += 1;
            } else {
                nc += 1;
            }
        }
        let min = min(na, min(nb, nc));
        na -= min;
        nb -= min;
        nc -= min;
        if max(na, max(nb, nc)) > 1 {
            println!("NO");
        } else {
            println!("YES");
        }
    }
}


A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.

fn solution() {
    let mut guess = String::new();
    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");
    let guess: u32 = match guess.trim().parse() {
        Ok(number) => number,
        Err(_) => 0,
    };
    if !guess.is_multiple_of(2) {
        println!("-1");
        return;
    }
    let vec: Vec<u32> = (0..guess).collect();

    if vec.len() == 1 || vec.is_empty() {
        println!("-1");
        return;
    }
    for i in 1..vec.len() + 1 {
        if i % 2 == 0 {
            println!("{}", i - 1);
        } else {
            println!("{}", i + 1);
        }
    }
}


You are given a string $$$s=s_1s_2\dots s_n$$$ of length $$$n$$$, which only contains digits $$$1$$$, $$$2$$$, ..., $$$9$$$.A substring $$$s[l \dots r]$$$ of $$$s$$$ is a string $$$s_l s_{l + 1} s_{l + 2} \ldots s_r$$$. A substring $$$s[l \dots r]$$$ of $$$s$$$ is called even if the number represented by it is even. Find the number of even substrings of $$$s$$$. Note, that even if some substrings are equal as strings, but have different $$$l$$$ and $$$r$$$, they are counted as different substrings.

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

    let sentence = &mut input.trim().chars();

    let mut outcome = usize::default();

    for counter in 0usize..amount {
        let letter = sentence.next().unwrap();

        let number = letter.to_digit(10).unwrap();

        if number.is_multiple_of(2) {
            outcome += counter + 1;
        }
    }

    println!("{}", &outcome);
}


A positive integer $$$x$$$ is called a power of two if it can be represented as $$$x = 2^y$$$, where $$$y$$$ is a non-negative integer. So, the powers of two are $$$1, 2, 4, 8, 16, \dots$$$.You are given two positive integers $$$n$$$ and $$$k$$$. Your task is to represent $$$n$$$ as the sum of exactly $$$k$$$ powers of two.

fn solution() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();

    let n = get!();
    let k = get!(usize);

    let mut p = n;
    let mut b = 1_i64;
    let mut bits = vec![];

    while p > 0 {
        if p & 1 != 0 {
            bits.push(b);
        }
        p >>= 1;
        b <<= 1;
    }

    bits.sort();

    let mut r = k;
    let mut ans = vec![];
    while r > 0 && !bits.is_empty() {
        if bits.len() == r {
            let e = bits.pop().unwrap();
            ans.push(e);
            r -= 1;
        } else {
            let e = bits.pop().unwrap();
            if e == 1 {
                ans.push(1);
                r -= 1;
            } else {
                bits.push(e / 2);
                bits.push(e / 2);
            }
        }
    }
    if r > 0 || !bits.is_empty() {
        println!("NO");
        return;
    }
    println!("YES");
    for i in 0..ans.len() {
        if i == 0 {
            print!("{}", ans[i]);
        } else {
            print!(" {}", ans[i]);
        }
    }
    println!();
}


The Berland language consists of words having exactly two letters. Moreover, the first letter of a word is different from the second letter. Any combination of two different Berland letters (which, by the way, are the same as the lowercase letters of Latin alphabet) is a correct word in Berland language.The Berland dictionary contains all words of this language. The words are listed in a way they are usually ordered in dictionaries. Formally, word $$$a$$$ comes earlier than word $$$b$$$ in the dictionary if one of the following conditions hold:  the first letter of $$$a$$$ is less than the first letter of $$$b$$$;  the first letters of $$$a$$$ and $$$b$$$ are the same, and the second letter of $$$a$$$ is less than the second letter of $$$b$$$. So, the dictionary looks like that:  Word $$$1$$$: ab  Word $$$2$$$: ac  ...  Word $$$25$$$: az  Word $$$26$$$: ba  Word $$$27$$$: bc  ...  Word $$$649$$$: zx  Word $$$650$$$: zy You are given a word $$$s$$$ from the Berland language. Your task is to find its index in the dictionary.

int solution(void) {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    char *array = (char *)malloc(2 * sizeof(char));
    scanf("%s", array);
    printf("%d\n", ((array[0] - 97) * 25) +
                       (array[0] > array[1] ? array[1] - 96 : array[1] - 97));
    free(array);
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).ok();
    let mut output = String::new();
    let mut input = input.split_ascii_whitespace();
    let t = input.next().unwrap().parse::<usize>().unwrap();
    for _ in 0..t {
        let s = input.next().unwrap().as_bytes();
        let a = s[0] - b'a';
        let b = s[1] - b'a';
        let mut index = a as u32 * 25 + b as u32;
        if b < a {
            index += 1;
        }
        writeln!(output, "{}", index).ok();
    }
    print!("{output}");
}


Score : <var>100</var> points

Problem Statement

This contest is CODEFESTIVAL, which can be shortened to the string CF by deleting some characters.

Mr. Takahashi, full of curiosity, wondered if he could obtain CF from other strings in the same way.

You are given a string <var>s</var> consisting of uppercase English letters.
Determine whether the string CF can be obtained from the string <var>s</var> by deleting some characters.

Constraints

<var>2 ≤ |s| ≤ 100</var>

All characters in <var>s</var> are uppercase English letters (A-Z).

Input

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

<var>s</var>

Output

Print Yes if the string CF can be obtained from the string <var>s</var> by deleting some characters.
Otherwise print No.

Sample Input 1

CODEFESTIVAL

Sample Output 1

Yes

CF is obtained by deleting characters other than the first character C and the fifth character F.

Sample Input 2

FESTIVALCODE

Sample Output 2

No

FC can be obtained but CF cannot be obtained because you cannot change the order of the characters.

Sample Input 3

CF

Sample Output 3

Yes

It is also possible not to delete any characters.

Sample Input 4

FCF

Sample Output 4

Yes

CF is obtained by deleting the first character.

fn solution() {
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let y: Vec<char> = st.chars().collect();
    let mut x: i32 = 0;
    for i in y {
        if x == 0 {
            if i == 'C' {
                x += 1;
            };
        } else {
            if i == 'F' {
                x += 1;
            }
        }
    }
    if x >= 2 {
        println!("Yes");
    } else {
        println!("No");
    }
}


int solution(const int *arr, int l, int r, int x) {
  if (r >= l) {
    int mid = l + ((r - l) / 2);

    if (arr[mid] == x) {
      return mid;
    }

    if (arr[mid] > x) {
      return binarysearch1(arr, l, mid - 1, x);
    }

    return binarysearch1(arr, mid + 1, r, x);
  }

  return -1;
}

fn solution<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
    let is_asc = arr.len() > 1 && arr[0] < arr[arr.len() - 1];

    let mut left = 0;
    let mut right = arr.len();

    while left < right {
        let mid = left + (right - left) / 2;
        let cmp_result = item.cmp(&arr[mid]);

        match (is_asc, cmp_result) {
            (true, Ordering::Less) | (false, Ordering::Greater) => {
                right = mid;
            }
            (true, Ordering::Greater) | (false, Ordering::Less) => {
                left = mid + 1;
            }
            (_, Ordering::Equal) => {
                return Some(mid);
            }
        }
    }

    None
}


Professor Ibrahim has prepared the final homework for his algorithm’s class. He asked his students to implement the Posterization Image Filter.Their algorithm will be tested on an array of integers, where the $$$i$$$-th integer represents the color of the $$$i$$$-th pixel in the image. The image is in black and white, therefore the color of each pixel will be an integer between 0 and 255 (inclusive).To implement the filter, students are required to divide the black and white color range [0, 255] into groups of consecutive colors, and select one color in each group to be the group’s key. In order to preserve image details, the size of a group must not be greater than $$$k$$$, and each color should belong to exactly one group.Finally, the students will replace the color of each pixel in the array with that color’s assigned group key.To better understand the effect, here is an image of a basking turtle where the Posterization Filter was applied with increasing $$$k$$$ to the right.   To make the process of checking the final answer easier, Professor Ibrahim wants students to divide the groups and assign the keys in a way that produces the lexicographically smallest possible array.

int solution() {
  int input;
  int n;
  int k;
  int p[256];

  scanf("%d%d", &n, &k);
  for (int i = 0; i < 256; i++) {
    p[i] = -1;
  }
  for (int i = 0; i < n; ++i) {
    scanf("%d", &input);
    if (p[input] == -1) {
      int temp = (input - k + 1) < 0 ? 0 : (input - k + 1);
      for (int j = temp; j <= input; ++j) {
        if (p[j] == -1 || p[j] == j) {
          for (int l = j; l <= input; ++l) {
            p[l] = j;
          }
          break;
        }
      }
    }
    printf("%d ", p[input]);
  }
  return 0;
}

fn solution() {
    use std::io;
    use std::io::prelude::*;

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

    let mut it = input.split_whitespace();

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

    let p: Vec<usize> = it.map(|x| x.parse().unwrap()).collect();

    let mut rl = vec![None; 256];

    let mut mil = vec![false; 256];

    for &p in p.iter() {
        if rl[p] == None {
            let mut f = p;
            loop {
                if mil[f] {
                    f += 1;
                    break;
                }
                if f == 0 {
                    break;
                }
                if f + k == p + 1 {
                    break;
                }
                f -= 1;
            }
            for i in f..f + k {
                if i == 256 || mil[i] {
                    break;
                }
                if i < p {
                    mil[i] = true;
                }
                rl[i] = Some(f);
            }
        }
        mil[p] = true;
    }

    let mut ans = String::new();
    for p in p {
        let s = format!("{} ", rl[p].unwrap());
        ans.push_str(&s);
    }
    println!("{}", ans);
}


Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.

int solution() {

  int n;
  scanf("%d", &n);
  int arr[n];
  scanf("%d", &arr[0]);
  int max = arr[0];
  int min = arr[0];
  int jlm = 0;
  for (int i = 1; i < n; i++) {
    scanf("%d", &arr[i]);
    if (arr[i] > max) {
      jlm++;
      max = arr[i];
    }
    if (arr[i] < min) {
      min = arr[i];
      jlm++;
    }
  }
  printf("%d\n", jlm);
  return 0;
}

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

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

    let (mut minimum, mut maximum, mut delta) = (10001, -1, -2);
    for num in buf
        .split_whitespace()
        .map(|elem| elem.parse::<i16>().unwrap())
    {
        if num < minimum {
            minimum = num;
            delta += 1;
        }
        if num > maximum {
            maximum = num;
            delta += 1;
        }
    }

    println!("{:?}", delta);
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the <var>i</var>-th mountain from the west is <var>H_i</var>.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the <var>i</var>-th mountain from the west <var>(i = 2, 3, ..., N)</var>, you can see the ocean if and only if <var>H_1 \leq H_i</var>, <var>H_2 \leq H_i</var>, <var>...</var>, and <var>H_{i-1} \leq H_i</var>.

From how many of these <var>N</var> inns can you see the ocean?

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>H_1</var> <var>H_2</var> <var>...</var> <var>H_N</var>

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1

int solution(void) {

  int N = 0;
  int Ni[20];
  int max = 0;
  int result = 0;
  scanf("%d", &N);

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

  for (int i = 0; i < N; i++) {
    if (Ni[i] >= max) {
      max = Ni[i];
      result++;
    }
  }
  printf("%d", result);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let hs: Vec<i32> = buf.trim().split(" ").map(|x| x.parse().unwrap()).collect();
    let mut ans = 0;
    let mut max = 0;
    for h in hs {
        if h >= max {
            ans += 1;
        }
        max = std::cmp::max(h, max);
    }
    println!("{}", ans);
}


Score : <var>800</var> points

Problem Statement

This is an interactive task.

Snuke has a favorite positive integer, <var>N</var>. You can ask him the following type of question at most <var>64</var> times: "Is <var>n</var> your favorite integer?" Identify <var>N</var>.

Snuke is twisted, and when asked "Is <var>n</var> your favorite integer?", he answers "Yes" if one of the two conditions below is satisfied, and answers "No" otherwise:

Both <var>n \leq N</var> and <var>str(n) \leq str(N)</var> hold.

Both <var>n > N</var> and <var>str(n) > str(N)</var> hold.

Here, <var>str(x)</var> is the decimal representation of <var>x</var> (without leading zeros) as a string. For example, <var>str(123) =</var> 123 and <var>str(2000)</var> = 2000.
Strings are compared lexicographically. For example, 11111 <var><</var> 123 and 123456789 <var><</var> 9.

Constraints

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

Input and Output

Write your question to Standard Output in the following format:

? <var>n</var>

Here, <var>n</var> must be an integer between <var>1</var> and <var>10^{18}</var> (inclusive).

Then, the response to the question shall be given from Standard Input in the following format:

<var>ans</var>

Here, <var>ans</var> is either Y or N. Y represents "Yes"; N represents "No".

Finally, write your answer in the following format:

! <var>n</var>

Here, <var>n=N</var> must hold.

Judging

After each output, you must flush Standard Output. Otherwise you may get TLE.

After you print the answer, the program must be terminated immediately. Otherwise, the behavior of the judge is undefined.

When your output is invalid or incorrect, the behavior of the judge is undefined (it does not necessarily give WA).

Sample

Below is a sample communication for the case <var>N=123</var>:

Input
Output

? 1

Y

? 32

N

? 1010

N

? 999

Y

! 123

Since <var>1 \leq 123</var> and <var>str(1) \leq str(123)</var>, the first response is "Yes".

Since <var>32 \leq 123</var> but <var>str(32) > str(123)</var>, the second response is "No".

Since <var>1010 > 123</var> but <var>str(1010) \leq str(123)</var>, the third response is "No".

Since <var>999 \geq 123</var> and <var>str(999) > str(123)</var>, the fourth response is "Yes".

The program successfully identifies <var>N=123</var> in four questions, and thus passes the case.

int solution() {
  int k = 10;
  char res;
  const long long pow[11] = {1,         10,         100,        1000,
                             10000,     100000,     1000000,    10000000,
                             100000000, 1000000000, 10000000000};
  long long tmp = 49999999999;
  long long ans = 0;

  printf("? %lld\n", tmp);
  fflush(stdout);
  scanf(" %c", &res);
  if (res == 'Y') {
    for (tmp -= pow[k]; tmp >= pow[k]; tmp -= pow[k]) {
      printf("? %lld\n", tmp);
      fflush(stdout);
      scanf(" %c", &res);
      if (res == 'N') {
        break;
      }
    }
    ans = tmp / pow[k] + 1;
    tmp += pow[k];
  } else {
    for (tmp += pow[k]; tmp <= pow[k] * 9; tmp += pow[k]) {
      printf("? %lld\n", tmp);
      fflush(stdout);
      scanf(" %c", &res);
      if (res == 'Y') {
        break;
      }
    }
    ans = tmp / pow[k];
  }
  printf("? %lld\n", ((ans - 1) * 10) + 9);
  fflush(stdout);
  scanf(" %c", &res);

  if ((ans > pow[10 - k] && res == 'Y') || (ans == pow[10 - k] && res == 'N')) {
    for (k--; k >= 0; k--) {
      tmp -= pow[k] * 5;
      printf("? %lld\n", tmp);
      fflush(stdout);
      scanf(" %c", &res);
      if (res == 'Y') {
        for (tmp -= pow[k]; tmp >= ans * pow[k + 1]; tmp -= pow[k]) {
          printf("? %lld\n", tmp);
          fflush(stdout);
          scanf(" %c", &res);
          if (res == 'N') {
            break;
          }
        }
        ans = ans * 10 + (tmp / pow[k] + 1) % 10;
        tmp += pow[k];
      } else {
        for (tmp += pow[k]; tmp < (ans + 1) * pow[k + 1] - 1; tmp += pow[k]) {
          printf("? %lld\n", tmp);
          fflush(stdout);
          scanf(" %c", &res);
          if (res == 'Y') {
            break;
          }
        }
        ans = ans * 10 + tmp / pow[k] % 10;
      }
      printf("? %lld\n", ((ans - 1) * 10) + 9);
      fflush(stdout);
      scanf(" %c", &res);
      if ((ans > pow[10 - k] && res == 'N') ||
          (ans == pow[10 - k] && res == 'Y')) {
        break;
      }
    }
  }

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

fn solution() {
    let mut res: i64 = 0;
    for i in 0..15 {
        let mut low: i64 = if res > 0 { -1 } else { 0 };
        let mut high: i64 = 9;
        while high - low > 1 {
            let mid = (low + high) / 2;
            if i < 5 {
                println!("? {}9999999999", 10 * res + mid);
            } else {
                println!("? {}999999", 10 * res + mid);
            }
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).ok();
            if &buf[0..1] == "Y" {
                high = mid;
            } else {
                low = mid;
            }
        }
        res = 10 * res + high;
        println!("? {}", res + 1);
        let str_cmp = res.to_string() < (res + 1).to_string();
        {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).ok();
            if str_cmp == (&buf[0..1] == "Y") {
                println!("! {}", res);
                break;
            }
        }
    }
}


Gregor is learning about RSA cryptography, and although he doesn't understand how RSA works, he is now fascinated with prime numbers and factoring them.Gregor's favorite prime number is $$$P$$$. Gregor wants to find two bases of $$$P$$$. Formally, Gregor is looking for two integers $$$a$$$ and $$$b$$$ which satisfy both of the following properties.  $$$P \bmod a = P \bmod b$$$, where $$$x \bmod y$$$ denotes the remainder when $$$x$$$ is divided by $$$y$$$, and  $$$2 \le a < b \le P$$$. Help Gregor find two bases of his favorite prime number!

int solution() {

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

  int prime_number = 0;
  int counter = 0;

  int results[2000];

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

    prime_number = 0;
    scanf("%d", &prime_number);

    results[counter] = 2;
    counter++;
    results[counter] = (prime_number - 1);
    counter++;
  }

  counter = 0;

  for (int m = 0; m < t; m++) {
    printf("%d %d\n", results[counter], results[counter + 1]);
    counter += 2;
  }
}

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

    while t > 0 {
        let mut p = String::new();
        io::stdin().read_line(&mut p).expect("");
        let p: u32 = p.trim().parse().expect("");
        println!("{} {}", 2, p - 1);

        t -= 1;
    }
}


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

int solution() {
  int a[27];
  int count = 0;
  int ascii = 'a';
  char in[1002];
  for (int i = 0; i < 27; i++) {
    a[i] = 0;
  }

  scanf(" %c", &in[0]);
  int i = 1;
  int flag = 1;
  while (flag) {
    scanf(" %c", &in[i]);
    if (in[i] == '}') {
      break;
    }
    a[in[i] - ascii]++;
  }

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

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

    let mut set = HashSet::new();
    for &c in s.iter() {
        if let 'a'..='z' = c {
            set.insert(c);
        }
    }
    println!("{}", set.len());
}


Score : <var>800</var> points

Problem Statement

Takahashi and Aoki will play a game using a grid with <var>H</var> rows and <var>W</var> columns of square cells.
There are <var>N</var> obstacles on this grid; the <var>i</var>-th obstacle is at <var>(X_i,Y_i)</var>.
Here, we represent the cell at the <var>i</var>-th row and <var>j</var>-th column <var>(1 \leq i \leq H, 1 \leq j \leq W)</var> by <var>(i,j)</var>.
There is no obstacle at <var>(1,1)</var>, and there is a piece placed there at <var>(1,1)</var>.

Starting from Takahashi, he and Aoki alternately perform one of the following actions:

Move the piece to an adjacent cell.
    Here, let the position of the piece be <var>(x,y)</var>. Then Takahashi can only move the piece to <var>(x+1,y)</var>, and Aoki can only move the piece to <var>(x,y+1)</var>.
    If the destination cell does not exist or it is occupied by an obstacle, this action cannot be taken.

Do not move the piece, and end his turn without affecting the grid.

The game ends when the piece does not move twice in a row.

Takahashi would like to perform as many actions (including not moving the piece) as possible before the game ends, while Aoki would like to perform as few actions as possible before the game ends.
How many actions will Takahashi end up performing?

Constraints

<var>1 \leq H,W \leq 2\times 10^5</var>

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

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

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

If <var>i \neq j</var>, <var>(X_i,Y_i) \neq (X_j,Y_j)</var>

<var>(X_i,Y_i) \neq (1,1)</var>

<var>X_i</var> and <var>Y_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>N</var>
<var>X_1</var> <var>Y_1</var>
<var>:</var>
<var>X_N</var> <var>Y_N</var>

Output

Print the number of actions Takahashi will end up performing.

Sample Input 1

3 3 1
3 2

Sample Output 1

2

For example, the game proceeds as follows:

Takahashi moves the piece to (2,1).

Aoki does not move the piece.

Takahashi moves the piece to (3,1).

Aoki does not move the piece.

Takahashi does not move the piece.

Takahashi performs three actions in this case, but if both players play optimally, Takahashi will perform only two actions before the game ends.

Sample Input 2

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

Sample Output 2

6

Sample Input 3

100000 100000 0

Sample Output 3

100000

int solution() {
  long H;
  long W;
  long N;
  long i;
  long j;
  long k;
  long a = 0;
  long *A;

  scanf("%ld %ld %ld", &H, &W, &N);
  A = (long *)malloc((H + 1) * sizeof(long));
  for (i = 1; i <= H; i++) {
    A[i] = 0;
  }

  for (k = 0; k < N; k++) {
    scanf("%ld %ld", &i, &j);
    if (i < j) {
      continue;
    }
    if (A[i] == 0 || A[i] > j) {
      A[i] = j;
    }
  }

  for (i = 1; i <= H; i++) {
    if (A[i] == 0) {
      continue;
    }

    if (A[i] == i - a) {
      a++;
      continue;
    }

    if (A[i] < i - a) {
      k = 1;
      break;
    }
  }

  printf("%ld\n", i - 1);
  return 0;
}

fn solution() {
    input! {
        h: usize,
        w: usize,
        n: usize,
        ps: [[usize; 2]; n]
    }
    if h == 1 {
        println!("1");
        return;
    }
    let mut tab = vec![Vec::new(); w];
    let mut set = HashSet::new();
    for i in 0..n {
        if ps[i][0] < ps[i][1] {
            continue;
        }
        tab[ps[i][1] - 1].push(ps[i][0]);
        set.insert(ps[i].clone());
    }
    let mut r = vec![0; w];
    let mut pos = 0;
    for i in 0..w {
        pos += 1;
        while set.contains(&vec![pos, i + 1]) {
            pos += 1;
        }
        let mut min = h + 1;
        for j in 0..tab[i].len() {
            if tab[i][j] > pos && min > tab[i][j] {
                min = tab[i][j];
            }
        }
        r[i] = min;
    }
    println!("{}", r.iter().min().unwrap() - 1);
}


Polycarp bought a new expensive painting and decided to show it to his $$$n$$$ friends. He hung it in his room. $$$n$$$ of his friends entered and exited there one by one. At one moment there was no more than one person in the room. In other words, the first friend entered and left first, then the second, and so on.It is known that at the beginning (before visiting friends) a picture hung in the room. At the end (after the $$$n$$$-th friend) it turned out that it disappeared. At what exact moment it disappeared — there is no information.Polycarp asked his friends one by one. He asked each one if there was a picture when he entered the room. Each friend answered one of three:  no (response encoded with 0);  yes (response encoded as 1);  can't remember (response is encoded with ?). Everyone except the thief either doesn't remember or told the truth. The thief can say anything (any of the three options).Polycarp cannot understand who the thief is. He asks you to find out the number of those who can be considered a thief according to the answers.

int solution() {
  int cases;
  scanf("%d", &cases);
  char string[200000];
  for (int c = 0; c < cases; c++) {
    scanf("%s", &string[0]);
    if (strlen(string) == 1) {
      printf("1\n");
      continue;
    }
    int start = -1;
    int end = 200001;
    int i = 0;
    while (string[i] != 0) {
      if (string[i] == '0' && end == 200001) {
        end = i;
      }
      i++;
    }
    if (end == 200001) {
      end = i - 1;
    }
    i--;
    while (i >= 0) {
      if (string[i] == '1' && start == -1) {
        start = i;
      }
      i--;
    }
    if (start != -1) {
      start--;
    }
    if (start > end) {
      printf("1\n");
    } else {
      printf("%d\n", end - start);
    }
  }

  return 0;
}

fn solution() {
    let k = std::io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i64>()
        .unwrap();
    for _ in 0..k {
        let mut m = String::new();
        std::io::stdin().read_line(&mut m);
        let m = m
            .trim()
            .split("")
            .flat_map(str::parse::<char>)
            .collect::<Vec<_>>();
        let mut ones = vec![];
        let mut zeros = vec![];
        for (index, vals) in m.iter().enumerate() {
            if vals == &'0' {
                zeros.push(index)
            } else if vals == &'1' {
                ones.push(index)
            }
        }
        if ones.is_empty() && zeros.is_empty() {
            println!("{}", m.len());
        } else if !ones.is_empty() && zeros.is_empty() {
            println!("{}", m.len() - ones[ones.len() - 1])
        } else if ones.is_empty() && !zeros.is_empty() {
            println!("{}", zeros[0] + 1)
        } else {
            println!("{}", zeros[0] - ones[ones.len() - 1] + 1);
        }
    }
}


Score : <var>100</var> points

Problem Statement

How many multiples of <var>d</var> are there among the integers between <var>L</var> and <var>R</var> (inclusive)?

Constraints

All values in input are integers.

<var>1 \leq L \leq R \leq 100</var>

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

Input

Input is given from Standard Input in the following format:

<var>L</var> <var>R</var> <var>d</var>

Output

Print the number of multiples of <var>d</var> among the integers between <var>L</var> and <var>R</var> (inclusive).

Sample Input 1

5 10 2

Sample Output 1

3

Among the integers between <var>5</var> and <var>10</var>, there are three multiples of <var>2</var>: <var>6</var>, <var>8</var>, and <var>10</var>.

Sample Input 2

6 20 7

Sample Output 2

2

Among the integers between <var>6</var> and <var>20</var>, there are two multiples of <var>7</var>: <var>7</var> and <var>14</var>.

Sample Input 3

1 100 1

Sample Output 3

100

int solution() {
  int L;
  int R;
  int d;
  int k = 1;
  int i = 0;
  int n = 0;
  scanf("%d%d%d", &L, &R, &d);
  while (1) {
    n = d * k;
    k++;
    if (n >= L && n <= R) {
      i++;
    }
    if (n > R) {
      break;
    }
  }
  printf("%d\n", i);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let mut it = buf.split_whitespace().map(|n| usize::from_str(n).unwrap());
    let (mut l, r, d) = (it.next().unwrap(), it.next().unwrap(), it.next().unwrap());
    l -= 1;
    println!("{}", r / d - l / d);
}