Score: <var>500</var> points

Problem Statement

New AtCoder City has an infinite grid of streets, as follows:

At the center of the city stands a clock tower. Let <var>(0, 0)</var> be the coordinates of this point.

A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the <var>x</var>-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to East-West Main Street, with a distance of <var>1</var> between them. They correspond to the lines <var>\ldots, y = -2, y = -1, y = 1, y = 2, \ldots</var> in the two-dimensional coordinate plane.

A straight street, which we will call North-South Main Street, runs north-south and passes the clock tower. It corresponds to the <var>y</var>-axis in the two-dimensional coordinate plane.

There are also other infinitely many streets parallel to North-South Main Street, with a distance of <var>1</var> between them. They correspond to the lines <var>\ldots, x = -2, x = -1, x = 1, x = 2, \ldots</var> in the two-dimensional coordinate plane.

There are <var>N</var> residential areas in New AtCoder City. The <var>i</var>-th area is located at the intersection with the coordinates <var>(X_i, Y_i)</var> and has a population of <var>P_i</var>. Each citizen in the city lives in one of these areas.

The city currently has only two railroads, stretching infinitely, one along East-West Main Street and the other along North-South Main Street.

M-kun, the mayor, thinks that they are not enough for the commuters, so he decides to choose <var>K</var> streets and build a railroad stretching infinitely along each of those streets.

Let the walking distance of each citizen be the distance from his/her residential area to the nearest railroad.

M-kun wants to build railroads so that the sum of the walking distances of all citizens, <var>S</var>, is minimized.

For each <var>K = 0, 1, 2, \dots, N</var>, what is the minimum possible value of <var>S</var> after building railroads?

Constraints

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

<var>-10 \ 000 \leq X_i \leq 10 \ 000</var>

<var>-10 \ 000 \leq Y_i \leq 10 \ 000</var>

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

The locations of the <var>N</var> residential areas, <var>(X_i, Y_i)</var>, are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>X_1</var> <var>Y_1</var> <var>P_1</var>
<var>X_2</var> <var>Y_2</var> <var>P_2</var>
 <var>:</var>  <var>:</var>  <var>:</var>
<var>X_N</var> <var>Y_N</var> <var>P_N</var>

Output

Print the answer in <var>N+1</var> lines.

The <var>i</var>-th line <var>(i = 1, \ldots, N+1)</var> should contain the minimum possible value of <var>S</var> after building railroads for the case <var>K = i-1</var>.

Sample Input 1

3
1 2 300
3 3 600
1 4 800

Sample Output 1

2900
900
0
0

When <var>K = 0</var>, the residents of Area <var>1</var>, <var>2</var>, and <var>3</var> have to walk the distances of <var>1</var>, <var>3</var>, and <var>1</var>, respectively, to reach a railroad.

Thus, the sum of the walking distances of all citizens, <var>S</var>, is <var>1 \times 300 + 3 \times 600 + 1 \times 800 = 2900</var>.

When <var>K = 1</var>, if we build a railroad along the street corresponding to the line <var>y = 4</var> in the coordinate plane, the walking distances of the citizens of Area <var>1</var>, <var>2</var>, and <var>3</var> become <var>1</var>, <var>1</var>, and <var>0</var>, respectively.

Then, <var>S = 1 \times 300 + 1 \times 600 + 0 \times 800 = 900</var>.

We have many other options for where we build the railroad, but none of them makes <var>S</var> less than <var>900</var>.

When <var>K = 2</var>, if we build a railroad along the street corresponding to the lines <var>x = 1</var> and <var>x = 3</var> in the coordinate plane, all citizens can reach a railroad with the walking distance of <var>0</var>, so <var>S = 0</var>. We can also have <var>S = 0</var> when <var>K = 3</var>.

The figure below shows the optimal way to build railroads for the cases <var>K = 0, 1, 2</var>.

The street painted blue represents the roads along which we build railroads.

Sample Input 2

5
3 5 400
5 3 700
5 5 1000
5 7 700
7 5 400

Sample Output 2

13800
1600
0
0
0
0

The figure below shows the optimal way to build railroads for the cases <var>K = 1, 2</var>.

Sample Input 3

6
2 5 1000
5 2 1100
5 5 1700
-2 -5 900
-5 -2 600
-5 -5 2200

Sample Output 3

26700
13900
3200
1200
0
0
0

The figure below shows the optimal way to build railroads for the case <var>K = 3</var>.

Sample Input 4

8
2 2 286017
3 1 262355
2 -2 213815
1 -3 224435
-2 -2 136860
-3 -1 239338
-2 2 217647
-1 3 141903

Sample Output 4

2576709
1569381
868031
605676
366338
141903
0
0
0

The figure below shows the optimal way to build railroads for the case <var>K = 4</var>.

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

    let n: usize = {
        let mut buf = String::new();
        reader.read_line(&mut buf).unwrap();
        buf.trim_end().parse().unwrap()
    };
    let mut x: Vec<i64> = vec![0; n];
    let mut y: Vec<i64> = vec![0; n];
    let mut p: Vec<i64> = vec![0; n];
    for i in 0..n {
        let mut buf = String::new();
        reader.read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        x[i] = iter.next().unwrap().parse().unwrap();
        y[i] = iter.next().unwrap().parse().unwrap();
        p[i] = iter.next().unwrap().parse().unwrap();
    }

    let mut a: Vec<Vec<i64>> = vec![vec![std::i64::MAX; n]; 1 << n];
    let mut b: Vec<Vec<i64>> = vec![vec![std::i64::MAX; n]; 1 << n];
    for i in 0..(1 << n) {
        for j in 0..n {
            a[i][j] = cmp::min(a[i][j], x[j].abs());
            b[i][j] = cmp::min(b[i][j], y[j].abs());
            if i & 1 << j == 0 {
                continue;
            }
            for k in 0..n {
                a[i][k] = cmp::min(a[i][k], (x[j] - x[k]).abs());
                b[i][k] = cmp::min(b[i][k], (y[j] - y[k]).abs());
            }
        }
    }

    let pow = |mut a: usize, mut n: usize| {
        let mut res = 1;
        while n > 0 {
            if n & 1 > 0 {
                res *= a;
            }
            a *= a;
            n >>= 1;
        }
        res
    };

    let mut ans = vec![std::i64::MAX; n + 1];
    for i in 0..pow(3, n) {
        let mut c = 0;
        let mut x = i;
        let mut s = 0;
        let mut t = 0;
        for j in 0..n {
            let y = x % 3;
            if y == 1 {
                s += 1 << j;
                c += 1;
            } else if y == 2 {
                t += 1 << j;
                c += 1;
            }
            x /= 3;
        }

        let mut d = vec![std::i64::MAX; n];
        for i in 0..n {
            d[i] = cmp::min(a[s][i], b[t][i]);
        }
        let res = { d.iter().enumerate().fold(0, |acc, (i, k)| acc + p[i] * k) };
        ans[c] = cmp::min(ans[c], res);
    }

    for i in 0..=n {
        writeln!(writer, "{}", ans[i]).unwrap();
    }
}


void solution(int *a, int n) {
  int curr_size, left_start;
  int *b = (int *)malloc(n * sizeof(int));

  for (curr_size = 1; curr_size <= n - 1; curr_size = 2 * curr_size) {
    for (left_start = 0; left_start < n - 1; left_start += 2 * curr_size) {
      int l = left_start;
      int mid = (left_start + curr_size - 1 < n - 1)
                    ? left_start + curr_size - 1
                    : n - 1;

      int r = (left_start + 2 * curr_size - 1 < n - 1)
                  ? left_start + 2 * curr_size - 1
                  : n - 1;

      int p1 = l;
      int p2 = mid + 1;
      int c = l;

      while (p1 <= mid && p2 <= r) {
        if (a[p1] <= a[p2])
          b[c++] = a[p1++];
        else
          b[c++] = a[p2++];
      }

      while (p1 <= mid)
        b[c++] = a[p1++];

      while (p2 <= r)
        b[c++] = a[p2++];

      for (c = l; c <= r; c++)
        a[c] = b[c];
    }
  }

  free(b);
}

fn solution<T: Copy + Ord>(arr: &mut [T]) {
    if arr.len() <= 1 {
        return;
    }

    let len = arr.len();
    let mut sub_array_size = 1;

    while sub_array_size < len {
        let mut start_index = 0;

        while len - start_index > sub_array_size {
            let end_idx = if start_index + 2 * sub_array_size > len {
                len
            } else {
                start_index + 2 * sub_array_size
            };

            let mid = sub_array_size;

            let left_half = arr[start_index..start_index + mid].to_vec();
            let right_half = arr[start_index + mid..end_idx].to_vec();

            let mut l = 0;
            let mut r = 0;

            for v in &mut arr[start_index..end_idx] {
                if r == right_half.len() || (l < left_half.len() && left_half[l] < right_half[r]) {
                    *v = left_half[l];
                    l += 1;
                } else {
                    *v = right_half[r];
                    r += 1;
                }
            }

            start_index = end_idx;
        }

        sub_array_size *= 2;
    }
}


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

int solution(void) {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int v[n];
    printf("%d\n", n);
    for (int i = 1; i <= n; i++) {
      v[i - 1] = i;
      printf("%d ", i);
    }
    printf("\n");
    for (int i = n - 1; i > 0; i--) {
      int temp = v[i];
      v[i] = v[i - 1];
      v[i - 1] = temp;
      for (int f = 0; f < n; f++) {
        printf("%d ", v[f]);
      }
      printf("\n");
    }
  }
  return 0;
}

fn solution() {
    let out = &mut BufWriter::new(stdout());

    let mut input = String::new();
    stdin().read_line(&mut input).expect("Failed read");
    let t = input.trim().parse::<i64>().unwrap();

    for _ in 0..t {
        input = String::new();
        stdin().read_line(&mut input).expect("Failed read");
        let n = input.trim().parse::<i64>().unwrap();
        let mut v: Vec<i64> = (1..n + 1).collect();
        writeln!(out, "{}", n).ok();
        for a in &v {
            write!(out, "{} ", a).ok();
        }
        writeln!(out).ok();
        for i in 1..n {
            v.swap((n - i) as usize, (n - i - 1) as usize);
            for a in &v {
                write!(out, "{} ", a).ok();
            }
            writeln!(out).ok();
        }
    }
}


Let's define $$$S(x)$$$ to be the sum of digits of number $$$x$$$ written in decimal system. For example, $$$S(5) = 5$$$, $$$S(10) = 1$$$, $$$S(322) = 7$$$.We will call an integer $$$x$$$ interesting if $$$S(x + 1) < S(x)$$$. In each test you will be given one integer $$$n$$$. Your task is to calculate the number of integers $$$x$$$ such that $$$1 \le x \le n$$$ and $$$x$$$ is interesting.

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

    while t > 0 {
        let mut n = String::new();
        std::io::stdin().read_line(&mut n).expect("");
        let n: u64 = n.trim().parse().expect("");
        println!("{}", (n + 1) / 10);
        t -= 1;
    }
}


A little boy Gerald entered a clothes shop and found out something very unpleasant: not all clothes turns out to match. For example, Gerald noticed that he looks rather ridiculous in a smoking suit and a baseball cap.Overall the shop sells n clothing items, and exactly m pairs of clothing items match. Each item has its price, represented by an integer number of rubles. Gerald wants to buy three clothing items so that they matched each other. Besides, he wants to spend as little money as possible. Find the least possible sum he can spend.

int solution() {
  char triples[101][101];
  int i;
  int j;
  int k;
  int l;
  int m;
  int n;
  int cost[101];
  int aux;
  int min = INT_MAX;

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

  for (i = 1; i <= n; i++) {
    for (j = 1; j <= n; j++) {
      triples[i][j] = 0;
    }
  }

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

  for (k = 0; k < m; k++) {
    scanf("%d %d", &i, &j);

    triples[i][j] = 1;
    triples[j][i] = 1;

    aux = cost[i] + cost[j];

    if (aux < min) {
      for (l = 1; l <= n; l++) {
        if (triples[i][l] && triples[j][l]) {
          if (min > (aux + cost[l])) {
            min = (aux + cost[l]);
          }
        }
      }
    }
  }

  printf("%d\n", (min < INT_MAX ? min : -1));

  return 0;
}

fn solution() {
    let stdin: io::Stdin = io::stdin();
    let mut lines: io::Lines<io::StdinLock> = stdin.lock().lines();

    let first_line = lines.next().unwrap().unwrap();

    let flv: Vec<_> = first_line
        .trim()
        .split(' ')
        .map(|n| n.parse::<u32>().unwrap())
        .collect();

    let n = flv[0];
    let _m = flv[1];

    let cost: Vec<u32> = lines
        .next()
        .unwrap()
        .unwrap()
        .trim()
        .split(' ')
        .map(|n| n.parse().unwrap())
        .collect();

    let mut reach: Vec<HashSet<u32>> = vec![];
    reach.reserve(n as usize);
    for _ in cost.iter() {
        reach.push(HashSet::new());
    }

    let mut pairs: Vec<Vec<u32>> = vec![];
    for l in lines {
        let lv: Vec<u32> = l
            .unwrap()
            .trim()
            .split(' ')
            .map(|n| n.parse::<u32>().unwrap() - 1)
            .collect();

        reach[lv[0] as usize].insert(lv[1]);
        reach[lv[1] as usize].insert(lv[0]);
        pairs.push(lv);
    }

    let mut min_cost = <u32>::max_value();
    let mut has_solution = false;
    for p in pairs {
        for i in 0..n {
            if reach[p[0] as usize].contains(&i) && reach[p[1] as usize].contains(&i) {
                has_solution = true;
                let cur_cost = cost[p[0] as usize] + cost[p[1] as usize] + cost[i as usize];
                if cur_cost < min_cost {
                    min_cost = cur_cost;
                }
            }
        }
    }

    if has_solution {
        println!("{}", min_cost);
    } else {
        println!("{}", -1);
    }
}


You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:   Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$;  Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$;  Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.

int solution() {
  int count = 0;
  int amount;
  long long int number[1001];
  scanf("%d", &amount);

  for (long long int i = 0; i < amount; i++) {
    scanf("%lld", &number[i]);
  }

  for (long long int i = 0; i < amount; i++) {

    while (1) {

      if (number[i] % 5 == 0) {
        number[i] = (4 * number[i]) / 5;
        count++;
      } else if (number[i] % 5 != 0 && number[i] % 3 == 0) {
        number[i] = (2 * number[i]) / 3;
        count++;
      } else if (number[i] % 5 != 0 && number[i] % 3 != 0 &&
                 number[i] % 2 == 0) {
        number[i] = number[i] / 2;
        count++;
      }
      if (number[i] != 1 && number[i] % 5 != 0 && number[i] % 3 != 0 &&
          number[i] % 2 != 0) {
        count = -1;
        printf("%d\n", count);
        count = 0;
        break;
      }
      if (number[i] == 1) {
        printf("%d\n", count);
        count = 0;
        break;
      }
    }
  }
}

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

    io::stdin().read_line(&mut t).unwrap();
    let mut t: u32 = t.trim().parse().unwrap();

    while t != 0 {
        t -= 1;
        let mut q = String::new();
        io::stdin().read_line(&mut q).unwrap();
        let mut q: u64 = q.trim().parse::<u64>().unwrap();

        let mut count = 0;

        loop {
            count += 1;

            if q == 1 {
                println!("{}", count - 1);
                break;
            }

            if q.is_multiple_of(2) {
                q /= 2;
                continue;
            }

            if q.is_multiple_of(3) {
                q = 2 * q / 3;
                continue;
            }

            if q.is_multiple_of(5) {
                q = 4 * q / 5;
                continue;
            }

            break;
        }

        if q != 1 {
            println!("-1");
        }
    }
}


Score : <var>300</var> points

Problem Statement

You are given an integer sequence of length <var>N</var>. The <var>i</var>-th term in the sequence is <var>a_i</var>.
In one operation, you can select a term and either increment or decrement it by one.

At least how many operations are necessary to satisfy the following conditions?

For every <var>i</var> <var>(1≤i≤n)</var>, the sum of the terms from the <var>1</var>-st through <var>i</var>-th term is not zero.

For every <var>i</var> <var>(1≤i≤n-1)</var>, the sign of the sum of the terms from the <var>1</var>-st through <var>i</var>-th term, is different from the sign of the sum of the terms from the <var>1</var>-st through <var>(i+1)</var>-th term.

Constraints

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

<var>|a_i| ≤ 10^9</var>

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

Input

Input is given from Standard Input in the following format:

<var>n</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_n</var>

Output

Print the minimum necessary count of operations.

Sample Input 1

4
1 -3 1 0

Sample Output 1

4

For example, the given sequence can be transformed into <var>1, -2, 2, -2</var> by four operations. The sums of the first one, two, three and four terms are <var>1, -1, 1</var> and <var>-1</var>, respectively, which satisfy the conditions.

Sample Input 2

5
3 -6 4 -5 7

Sample Output 2

0

The given sequence already satisfies the conditions.

Sample Input 3

6
-1 4 3 2 -5 4

Sample Output 3

8

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut a: Vec<i64> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();
    for i in 0..n - 1 {
        a[i + 1] += a[i];
    }

    let mut ans1 = 0;
    let mut ans2 = 0;
    let mut diff = 0i64;
    for i in 0..n {
        if i % 2 == 0 && a[i] + diff <= 0 {
            ans1 += 1 - (a[i] + diff);
            diff += 1 - (a[i] + diff);
        }
        if i % 2 == 1 && a[i] + diff >= 0 {
            ans1 += a[i] + diff + 1;
            diff -= a[i] + diff + 1;
        }
    }
    diff = 0;
    for i in 0..n {
        if i % 2 == 0 && a[i] + diff >= 0 {
            ans2 += a[i] + diff + 1;
            diff -= a[i] + diff + 1;
        }
        if i % 2 == 1 && a[i] + diff <= 0 {
            ans2 += 1 - (a[i] + diff);
            diff += 1 - (a[i] + diff);
        }
    }
    println!("{}", min(ans1, ans2));
}


Score : <var>200</var> points

Problem Statement

You have a digit sequence <var>S</var> of length <var>4</var>. You are wondering which of the following formats <var>S</var> is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If <var>S</var> is valid in only YYMM format, print YYMM; if <var>S</var> is valid in only MMYY format, print MMYY; if <var>S</var> is valid in both formats, print AMBIGUOUS; if <var>S</var> is valid in neither format, print NA.

Constraints

<var>S</var> is a digit sequence of length <var>4</var>.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May <var>XX19</var> is a valid date, but <var>19</var> is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December <var>XX01</var> and January <var>XX12</var> are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither <var>0</var> nor <var>17</var> is valid as a month. Thus, this string is valid in neither format.

fn solution() {
    let mut buf = String::new();
    let _ = std::io::stdin().read_line(&mut buf);
    let (b, a) = buf.trim().split_at(2);
    let b = b.parse::<u32>().unwrap();
    let a = a.parse::<u32>().unwrap();
    let b = !(1..=12).contains(&b);
    let a = !(1..=12).contains(&a);
    if b && a {
        println!("NA");
    } else if !b && a {
        println!("MMYY");
    } else if b && !a {
        println!("YYMM");
    } else {
        println!("AMBIGUOUS");
    }
}


Digit Number

Write a program which computes the digit number of sum of two integers <var>a</var> and <var>b</var>.

Input

There are several test cases. Each test case consists of two non-negative integers <var>a</var> and b which are separeted by a space in a line. The input terminates with EOF.

Constraints

0 ≤ <var>a</var>, <var>b</var> ≤ 1,000,000

The number of datasets ≤ 200

Output

Print the number of digits of <var>a</var> + <var>b</var> for each data set.

Sample Input

5 7
1 99
1000 999

Output for the Sample Input

2
3
4

int solution(void) {
  int a = 0;
  int b = 0;
  int i = 0;
  int sum = 0;

  while (scanf("%d %d", &a, &b) != EOF) {
    sum = a + b;

    for (i = 1; i < 15; i++) {
      if (sum < 10) {
        printf("%d\n", i);
        break;
      }
      sum = sum / 10;
    }
  }

  return 0;
}

fn solution() {
    let mut input;
    let mut total: u64;
    loop {
        input = String::new();
        if let Ok(0) = std::io::stdin().read_line(&mut input) {
            break;
        }
        total = 0;
        for i in input.split_whitespace() {
            total += i.parse::<u64>().expect("");
        }
        println!("{}", total.to_string().len());
    }
}


You have an array of integers (initially empty).You have to perform $$$q$$$ queries. Each query is of one of two types:   "$$$1$$$ $$$x$$$" — add the element $$$x$$$ to the end of the array;  "$$$2$$$ $$$x$$$ $$$y$$$" — replace all occurrences of $$$x$$$ in the array with $$$y$$$. Find the resulting array after performing all the queries.

fn solution() {
    let mut cin = String::new();
    std::io::stdin().read_to_string(&mut cin).unwrap();
    let mut cin = cin.split_ascii_whitespace().flat_map(str::parse::<_>);

    cin![q];
    let mut p = 0;
    let mut ps = vec![HashSet::new(); 1 << 19];
    for _ in 1..=q {
        cin![op x];
        if op == 1 {
            ps[x].insert(p);
            p += 1;
        } else {
            cin![y];
            if x == y {
                continue;
            }
            if ps[y].len() < ps[x].len() {
                ps.swap(x, y);
            }
            let tv = ps[x].drain().collect::<Vec<_>>();
            for p in tv {
                ps[y].insert(p);
            }
        }
    }
    let mut v = vec![0; p];
    for i in 1..=500000 {
        for p in &ps[i] {
            v[*p] = i;
        }
    }
    let mut s = String::new();
    for v in v {
        s += &format!("{} ", v);
    }
    s.pop();
    println!("{}", s)
}


Santa has $$$n$$$ candies and he wants to gift them to $$$k$$$ kids. He wants to divide as many candies as possible between all $$$k$$$ kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has $$$a$$$ candies and the kid who recieves the maximum number of candies has $$$b$$$ candies. Then Santa will be satisfied, if the both conditions are met at the same time:  $$$b - a \le 1$$$ (it means $$$b = a$$$ or $$$b = a + 1$$$);  the number of kids who has $$$a+1$$$ candies (note that $$$a+1$$$ not necessarily equals $$$b$$$) does not exceed $$$\lfloor\frac{k}{2}\rfloor$$$ (less than or equal to $$$\lfloor\frac{k}{2}\rfloor$$$). $$$\lfloor\frac{k}{2}\rfloor$$$ is $$$k$$$ divided by $$$2$$$ and rounded down to the nearest integer. For example, if $$$k=5$$$ then $$$\lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2$$$.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer $$$t$$$ independent test cases.

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut queries: u16 = line.trim().parse().unwrap();
    while queries > 0 {
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut numbers = line.split_whitespace();
        let sweets: i32 = numbers.next().unwrap().parse().unwrap();
        let children: i32 = numbers.next().unwrap().parse().unwrap();
        let mut unused = sweets % children;
        unused -= children / 2;
        if unused < 0 {
            unused = 0;
        }
        println!("{}", sweets - unused);
        queries -= 1;
    }
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> of length <var>N</var> consisting of lowercase English letters.
We will cut this string at one position into two strings <var>X</var> and <var>Y</var>.
Here, we would like to maximize the number of different letters contained in both <var>X</var> and <var>Y</var>.
Find the largest possible number of different letters contained in both <var>X</var> and <var>Y</var> when we cut the string at the optimal position.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the largest possible number of different letters contained in both <var>X</var> and <var>Y</var>.

Sample Input 1

6
aabbca

Sample Output 1

2

If we cut the string between the third and fourth letters into <var>X =</var> aab and <var>Y =</var> bca, the letters contained in both <var>X</var> and <var>Y</var> are a and b.
There will never be three or more different letters contained in both <var>X</var> and <var>Y</var>, so the answer is <var>2</var>.

Sample Input 2

10
aaaaaaaaaa

Sample Output 2

1

However we divide <var>S</var>, only a will be contained in both <var>X</var> and <var>Y</var>.

Sample Input 3

45
tgxgdqkyjzhyputjjtllptdfxocrylqfqjynmfbfucbir

Sample Output 3

9

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    is.clear();
    stdin().read_line(&mut is).ok();
    let s = is.trim();
    let mut ans = 0;

    for i in 1..s.len() {
        let (x, y) = s.split_at(i);
        let mut x_cnt = [false; 26];
        let mut y_cnt = [false; 26];

        x.chars().for_each(|c| x_cnt[c as usize - 0x61] = true);
        y.chars().for_each(|c| y_cnt[c as usize - 0x61] = true);
        ans = max(
            ans,
            x_cnt
                .iter()
                .zip(y_cnt.iter())
                .filter(|e| *e.0 && *e.1)
                .count(),
        );
    }

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


Score : <var>300</var> points

Problem Statement

Given is a string <var>S</var> consisting of lowercase English letters. Find the maximum positive integer <var>K</var> that satisfies the following condition:

There exists a partition of <var>S</var> into <var>K</var> non-empty strings <var>S=S_1S_2...S_K</var> such that <var>S_i \neq S_{i+1}</var> (<var>1 \leq i \leq K-1</var>).

Here <var>S_1S_2...S_K</var> represents the concatenation of <var>S_1,S_2,...,S_K</var> in this order.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the maximum positive integer <var>K</var> that satisfies the condition.

Sample Input 1

aabbaa

Sample Output 1

4

We can, for example, divide <var>S</var> into four strings aa, b, ba, and a.

Sample Input 2

aaaccacabaababc

Sample Output 2

12

int solution() {
  bool is2 = false;

  char s[200000];
  scanf("%s", s);
  int len = strlen(s);
  int k = len;
  for (int i = 0; i < len - 1; i++) {
    if (!is2 && s[i] == s[i + 1]) {
      is2 = true;
      i++;
      k--;
    } else {
      is2 = false;
    }
  }
  printf("%d\n", k);
  return 0;
}


The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

int solution() {
  int n = 0;
  int i = 0;
  int ans = 0;
  int b = 0;
  scanf("%d", &n);
  int a[n + 1];

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

  printf("%d", ans);

  return 0;
}

fn solution() {
    let _ = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().to_string()
    };
    let v: Vec<i32> = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim()
            .split(" ")
            .map(|s| s.parse::<i32>().unwrap())
            .collect()
    };

    let (_, untreated) = v.into_iter().fold((0, 0), |(policy, untreated), i| {
        if i == -1 {
            if policy == 0 {
                (0, untreated + 1)
            } else {
                (policy - 1, untreated)
            }
        } else {
            (policy + i, untreated)
        }
    });
    println!("{:?}", untreated);
}


Pig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds.  Determine if Pig can visit the friend using teleports only, or he should use his car.

int solution() {
  int n = 0;
  int max = 0;
  int x = 0;
  scanf("%d", &n);
  scanf("%d", &x);
  int a[n];
  int b[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    scanf("%d", &b[i]);
  }
  bool continuous = true;
  max = b[0];
  for (int i = 1; i < n; i++) {
    if (a[i] > max) {
      continuous = false;
      break;
    }
    max = b[i] > max ? b[i] : max;
  }

  if (a[0] == 0 && max >= x && continuous) {
    printf("YES\n");
  } else {
    printf("NO\n");
  }
  return 0;
}

fn solution() {
    let mut stdin = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut stdin).unwrap();
    let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();

    let n = get!();
    let g = get!();
    let mut x = 0;
    for _ in 0..n {
        let ai = get!();
        let bi = get!();
        if ai <= x {
            x = std::cmp::max(x, bi);
        }
    }
    if g <= x {
        println!("YES");
    } else {
        println!("NO");
    }
}


Vladik often travels by trains. He remembered some of his trips especially well and I would like to tell you about one of these trips:Vladik is at initial train station, and now n people (including Vladik) want to get on the train. They are already lined up in some order, and for each of them the city code ai is known (the code of the city in which they are going to).Train chief selects some number of disjoint segments of the original sequence of people (covering entire sequence by segments is not necessary). People who are in the same segment will be in the same train carriage. The segments are selected in such way that if at least one person travels to the city x, then all people who are going to city x should be in the same railway carriage. This means that they can’t belong to different segments. Note, that all people who travel to the city x, either go to it and in the same railway carriage, or do not go anywhere at all.Comfort of a train trip with people on segment from position l to position r is equal to XOR of all distinct codes of cities for people on the segment from position l to position r. XOR operation also known as exclusive OR.Total comfort of a train trip is equal to sum of comfort for each segment.Help Vladik to know maximal possible total comfort.

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

    let a: Vec<usize> = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input
            .split_whitespace()
            .map(|k| k.parse::<usize>().unwrap())
            .collect()
    };

    let fr: Vec<_> = (0..5001).map(|i| a.iter().position(|&k| k == i)).collect();
    let ls: Vec<_> = (0..5001).map(|i| a.iter().rposition(|&k| k == i)).collect();

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

    for i in 0..n {
        let mut max_val = 0;
        let mut max_ls = 0;
        let mut min_fr = n + 1;
        let mut cur = 0;
        let mut is_al = vec![false; 5001];
        for j in (0..(i + 1)).rev() {
            max_ls = max(ls[a[j]].unwrap(), max_ls);
            min_fr = min(fr[a[j]].unwrap(), min_fr);
            if !is_al[a[j]] {
                cur ^= (a[j]);
            }
            is_al[a[j]] = true;
            if min_fr >= j && i >= max_ls {
                if j >= 1 {
                    max_val = max(max_val, cur + dp[j - 1]);
                } else {
                    max_val = max(max_val, cur);
                }
            }
        }
        if i >= 1 {
            max_val = max(max_val, dp[i - 1]);
        }
        dp.push(max_val);
    }

    println!("{}", dp[n - 1]);
}


This is an interactive problem.I want to play a game with you...We hid from you a cyclic graph of $$$n$$$ vertices ($$$3 \le n \le 10^{18}$$$). A cyclic graph is an undirected graph of $$$n$$$ vertices that form one cycle. Each vertex belongs to the cycle, i.e. the length of the cycle (the number of edges in it) is exactly $$$n$$$. The order of the vertices in the cycle is arbitrary.You can make queries in the following way: "? a b" where $$$1 \le a, b \le 10^{18}$$$ and $$$a \neq b$$$. In response to the query, the interactor outputs on a separate line the length of random of two paths from vertex $$$a$$$ to vertex $$$b$$$, or -1 if $$$\max(a, b) > n$$$. The interactor chooses one of the two paths with equal probability. The length of the path —is the number of edges in it.You win if you guess the number of vertices in the hidden graph (number $$$n$$$) by making no more than $$$50$$$ queries.Note that the interactor is implemented in such a way that for any ordered pair $$$(a, b)$$$, it always returns the same value for query "? a b", no matter how many such queries. Note that the "? b a" query may be answered differently by the interactor.The vertices in the graph are randomly placed, and their positions are fixed in advance.Hacks are forbidden in this problem. The number of tests the jury has is $$$50$$$.

int solution(void) {
  long long r1 = 0;
  long long r2 = 0;
  for (int b = 2; b <= 26; ++b) {
    printf("\? %d %d\n", 1, b);
    fflush(stdout);
    scanf("%lli", &r1);
    if (r1 == -1) {
      printf("! %d\n", b - 1);
      fflush(stdout);
      return 0;
    }
    printf("\? %d %d\n", b, 1);
    fflush(stdout);
    scanf("%lli", &r2);
    if (r1 != r2) {
      break;
    }
  }
  printf("! %lli\n", r1 + r2);
  fflush(stdout);
  return 0;
}

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

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

    let mut write_and_flush = |line: &str| {
        writeln!(out, "{}", line).unwrap();
        out.flush().unwrap();
    };

    let is_finished = |line: &str| line.eq("0");

    let mut target = 3i64;

    loop {
        write_and_flush(&format!("? 1 {}", target));

        let mut buf = String::new();
        io::stdin().read_line(&mut buf)?;
        let line = buf.trim();

        if is_finished(line) {
            break;
        }

        let path1: i64 = line.parse().unwrap();
        if path1 == -1 {
            write_and_flush(&format!("! {}", target - 1));
            break;
        }

        write_and_flush(&format!("? {} 1", target));

        let mut buf = String::new();
        io::stdin().read_line(&mut buf)?;
        let line = buf.trim();

        if is_finished(line) {
            break;
        }

        let path2: i64 = line.parse().unwrap();

        if path1 != path2 {
            write_and_flush(&format!("! {}", path1 + path2));
            break;
        } else {
            target += 1;
        }
    }
    Ok(())
}


Switching Railroad Cars

This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks.

We can simulate the movement (comings and goings) of the cars as follow:

An entry of a car is represented by its number.

An exit of a car is represented by 0

For example, a sequence

1
6
0
8
10

demonstrates that car 1 and car 6 enter to the rail tracks in this order, car 6 exits from the rail tracks, and then car 8 and car 10 enter.

Write a program which simulates comings and goings of the cars which are represented by the sequence of car numbers. The program should read the sequence of car numbers and 0, and print numbers of cars which exit from the rail tracks in order. At the first, there are no cars on the rail tracks. You can assume that 0 will not be given when there is no car on the rail tracks.

Input

car number
car number or 0
car number or 0
  .
  .
  .
car number or 0

The number of input lines is less than or equal to 100.

Output

For each 0, print the car number.

Sample Input

1
6
0
8
10
0
0
0

Output for the Sample Input

6
10
8
1

int solution() {
  int t[10];
  int ts = 0;
  while (scanf("%d", &t[ts]) != EOF) {
    if (t[ts]) {
      ts++;
    } else {
      printf("%d\n", t[--ts]);
    }
  }
  return 0;
}

fn solution() {
    let mut stack = vec![];
    let input = BufReader::new(stdin());
    for line in input.lines() {
        let n = line.unwrap().trim().parse::<u32>().unwrap();
        if n == 0 {
            println!("{}", stack.last().unwrap());
            let last_idx = stack.len() - 1;
            stack.remove(last_idx);
        } else {
            stack.push(n);
        }
    }
}


Score : <var>400</var> points

Problem Statement

We have an undirected graph <var>G</var> with <var>N</var> vertices numbered <var>1</var> to <var>N</var> and <var>N</var> edges as follows:

For each <var>i=1,2,...,N-1</var>, there is an edge between Vertex <var>i</var> and Vertex <var>i+1</var>.

There is an edge between Vertex <var>X</var> and Vertex <var>Y</var>.

For each <var>k=1,2,...,N-1</var>, solve the problem below:

Find the number of pairs of integers <var>(i,j) (1 \leq i < j \leq N)</var> such that the shortest distance between Vertex <var>i</var> and Vertex <var>j</var> in <var>G</var> is <var>k</var>.

Constraints

<var>3 \leq N \leq 2 \times 10^3</var>

<var>1 \leq X,Y \leq N</var>

<var>X+1 < Y</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>X</var> <var>Y</var>

Output

For each <var>k=1, 2, ..., N-1</var> in this order, print a line containing the answer to the problem.

Sample Input 1

5 2 4

Sample Output 1

5
4
1
0

The graph in this input is as follows:

There are five pairs <var>(i,j) (1 \leq i < j \leq N)</var> such that the shortest distance between Vertex <var>i</var> and Vertex <var>j</var> is <var>1</var>: <var>(1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5)</var>.

There are four pairs <var>(i,j) (1 \leq i < j \leq N)</var> such that the shortest distance between Vertex <var>i</var> and Vertex <var>j</var> is <var>2</var>: <var>(1,3)\,,(1,4)\,,(2,5)\,,(3,5)</var>.

There is one pair <var>(i,j) (1 \leq i < j \leq N)</var> such that the shortest distance between Vertex <var>i</var> and Vertex <var>j</var> is <var>3</var>: <var>(1,5)</var>.

There are no pairs <var>(i,j) (1 \leq i < j \leq N)</var> such that the shortest distance between Vertex <var>i</var> and Vertex <var>j</var> is <var>4</var>.

Sample Input 2

3 1 3

Sample Output 2

3
0

The graph in this input is as follows:

Sample Input 3

7 3 7

Sample Output 3

7
8
4
2
0
0

Sample Input 4

10 4 8

Sample Output 4

10
12
10
8
4
1
0
0
0

fn solution() {
    let (n, x, y) = {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let s: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
        (s[0], s[1], s[2])
    };
    let mut k = vec![0; n];
    let f = |i, j| if i < j { j - i } else { i - j };
    for i in 1..n + 1 {
        for j in i + 1..n + 1 {
            k[min(f(i, j), f(i, x) + f(y, j) + 1)] += 1;
        }
    }
    for i in 1..n {
        println!("{}", k[i]);
    }
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.Let's call a pair of indices $$$i$$$, $$$j$$$ good if $$$1 \le i < j \le n$$$ and $$$\gcd(a_i, 2a_j) > 1$$$ (where $$$\gcd(x, y)$$$ is the greatest common divisor of $$$x$$$ and $$$y$$$).Find the maximum number of good index pairs if you can reorder the array $$$a$$$ in an arbitrary way.

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

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

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

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

    for _ in 0..t {
        let n = lines.next().unwrap().parse::<usize>().unwrap();
        let s = lines.next().unwrap();
        let it = s.split_whitespace().map(|s| s.parse::<usize>().unwrap());

        let a = it.collect::<Vec<_>>();

        let (even, odd): (Vec<_>, Vec<_>) = a.iter().cloned().partition(|x| x % 2 == 0);

        let oans = (0..odd.len())
            .map(|i| {
                (i + 1..odd.len())
                    .map(|j| {
                        let mut x = odd[i];
                        let mut y = 2 * odd[j];
                        while y != 0 {
                            let t = x % y;
                            x = y;
                            y = t;
                        }
                        if x == 1 {
                            0u64
                        } else {
                            1
                        }
                    })
                    .sum::<u64>()
            })
            .sum::<u64>();

        let m = even.len() as u64;
        let eans = if m < 2 { 0 } else { (m * (m - 1)) / 2 } + m * (n as u64 - m);

        let ans = oans + eans;
        writeln!(&mut output, "{}", ans).unwrap();
    }
}


Given a set of integers (it can contain equal elements).You have to split it into two subsets $$$A$$$ and $$$B$$$ (both of them can contain equal elements or be empty). You have to maximize the value of $$$mex(A)+mex(B)$$$.Here $$$mex$$$ of a set denotes the smallest non-negative integer that doesn't exist in the set. For example:   $$$mex(\{1,4,0,2,2,1\})=3$$$  $$$mex(\{3,3,2,1,3,0,0\})=4$$$  $$$mex(\varnothing)=0$$$ ($$$mex$$$ for empty set) The set is splitted into two subsets $$$A$$$ and $$$B$$$ if for any integer number $$$x$$$ the number of occurrences of $$$x$$$ into this set is equal to the sum of the number of occurrences of $$$x$$$ into $$$A$$$ and the number of occurrences of $$$x$$$ into $$$B$$$.

fn solution() {
    let mut input = String::new();
    stdin().read_line(&mut input).expect("error");
    let iterations = input.trim().parse::<u32>().expect("error");
    for _ in 0..iterations {
        input.clear();
        stdin().read_line(&mut input).expect("error");
        input.clear();
        stdin().read_line(&mut input).expect("error");
        let mut numbers = input
            .split_whitespace()
            .map(|n| n.parse::<u32>().expect("error"))
            .collect::<Vec<u32>>();
        numbers.sort();

        let mut a = 0;
        let mut b = 0;
        for item in numbers {
            if item == a {
                a += 1;
            } else if item == b {
                b += 1;
            }
        }
        println!("{}", a + b);
    }
}


Score : <var>200</var> points

Problem Statement

AtCoDeer the deer has found two positive integers, <var>a</var> and <var>b</var>.
Determine whether the concatenation of <var>a</var> and <var>b</var> in this order is a square number.

Constraints

<var>1</var> <var>≤</var> <var>a,b</var> <var>≤</var> <var>100</var>

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

Input

Input is given from Standard Input in the following format:

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

Output

If the concatenation of <var>a</var> and <var>b</var> in this order is a square number, print Yes; otherwise, print No.

Sample Input 1

1 21

Sample Output 1

Yes

As <var>121</var> <var>=</var> <var>11</var> × <var>11</var>, it is a square number.

Sample Input 2

100 100

Sample Output 2

No

<var>100100</var> is not a square number.

Sample Input 3

12 10

Sample Output 3

No

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let vec: Vec<&str> = s.trim().split(' ').collect();
    let mut n = String::new();
    for v in &vec {
        n += v.as_ref();
    }
    let p = n.parse::<i32>().unwrap();
    for i in 0..10000 {
        let s = i * i;
        if s == p {
            println!("Yes");
            return;
        }
    }
    println!("No");
}


The only difference between the easy and hard versions is that the given string $$$s$$$ in the easy version is initially a palindrome, this condition is not always true for the hard version.A palindrome is a string that reads the same left to right and right to left. For example, "101101" is a palindrome, while "0101" is not.Alice and Bob are playing a game on a string $$$s$$$ of length $$$n$$$ consisting of the characters '0' and '1'. Both players take alternate turns with Alice going first.In each turn, the player can perform one of the following operations:   Choose any $$$i$$$ ($$$1 \le i \le n$$$), where $$$s[i] =$$$ '0' and change $$$s[i]$$$ to '1'. Pay 1 dollar.  Reverse the whole string, pay 0 dollars. This operation is only allowed if the string is currently not a palindrome, and the last operation was not reverse. That is, if Alice reverses the string, then Bob can't reverse in the next move, and vice versa. Reversing a string means reordering its letters from the last to the first. For example, "01001" becomes "10010" after reversing.The game ends when every character of string becomes '1'. The player who spends minimum dollars till this point wins the game and it is a draw if both spend equal dollars. If both players play optimally, output whether Alice wins, Bob wins, or if it is a draw.

int solution() {
  char s[1005];
  int t;
  int n;
  int flag = 0;
  int sum = 0;
  scanf("%d", &t);
  while (t--) {
    flag = 0, sum = 0;
    scanf("%d", &n);
    scanf("%s", s);
    for (int i = 0; i < n; i++) {
      if (s[i] != s[n - 1 - i]) {
        flag = 1;
      }
      if (s[i] == '0') {
        sum++;
      }
    }
    if (flag == 0) {
      if (sum == 1 || sum % 2 == 0) {
        printf("BOB\n");
      } else {
        printf("ALICE\n");
      }
    } else {
      if (sum == 2 && n % 2 == 1 && s[n / 2] == '0') {
        printf("DRAW\n");
      } else {
        printf("ALICE\n");
      }
    }
  }
  return 0;
}

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

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

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

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

    for _ in 0..t {
        let n = lines.next().unwrap().parse::<usize>().unwrap();

        let s = lines.next().unwrap();
        let a = s.as_bytes();

        let mut rc = 0;
        let mut bc = 0;

        for i in 0..n / 2 {
            let j = n - 1 - i;

            let a0 = a[i] == b'0';
            let a1 = a[j] == b'0';

            if a0 && a1 {
                rc += 1;
            } else if a0 || a1 {
                bc += 1;
            }
        }

        let a0 = rc > 0;
        let a1 = n % 2 == 1 && a[n / 2] == b'0';

        let sb1 = {
            match (a0, a1) {
                (false, false) => 0,
                (false, true) => -1,
                (true, false) => -2,
                (true, true) => 1,
            }
        };

        let s0 = bc + sb1;

        let s1 = if bc > 0 { bc - 2 - sb1 } else { i32::MIN };

        let s = std::cmp::max(s0, s1);

        use std::cmp::Ordering::*;
        let ans = match s.cmp(&0) {
            Less => "BOB",
            Equal => "DRAW",
            Greater => "ALICE",
        };

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


Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$.  For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.

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


Score : <var>300</var> points

Problem Statement

Dolphin resides in two-dimensional Cartesian plane, with the positive <var>x</var>-axis pointing right and the positive <var>y</var>-axis pointing up.

Currently, he is located at the point <var>(sx,sy)</var>. In each second, he can move up, down, left or right by a distance of <var>1</var>.

Here, both the <var>x</var>- and <var>y</var>-coordinates before and after each movement must be integers.

He will first visit the point <var>(tx,ty)</var> where <var>sx < tx</var> and <var>sy < ty</var>, then go back to the point <var>(sx,sy)</var>, then visit the point <var>(tx,ty)</var> again, and lastly go back to the point <var>(sx,sy)</var>.

Here, during the whole travel, he is not allowed to pass through the same point more than once, except the points <var>(sx,sy)</var> and <var>(tx,ty)</var>.

Under this condition, find a shortest path for him.

Constraints

<var>-1000 ≤ sx < tx ≤ 1000</var>

<var>-1000 ≤ sy < ty ≤ 1000</var>

<var>sx,sy,tx</var> and <var>ty</var> are integers.

Input

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

<var>sx</var> <var>sy</var> <var>tx</var> <var>ty</var>

Output

Print a string <var>S</var> that represents a shortest path for Dolphin.

The <var>i</var>-th character in <var>S</var> should correspond to his <var>i</var>-th movement.

The directions of the movements should be indicated by the following characters:

U: Up

D: Down

L: Left

R: Right

If there exist multiple shortest paths under the condition, print any of them.

Sample Input 1

0 0 1 2

Sample Output 1

UURDDLLUUURRDRDDDLLU

One possible shortest path is:

Going from <var>(sx,sy)</var> to <var>(tx,ty)</var> for the first time: <var>(0,0)</var> → <var>(0,1)</var> → <var>(0,2)</var> → <var>(1,2)</var>

Going from <var>(tx,ty)</var> to <var>(sx,sy)</var> for the first time: <var>(1,2)</var> → <var>(1,1)</var> → <var>(1,0)</var> → <var>(0,0)</var>

Going from <var>(sx,sy)</var> to <var>(tx,ty)</var> for the second time: <var>(0,0)</var> → <var>(-1,0)</var> → <var>(-1,1)</var> → <var>(-1,2)</var> → <var>(-1,3)</var> → <var>(0,3)</var> → <var>(1,3)</var> → <var>(1,2)</var>

Going from <var>(tx,ty)</var> to <var>(sx,sy)</var> for the second time: <var>(1,2)</var> → <var>(2,2)</var> → <var>(2,1)</var> → <var>(2,0)</var> → <var>(2,-1)</var> → <var>(1,-1)</var> → <var>(0,-1)</var> → <var>(0,0)</var>

Sample Input 2

-2 -2 1 1

Sample Output 2

UURRURRDDDLLDLLULUUURRURRDDDLLDL

int solution() {
  int sx = 0;
  int sy = 0;
  int tx = 0;
  int ty = 0;
  int i = 0;
  scanf("%d %d %d %d", &sx, &sy, &tx, &ty);
  for (i = 0; i < ty - sy; i++) {
    printf("U");
  }
  for (i = 0; i < tx - sx; i++) {
    printf("R");
  }
  for (i = 0; i < ty - sy; i++) {
    printf("D");
  }
  for (i = 0; i < tx - sx; i++) {
    printf("L");
  }
  printf("L");
  for (i = 0; i < ty - sy + 1; i++) {
    printf("U");
  }
  for (i = 0; i < tx - sx + 1; i++) {
    printf("R");
  }
  printf("D");
  printf("R");
  for (i = 0; i < ty - sy + 1; i++) {
    printf("D");
  }
  for (i = 0; i < tx - sx + 1; i++) {
    printf("L");
  }
  printf("U");
  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 sx: i64 = itr.next().unwrap().parse().unwrap();
    let sy: i64 = itr.next().unwrap().parse().unwrap();
    let tx: i64 = itr.next().unwrap().parse().unwrap();
    let ty: i64 = itr.next().unwrap().parse().unwrap();

    let dx = tx - sx;
    let dy = ty - sy;
    let mut ans = Vec::new();
    for _ in 0..dx {
        ans.push('R');
    }
    for _ in 0..dy {
        ans.push('U');
    }
    for _ in 0..dx {
        ans.push('L');
    }
    for _ in 0..dy {
        ans.push('D');
    }

    ans.push('D');
    for _ in 0..dx + 1 {
        ans.push('R');
    }
    for _ in 0..dy + 1 {
        ans.push('U');
    }
    ans.push('L');
    ans.push('U');
    for _ in 0..dx + 1 {
        ans.push('L');
    }
    for _ in 0..dy + 1 {
        ans.push('D');
    }
    ans.push('R');

    let s: String = ans.into_iter().collect();
    println!("{}", s);
}


問題 4:　部活のスケジュール表 (Schedule)

問題

IOI 高校のプログラミング部には，J 君と O 君と I 君の 3 人の部員がいる．
プログラミング部では，部活のスケジュールを組もうとしている．

今，N 日間の活動のスケジュールを決めようとしている．
各活動日のスケジュールとして考えられるものは，各部員については活動に参加するかどうかの 2 通りがあり，部としては全部で 8 通りある．
部室の鍵はただ 1 つだけであり，最初は J 君が持っている．
各活動日には，その日の活動に参加する部員のうちのいずれか 1 人が鍵を持っている必要があり，活動後に参加した部員のいずれかが鍵を持って帰る．

プログラミング部では，活動日には毎回必ず活動が行われるように，あらかじめ各活動日の責任者を定めた．
責任者は，必ずその日の活動に出席しなければならない．

スケジュールを決めようとしている日数と，各活動日の責任者が誰であるかの情報が与えられた時，すべての活動日に部活動を行うことができるようなスケジュール表として考えられるものの数を 10007 で割った余りを求めるプログラムを作成せよ．
ただし，部活の終了時に鍵を持って帰る部員は，その日の活動に参加している部員の誰でもよく，最終日は誰が鍵を持って帰ってもよいものとする．

入力

入力は，2 行からなる．

1 行目には，スケジュールを決めようとしている日数を表す 1 つの整数 N (2 ≤ N ≤ 1000) が書かれている．

2 行目には，各活動日の責任者を表す N 文字からなる文字列が書かれている．
この文字列の i 文字目 (1 ≤ i ≤ N) は，i 日目の活動日の責任者を表す．
すなわち，i 文字目が J, O, I であることはそれぞれ i 日目の活動日の責任者が J 君，O 君，I 君であることを意味する．

出力

スケジュール表として考えられるものの数を 10007 で割った余りを 1 行で出力せよ．

入出力例

入力例 1

2
OI

出力例 1

7

入出力例 1 において，2 日間の活動日のスケジュールを考える．1 日目の責任者は O 君，2 日目の責任者は I 君である．
問題文の条件をみたすスケジュール表は 7 通り考えられる．

   1 日目
   2 日目

  スケジュール 1
  J, O
  O, I

  スケジュール 2
  J, O
  J, I

  スケジュール 3
  J, O
  J, O, I

  スケジュール 4
  J, O, I
  I

  スケジュール 5
  J, O, I
  J, I

  スケジュール 6
  J, O, I
  O, I

  スケジュール 7
  J, O, I
  J, O, I

この表では，J, O, I はそれぞれその日に J 君, O 君, I 君が参加することを表す．
1 日目の責任者は O 君であるが，最初鍵を持っているのは J 君であるため，1 日目の活動には J 君, O 君の両方が参加する必要があることに注意せよ．
また，1 日目に鍵を持って帰った人は 2 日目にも参加しないといけないので，1 日目と 2 日目の両方に参加する人が少なくとも 1 人存在しなければならないことに注意せよ．

入力例 2

20
JIOIJOIJOJOIIIOJIOII

出力例 2

4976

入出力例 2 において，条件をみたすスケジュール表は全部で 72493594992 通り考えられる．それを 10007 で割った余りである 4976 を出力する．

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

fn solution() {
    let input = {
        let mut buf = vec![];
        stdin().read_to_end(&mut buf);
        unsafe { String::from_utf8_unchecked(buf) }
    };
    let mut lines = input.split('\n');
    let iter = lines.nth(1).unwrap().bytes();

    let mut comb = [1u64, 0, 0, 0, 0, 0, 0];

    for ch in iter {
        let chg = match ch {
            b'J' => 1,
            b'O' => 2,
            _ => 4,
        };
        let mut tmp = [0u64; 7];

        for (i, &n) in comb.iter().enumerate() {
            if n == 0 {
                continue;
            }
            let bit = i + 1;

            if bit & (1 | chg) != 0 {
                tmp[(chg | 1) - 1] += n;
            }
            if bit & (2 | chg) != 0 {
                tmp[(chg | 2) - 1] += n;
            }
            if bit & (4 | chg) != 0 {
                tmp[(chg | 4) - 1] += n;
            }
            tmp[7 - 1] += n;
        }

        if tmp[7 - 1] >= 1 << 62 {
            for n in &mut tmp {
                *n %= 10007;
            }
        }
        comb = tmp;
    }

    let sum = comb.into_iter().sum::<u64>() % 10007;
    println!("{}", sum);
}


You are given a set of $$$2n+1$$$ integer points on a Cartesian plane. Points are numbered from $$$0$$$ to $$$2n$$$ inclusive. Let $$$P_i$$$ be the $$$i$$$-th point. The $$$x$$$-coordinate of the point $$$P_i$$$ equals $$$i$$$. The $$$y$$$-coordinate of the point $$$P_i$$$ equals zero (initially). Thus, initially $$$P_i=(i,0)$$$.The given points are vertices of a plot of a piecewise function. The $$$j$$$-th piece of the function is the segment $$$P_{j}P_{j + 1}$$$.In one move you can increase the $$$y$$$-coordinate of any point with odd $$$x$$$-coordinate (i.e. such points are $$$P_1, P_3, \dots, P_{2n-1}$$$) by $$$1$$$. Note that the corresponding segments also change.For example, the following plot shows a function for $$$n=3$$$ (i.e. number of points is $$$2\cdot3+1=7$$$) in which we increased the $$$y$$$-coordinate of the point $$$P_1$$$ three times and $$$y$$$-coordinate of the point $$$P_5$$$ one time:  Let the area of the plot be the area below this plot and above the coordinate axis OX. For example, the area of the plot on the picture above is 4 (the light blue area on the picture above is the area of the plot drawn on it).Let the height of the plot be the maximum $$$y$$$-coordinate among all initial points in the plot (i.e. points $$$P_0, P_1, \dots, P_{2n}$$$). The height of the plot on the picture above is 3.Your problem is to say which minimum possible height can have the plot consisting of $$$2n+1$$$ vertices and having an area equal to $$$k$$$. Note that it is unnecessary to minimize the number of moves.It is easy to see that any answer which can be obtained by performing moves described above always exists and is an integer number not exceeding $$$10^{18}$$$.

int solution() {
  long long n;
  long long k;
  while (scanf("%lld%lld", &n, &k) != EOF) {
    long long t;
    t = k / n;
    if (t * n != k) {
      printf("%lld\n", t + 1);
    } else {
      printf("%lld\n", t);
    }
  }
  return 0;
}

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

    handle.read_to_string(&mut buffer).expect("stdin");

    let arr: Vec<_> = buffer
        .split_whitespace()
        .map(|x| x.parse::<i64>().unwrap())
        .collect();

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

    let distrib_height = k / n + if k % n == 0 { 0 } else { 1 };

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


Score : <var>100</var> points

Problem Statement

There are two rectangles.
The lengths of the vertical sides of the first rectangle are <var>A</var>, and the lengths of the horizontal sides of the first rectangle are <var>B</var>.
The lengths of the vertical sides of the second rectangle are <var>C</var>, and the lengths of the horizontal sides of the second rectangle are <var>D</var>.

Print the area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Constraints

All input values are integers.

<var>1≤A≤10^4</var>

<var>1≤B≤10^4</var>

<var>1≤C≤10^4</var>

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

Input

The 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 area of the rectangle with the larger area.
If the two rectangles have equal areas, print that area.

Sample Input 1

3 5 2 7

Sample Output 1

15

The first rectangle has an area of <var>3×5=15</var>, and the second rectangle has an area of <var>2×7=14</var>.
Thus, the output should be <var>15</var>, the larger area.

Sample Input 2

100 600 200 300

Sample Output 2

60000

int solution(void) {
  int A = 0;
  int B = 0;
  int C = 0;
  int D = 0;
  int s1 = 0;
  int s2 = 0;
  scanf("%d%d%d%d", &A, &B, &C, &D);
  s1 = A * B;
  s2 = C * D;
  if (s1 == s2) {
    printf("%d\n", s1);
  }
  if (s1 > s2) {
    printf("%d\n", s1);
  } else if (s1 < s2) {
    printf("%d\n", s2);
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
    println!("{}", std::cmp::max(v[0] * v[1], v[2] * v[3]));
}


I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?You are given a string of $$$n$$$ lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find out what the MEX of the string is!

int solution() {
  int t;
  int n;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    int b[30];
    int flag = 0;
    memset(b, 0, sizeof(b));
    char a[1005];
    char tem;
    for (int i = 0; i < n;) {
      tem = getchar();
      if (tem >= 'a' && tem <= 'z') {
        a[i] = tem;
        i++;
        b[tem - 'a'] = 1;
      }
    }
    for (int i = 0; i < 26; i++) {
      if (b[i] == 0) {
        printf("%c\n", i + 'a');
        flag = 1;
        break;
      }
    }
    for (char i = 'a'; i <= 'z'; i++) {
      if (flag == 1) {
        break;
      }
      for (char j = 'a'; j <= 'z'; j++) {
        int cflag = 1;
        for (int k = 0; k < n - 1; k++) {
          if (i == a[k] && j == a[k + 1]) {
            cflag = 0;
            break;
          }
        }
        if (cflag == 1) {
          flag = 1;
          printf("%c%c\n", i, j);
          break;
        }
      }
      if (flag == 1) {
        break;
      }
    }
    for (char i = 'a'; i <= 'z'; i++) {
      if (flag == 1) {
        break;
      }
      for (char j = 'a'; j <= 'z'; j++) {
        for (char k = 'a'; k < 'z'; k++) {
          int cflag = 1;
          for (int m = 0; m < n - 2; m++) {
            if (i == a[m] && j == a[m + 1] && k == a[m + 2]) {
              cflag = 0;
              break;
            }
          }
          if (cflag == 1) {
            printf("%c%c%c\n", i, j, k);
            flag = 1;
            break;
          }
        }
        if (flag == 1) {
          break;
        }
      }
    }
  }

  return 0;
}

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

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

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

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

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

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

        let s = lines.next().unwrap();

        let mut t1 = [false; 26];
        let mut t2 = [false; 26 * 26];
        let mut t3 = [false; 26 * 26 * 26];

        let a = s.as_bytes();

        for &b in a {
            let i = (b - b'a') as usize;
            t1[i] = true;
        }

        for b in a.windows(2) {
            let d1 = (b[0] - b'a') as usize;
            let d0 = (b[1] - b'a') as usize;

            let i = 26 * d1 + d0;
            t2[i] = true;
        }

        for b in a.windows(3) {
            let d2 = (b[0] - b'a') as usize;
            let d1 = (b[1] - b'a') as usize;
            let d0 = (b[2] - b'a') as usize;

            let i = 26 * 26 * d2 + 26 * d1 + d0;
            t3[i] = true;
        }

        if let Some(i) = t1.iter().position(|&a| !a) {
            let mex = &[i as u8 + b'a'];
            let s = std::str::from_utf8(mex).unwrap();
            writeln!(&mut output, "{}", s).unwrap();
        } else if let Some(i) = t2.iter().position(|&a| !a) {
            let d1 = (i / 26) as u8;
            let d0 = (i % 26) as u8;

            let mex = &[d1 + b'a', d0 + b'a'];
            let s = std::str::from_utf8(mex).unwrap();
            writeln!(&mut output, "{}", s).unwrap();
        } else {
            let mut i = t3.iter().position(|&a| !a).unwrap();

            let d0 = (i % 26) as u8;
            i /= 26;
            let d1 = (i % 26) as u8;
            i /= 26;
            let d2 = (i % 26) as u8;

            let mex = &[d2 + b'a', d1 + b'a', d0 + b'a'];
            let s = std::str::from_utf8(mex).unwrap();
            writeln!(&mut output, "{}", s).unwrap();
        }
    }
}


Score : <var>300</var> points

Problem Statement

You drew lottery <var>N</var> times. In the <var>i</var>-th draw, you got an item of the kind represented by a string <var>S_i</var>.

How many kinds of items did you get?

Constraints

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

<var>S_i</var> consists of lowercase English letters and has a length between <var>1</var> and <var>10</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var>
<var>:</var>
<var>S_N</var>

Output

Print the number of kinds of items you got.

Sample Input 1

3
apple
orange
apple

Sample Output 1

2

You got two kinds of items: apple and orange.

Sample Input 2

5
grape
grape
grape
grape
grape

Sample Output 2

1

Sample Input 3

4
aaaa
a
aaa
aa

Sample Output 3

4

int solution(void) {
  int n;
  int i;
  int s;
  int c;
  int changed;
  int j;

  struct cell head;
  struct cell *p;

  for (i = 0; i < 30; i++) {
    head.next[i] = NULL;
  }
  head.e = 0;

  s = 0;

  scanf("%d", &n);
  getchar();
  for (i = 0; i < n; i++) {
    p = &head;
    changed = 0;
    while ((c = getchar()) != '\n') {
      if (p->next[c - 'a'] == NULL) {
        changed = 1;
        p->next[c - 'a'] = (struct cell *)malloc(sizeof(struct cell));
        p = p->next[c - 'a'];
        for (j = 0; j < 30; j++) {
          p->next[j] = NULL;
        }
        p->e = 0;

      } else {
        p = p->next[c - 'a'];
      }
    }
    if (p->e == 0) {
      p->e = 1;
      changed = 1;
    }
    s += changed;
  }

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

  return 0;
}

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

    let mut m = std::collections::HashMap::<String, bool>::new();
    for _ in 0..n {
        let mut t = String::new();
        std::io::stdin().read_line(&mut t).ok();
        m.insert(t, true);
    }

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


You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding.  On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.

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

fn solution() {
    let mut i = 0u32;
    let mut t = String::new();
    io::stdin().read_line(&mut t).expect("Input Failed");
    let t: u32 = t.trim().parse().expect("Not a number");
    loop {
        if i == t {
            break;
        } else {
            let mut n = String::new();
            io::stdin().read_line(&mut n).expect("Input Failed");
            let n: u32 = n.trim().parse().expect("Not a number");
            println!("{}", n);
            i += 1
        }
    }
}


You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other.    The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \le a \le r_1$$$, $$$l_2 \le b \le r_2$$$ and $$$a \ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.

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

    for _ in 0..n {
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();

        let v: Vec<u32> = line.trim().split(' ').map(|x| x.parse().unwrap()).collect();

        let (l1, _, l2, _) = (v[0], v[1], v[2], v[3]);
        if l1 == l2 {
            println!("{} {}", l1, l1 + 1);
        } else {
            println!("{} {}", l1, l2);
        }
    }
}


According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.

int solution(void) {
  char c = 0;
  int n = 0;
  int i = 0;
  int cnt = 0;
  char arr[1000] = {
      0,
  };

  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf(" %c", &arr[i]);
    if (arr[i] == '1') {
      cnt++;
    }
  }

  if (n == 1) {
    if (cnt == 0) {
      c = 'N';
    } else {
      c = 'Y';
    }
  } else {
    if (n - cnt == 1) {
      c = 'Y';
    } else {
      c = 'N';
    }
  }

  if (c == 'Y') {
    printf("YES\n");
  } else {
    printf("NO\n");
  }

  return 0;
}

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

    let buttons: u16 = buttons.trim().parse().unwrap();

    let arr: Vec<u8> = arr
        .split_whitespace()
        .map(|e| if e == "1" { 1 } else { 0 })
        .collect();

    if buttons == 1 && arr[0] == 1 {
        println!("YES")
    } else if buttons == 1 && arr[0] != 1 {
        println!("NO")
    } else {
        let mut c = 0;
        for i in arr {
            if i == 0 {
                c += 1;
                if c > 1 {
                    break;
                }
            }
        }
        if c == 1 {
            println!("YES")
        } else {
            println!("NO")
        }
    }
}


Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:  Include a person to the chat ('Add' command).  Remove a person from the chat ('Remove' command).  Send a message from a person to all people, who are currently in the chat, including the one, who sends the message ('Send' command). Now Polycarp wants to find out the amount of outgoing traffic that the server will produce while processing a particular set of commands.Polycarp knows that chat server sends no traffic for 'Add' and 'Remove' commands. When 'Send' command is processed, server sends l bytes to each participant of the chat, where l is the length of the message.As Polycarp has no time, he is asking for your help in solving this problem.

int solution() {

  char status[100];
  int quant = 0;
  int qntBytes = 0;
  int i = 0;

  while (scanf("%[^\n] ", status) != EOF) {
    if (status[0] == '+') {
      quant++;
    } else if (status[0] == '-') {
      quant--;
    } else {
      for (i = 0; status[i] != ':'; i++) {
      }

      qntBytes += quant * (strlen(status) - i - 1);
    }
  }
  printf("%d", qntBytes);

  return 0;
}

fn solution() {
    let reader = BufReader::new(io::stdin());
    let mut cnt = 0;
    let mut length = 0;
    for line in reader.lines().flatten() {
        let bs = line.as_bytes();
        match bs[0] {
            b'+' => {
                cnt += 1;
            }
            b'-' => {
                cnt -= 1;
            }
            _ => {
                if let Some(n) = bs.iter().position(|&c| c == b':') {
                    length += cnt * (bs.len() - n - 1);
                }
            }
        }
    }
    println!("{}", length);
}


At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$ — is the maximum possible ($$$k$$$ — any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Error!");
    let x: i32 = line.trim().parse().expect("Error!");

    for _ in 0..x {
        let mut price = String::new();

        io::stdin().read_line(&mut price).expect("Error!");
        let _price: i32 = price.trim().parse().expect("Error!");

        let _power = price.len() as u32;
        let res = 10i32.pow(_power - 3);
        println!("{}", _price - res);
    }
}


You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.

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

    handle.read_to_string(&mut buffer).expect("stdin");

    let arr: Vec<_> = buffer.split_whitespace().collect();
    let mut str1 = arr[2].parse::<String>().unwrap();
    let mut str2 = arr[3].parse::<String>().unwrap();

    let mut x: i64 = 1;
    let mut y: i64 = 0;
    let mut ans: i64 = 0;
    let mo: i64 = 998244353;
    loop {
        if let Some(c) = str1.pop() {
            if c == '1' {
                y = (y + x) % mo
            }
        };
        match str2.pop() {
            Some(c) => {
                if c == '1' {
                    ans = (ans + y) % mo
                }
            }
            None => break,
        };
        x = (x * 2) % mo;
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

Given an integer <var>a</var> as input, print the value <var>a + a^2 + a^3</var>.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>a</var>

Output

Print the value <var>a + a^2 + a^3</var> as an integer.

Sample Input 1

2

Sample Output 1

14

When <var>a = 2</var>, we have <var>a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14</var>.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110

int solution(void) {
  int a = 0;
  scanf("%d", &a);
  printf("%d", a + (a * a) + (a * a * a));
  return 0;
}

fn solution() {
    let mut guess = String::new();
    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");

    let guess: f64 = guess.trim().parse().expect("Please type a number!");

    println!("{}", guess + guess * guess + guess * guess * guess);
}


You are given an integer $$$n$$$. You have to construct a permutation of size $$$n$$$.A permutation is an array where each integer from $$$1$$$ to $$$s$$$ (where $$$s$$$ is the size of permutation) occurs exactly once. For example, $$$[2, 1, 4, 3]$$$ is a permutation of size $$$4$$$; $$$[1, 2, 4, 5, 3]$$$ is a permutation of size $$$5$$$; $$$[1, 4, 3]$$$ is not a permutation (the integer $$$2$$$ is absent), $$$[2, 1, 3, 1]$$$ is not a permutation (the integer $$$1$$$ appears twice).A subsegment of a permutation is a contiguous subsequence of that permutation. For example, the permutation $$$[2, 1, 4, 3]$$$ has $$$10$$$ subsegments: $$$[2]$$$, $$$[2, 1]$$$, $$$[2, 1, 4]$$$, $$$[2, 1, 4, 3]$$$, $$$[1]$$$, $$$[1, 4]$$$, $$$[1, 4, 3]$$$, $$$[4]$$$, $$$[4, 3]$$$ and $$$[3]$$$.The value of the permutation is the number of its subsegments which are also permutations. For example, the value of $$$[2, 1, 4, 3]$$$ is $$$3$$$ since the subsegments $$$[2, 1]$$$, $$$[1]$$$ and $$$[2, 1, 4, 3]$$$ are permutations.You have to construct a permutation of size $$$n$$$ with minimum possible value among all permutations of size $$$n$$$.

fn solution() {
    let test_cases = {
        let mut s = String::new();
        io::stdin().read_line(&mut s).expect("read failed");
        s.trim().parse::<i32>().unwrap()
    };

    for _ in 0..test_cases {
        let n = {
            let mut s = String::new();
            io::stdin().read_line(&mut s).expect("read failed");
            s.trim().parse::<i32>().unwrap()
        };

        let mut v = Vec::<i32>::new();
        v.push(1);
        v.push(n);
        for i in 2..n {
            v.push(i);
        }

        for (i, x) in v.iter().enumerate() {
            print!("{}{}", x, if i + 1 == v.len() { "\n" } else { " " });
        }
    }
}


A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).

int solution() {
  int n = 0;
  char s[100000];
  scanf("%d", &n);
  scanf("%s", s);
  int moves = (n - 11) / 2;
  int eights[100000];
  int eights_counter = 0;
  for (int i = 0; i < n - 10; i++) {
    if (s[i] == '8') {
      eights[eights_counter++] = n - i - 11;
    }
  }

  if (eights_counter <= moves) {
    printf("NO");
  } else {
    printf("YES");
  }
  return 0;
}

fn solution() {
    let mut input = "".split_ascii_whitespace();
    let mut read = || loop {
        if let Some(word) = input.next() {
            break word;
        }
        input = {
            let mut input = "".to_owned();
            io::stdin().read_line(&mut input).unwrap();
            if input.is_empty() {
                panic!("reached EOF");
            }
            Box::leak(input.into_boxed_str()).split_ascii_whitespace()
        };
    };

    let n = read!(usize);
    let s = read!(String);

    let a = s.chars().collect::<Vec<char>>();
    let mut c8 = 0;
    for i in 0..(n - 10) {
        if a[i] == '8' {
            c8 += 1;
        }
    }

    let r = if (n - 9) / 2 <= c8 { "YES" } else { "NO" };
    println!("{}", r);
}


Score : <var>300</var> points

Problem Statement

In a flower bed, there are <var>N</var> flowers, numbered <var>1,2,......,N</var>. Initially, the heights of all flowers are <var>0</var>.
You are given a sequence <var>h=\{h_1,h_2,h_3,......\}</var> as input. You would like to change the height of Flower <var>k</var> to <var>h_k</var> for all <var>k</var> <var>(1 \leq  k \leq N)</var>, by repeating the following "watering" operation:

Specify integers <var>l</var> and <var>r</var>. Increase the height of Flower <var>x</var> by <var>1</var> for all <var>x</var> such that <var>l \leq x \leq r</var>.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

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

<var>0 \leq h_i \leq 100</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>h_1</var> <var>h_2</var> <var>h_3</var> <var>......</var> <var>h_N</var>

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is <var>2</var>.
One way to achieve it is:

Perform the operation with <var>(l,r)=(1,3)</var>.

Perform the operation with <var>(l,r)=(2,4)</var>.

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221

int solution() {
  int N;
  scanf("%d", &N);
  int h[102];
  int table[102] = {0};
  for (int i = 0; i < N; i++) {
    scanf("%d", h + i);
  }
  int ans = 0;
  int f = 0;
  int changed = 0;
  do {
    changed = 0;
    for (int j = 0; j < N; j++) {
      if (f == 0 && table[j] < h[j]) {
        f = 1;
        table[j]++;
        changed = 1;
      } else if (f == 1 && table[j] < h[j]) {
        table[j]++;
      } else if (f == 1 && table[j] >= h[j]) {
        f = 0;
        ans++;
      }
    }
    if (f == 1) {
      ans++;
      f = 0;
    }
  } while (changed);
  printf("%d", ans);
}

fn solution() {
    let text = {
        use std::io::Read;
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s).unwrap();
        s
    };
    let mut iter = text.split_whitespace();
    let _ = iter.next();
    let mut sum = 0i32;
    let mut prev = 0i32;
    for height in iter.map(|word| word.parse::<i32>().unwrap()) {
        if prev < height {
            sum += height - prev;
        }
        prev = height;
    }
    println!("{}", sum);
}


Score : <var>400</var> points

Problem Statement

Takahashi had a pair of two positive integers not exceeding <var>N</var>, <var>(a,b)</var>, which he has forgotten.
He remembers that the remainder of <var>a</var> divided by <var>b</var> was greater than or equal to <var>K</var>.
Find the number of possible pairs that he may have had.

Constraints

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

<var>0 \leq K \leq N-1</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of possible pairs that he may have had.

Sample Input 1

5 2

Sample Output 1

7

There are seven possible pairs: <var>(2,3),(5,3),(2,4),(3,4),(2,5),(3,5)</var> and <var>(4,5)</var>.

Sample Input 2

10 0

Sample Output 2

100

Sample Input 3

31415 9265

Sample Output 3

287927211

int solution(void) {
  unsigned long long n;
  unsigned long long k;
  unsigned long long i;
  unsigned long long cnt;

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

  cnt = 0;
  if (k == 0) {
    printf("%llu\n", n * n);
    return 0;
  }

  for (i = 1; i <= n; i++) {
    if (i > k) {
      cnt += (i - k) * (n - n % i) / i;
      cnt += (n % i) >= k ? (n % i) - k + 1 : 0;
    }
  }

  printf("%llu\n", cnt);
  return 0;
}

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

    let mut ans: u64 = 0;
    for b in k + 1..n + 1 {
        let div = n / b;
        ans += div * (b - k);
        if div * b + k <= n {
            ans += n - (div * b + k) + 1;
        }
    }
    if k == 0 {
        ans -= n;
    }
    println!("{}", ans);
}


You went to the store, selling $$$n$$$ types of chocolates. There are $$$a_i$$$ chocolates of type $$$i$$$ in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $$$x_i$$$ chocolates of type $$$i$$$ (clearly, $$$0 \le x_i \le a_i$$$), then for all $$$1 \le j < i$$$ at least one of the following must hold:  $$$x_j = 0$$$ (you bought zero chocolates of type $$$j$$$) $$$x_j < x_i$$$ (you bought less chocolates of type $$$j$$$ than of type $$$i$$$) For example, the array $$$x = [0, 0, 1, 2, 10]$$$ satisfies the requirement above (assuming that all $$$a_i \ge x_i$$$), while arrays $$$x = [0, 1, 0]$$$, $$$x = [5, 5]$$$ and $$$x = [3, 2]$$$ don't.Calculate the maximum number of chocolates you can buy.

int solution() {
  int n;
  scanf("%d", &n);
  int arr[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
  }
  long long sum = 0;
  for (int i = n - 1; i >= 0; i--) {
    sum += arr[i];
    if (arr[i] == 1) {
      break;
    }
    if ((i - 1) >= 0 && arr[i - 1] >= arr[i]) {
      arr[i - 1] = arr[i] - 1;
    }
  }
  printf("%lld", sum);
  return 0;
}

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!(usize);
    let mut xs = vec![];

    for _ in 0..n {
        xs.push(get!());
    }

    xs.reverse();

    let mut ans = 0_i64;
    let mut last = std::i64::MAX;
    for &x in xs.iter() {
        if x < last {
            ans += x;
            last = x;
        } else {
            last -= 1;
            if last > 0 {
                ans += last;
            }
        }
    }
    println!("{}", ans);
}


It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kept records of sleep times for the last n days. So now he has a sequence a1, a2, ..., an, where ai is the sleep time on the i-th day.The number of records is so large that Polycarp is unable to calculate the average value by himself. Thus he is asking you to help him with the calculations. To get the average Polycarp is going to consider k consecutive days as a week. So there will be n - k + 1 weeks to take into consideration. For example, if k = 2, n = 3 and a = [3, 4, 7], then the result is .You should write a program which will calculate average sleep times of Polycarp over all weeks.

int solution() {
  int k;
  int n;
  scanf("%d %d", &n, &k);
  int weeks = (n - k) + 1;
  int a[n];
  double soma = 0.0;
  double interm_soma = 0.0;
  int start_counting = 0;
  int teste = 0;
  for (int i = 0; i < n; i++) {
    if (i + 1 == k) {
      start_counting = 1;
    }
    scanf("%d", &a[i]);
    interm_soma += a[i];
    if (start_counting) {
      if (teste) {
        interm_soma -= a[i - k];
      }
      teste = 1;
      soma += interm_soma;
    }
  }
  printf("%.6lf\n", soma / weeks);
  return 0;
}

fn solution() {
    let mut fline = String::new();
    let mut nums = String::new();
    io::stdin()
        .read_line(&mut fline)
        .expect("Can't input first line");
    io::stdin()
        .read_line(&mut nums)
        .expect("can't input second line");
    nums = nums.trim().parse().expect("Can't parse");
    let inpvec: Vec<&str> = fline.split(" ").collect();
    let n: u32 = inpvec[0].trim().parse().expect("Unable to parse n");
    let k: u32 = inpvec[1].trim().parse().expect("Unable to parse k");
    let mut sum: f64 = 0f64;
    let numl: Vec<&str> = nums.split(" ").collect();
    let mut inum: u32;
    let mut count: u32;
    for i in 0..n {
        inum = numl[i as usize].trim().parse().expect("Fucked up!");
        count = cmp::min(i + 1, n - i);
        count = cmp::min(count, n - k + 1);
        count = cmp::min(count, k);
        sum += count as f64 * inum as f64;
    }

    sum /= (n - k + 1) as f64;
    println!("{}", sum);
}


Alice and Bob are playing a game on a matrix, consisting of $$$2$$$ rows and $$$m$$$ columns. The cell in the $$$i$$$-th row in the $$$j$$$-th column contains $$$a_{i, j}$$$ coins in it.Initially, both Alice and Bob are standing in a cell $$$(1, 1)$$$. They are going to perform a sequence of moves to reach a cell $$$(2, m)$$$.The possible moves are:   Move right — from some cell $$$(x, y)$$$ to $$$(x, y + 1)$$$;  Move down — from some cell $$$(x, y)$$$ to $$$(x + 1, y)$$$. First, Alice makes all her moves until she reaches $$$(2, m)$$$. She collects the coins in all cells she visit (including the starting cell).When Alice finishes, Bob starts his journey. He also performs the moves to reach $$$(2, m)$$$ and collects the coins in all cells that he visited, but Alice didn't.The score of the game is the total number of coins Bob collects.Alice wants to minimize the score. Bob wants to maximize the score. What will the score of the game be if both players play optimally?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int m;
    scanf("%d", &m);
    int arr[2][m];
    int sumu = 0;
    int sum1 = 0;
    int min = 1000000000;
    int max = 0;
    for (int i = 0; i < m; i++) {
      scanf("%d", &arr[0][i]);
      sumu += arr[0][i];
    }
    for (int i = 0; i < m; i++) {
      scanf("%d", &arr[1][i]);
    }
    int out = 0;
    for (int i = 0; i < m; i++) {
      sumu = sumu - arr[0][i];
      if (i != 0) {
        sum1 += arr[1][i - 1];
      }
      if (sumu >= sum1) {
        max = sumu;
      } else if (sum1 > sumu) {
        max = sum1;
      }
      if (max < min) {
        min = max;
      }
    }
    printf("%d\n", min);
  }
  return 0;
}

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

    let stdout = io::stdout();
    let handle = stdout.lock();
    let mut buffer = BufWriter::with_capacity(65536, handle);
    let mut first_row_sum: Vec<u64> = Vec::new();
    let mut second_row_sum: Vec<u64> = Vec::new();
    for _t in 0..t {
        line.clear();
        first_row_sum.clear();
        second_row_sum.clear();
        first_row_sum.push(0);
        second_row_sum.push(0);

        stdin.read_line(&mut line).unwrap();
        let column_count: usize = line.trim().parse().unwrap();
        line.clear();

        stdin.read_line(&mut line).unwrap();
        for coins in line.split_whitespace() {
            first_row_sum.push(*first_row_sum.last().unwrap() + coins.parse::<u64>().unwrap());
        }
        line.clear();

        stdin.read_line(&mut line).unwrap();
        for coins in line.split_whitespace() {
            second_row_sum.push(*second_row_sum.last().unwrap() + coins.parse::<u64>().unwrap());
        }

        let mut bob_max_score: u64 = u64::MAX;
        for i in 0..column_count {
            let bob_top_score = first_row_sum[column_count] - first_row_sum[i + 1];
            let bob_bottom_score = second_row_sum[i];
            bob_max_score = std::cmp::min(
                bob_max_score,
                std::cmp::max(bob_top_score, bob_bottom_score),
            );
        }

        writeln!(&mut buffer, "{}", bob_max_score).unwrap();
    }
    buffer.flush().unwrap();
}