A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means that the corresponding column is black.You think that this photo can contain a zebra. In this case the whole photo should consist of several (possibly, only one) alternating black and white stripes of equal width. For example, the photo [0, 0, 0, 1, 1, 1, 0, 0, 0] can be a photo of zebra, while the photo [0, 0, 0, 1, 1, 1, 1] can not, because the width of the black stripe is 3, while the width of the white stripe is 4. Can the given photo be a photo of zebra or not?

int solution() {
  int n = 0;
  scanf("%d", &n);
  int *value = (int *)malloc(sizeof(int[n]));
  for (int i = 0; i < n; i++) {
    scanf("%d", &value[i]);
  }
  int index = 1;
  for (; index < n; index++) {
    if (value[index] != value[0]) {
      break;
    }
  }
  if (n % index != 0) {
    printf("NO");
    return 0;
  }
  for (int i = index; i < n; i += index) {
    if (value[i] == value[i - index]) {
      printf("NO");
      return 0;
    }
    for (int j = 0; j < index; j++) {
      if (value[i + j] != value[i]) {
        printf("NO");
        return 0;
      }
    }
  }
  printf("YES");
  return 0;
}

fn solution() {
    let reader = io::stdin();
    let mut s = String::new();
    let _ = io::stdin().read_line(&mut s).expect("???");
    let numbers: Vec<i32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .trim()
        .split(' ')
        .map(|s| s.parse().unwrap())
        .collect();
    let mut locked: bool = false;
    let mut seq_start = 0;
    let mut current_sequence = 0;
    let mut current = numbers[0];
    for d in numbers {
        if (d != current) & (!locked) {
            seq_start = current_sequence;
            current_sequence = 1;
            locked = true;
            current = d
        } else if (d != current) & (locked) & (current_sequence != seq_start) {
            println!("NO");
            return;
        } else if d != current {
            current_sequence = 1;
            current = d
        } else if !locked {
            current_sequence += 1;
            seq_start += 1;
        } else {
            current_sequence += 1
        }
    }
    if current_sequence != seq_start {
        println!("NO")
    } else {
        println!("YES")
    }
}


Score : <var>300</var> points

Problem Statement

Given are an integer <var>X</var> and an integer sequence of length <var>N</var>: <var>p_1, \ldots, p_N</var>.

Among the integers not contained in the sequence <var>p_1, \ldots, p_N</var> (not necessarily positive), find the integer nearest to <var>X</var>, that is, find the integer whose absolute difference with <var>X</var> is the minimum. If there are multiple such integers, report the smallest such integer.

Constraints

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

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

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

<var>p_1, \ldots, p_N</var> are all distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>N</var>
<var>p_1</var> <var>...</var> <var>p_N</var>

Output

Print the answer.

Sample Input 1

6 5
4 7 10 6 5

Sample Output 1

8

Among the integers not contained in the sequence <var>4, 7, 10, 6, 5</var>, the one nearest to <var>6</var> is <var>8</var>.

Sample Input 2

10 5
4 7 10 6 5

Sample Output 2

9

Among the integers not contained in the sequence <var>4, 7, 10, 6, 5</var>, the ones nearest to <var>10</var> are <var>9</var> and <var>11</var>. We should print the smaller one, <var>9</var>.

Sample Input 3

100 0

Sample Output 3

100

When <var>N = 0</var>, the second line in the input will be empty. Also, as seen here, <var>X</var> itself can be the answer.

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let l1: Vec<i64> = buf
        .split_whitespace()
        .filter_map(|x| x.parse().ok())
        .collect();
    let x = l1[0];
    let _n = l1[1];

    buf.clear();
    stdin().read_line(&mut buf).unwrap();
    let l2: Vec<i64> = buf
        .split_whitespace()
        .filter_map(|x| x.parse().ok())
        .collect();
    let mut answer = -1;
    for p in 0..102 {
        if l2.contains(&p) {
            continue;
        }

        if (p - x).abs() < (answer - x).abs() {
            answer = p;
        }
    }
    print!("{}", answer);
}


Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible:   delete $$$s_1$$$ and $$$s_2$$$: $$$\textbf{10}11001 \rightarrow 11001$$$;  delete $$$s_2$$$ and $$$s_3$$$: $$$1\textbf{01}1001 \rightarrow 11001$$$;  delete $$$s_4$$$ and $$$s_5$$$: $$$101\textbf{10}01 \rightarrow 10101$$$;  delete $$$s_6$$$ and $$$s_7$$$: $$$10110\textbf{01} \rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.

int solution()

{
  int t;
  scanf("%d", &t);
  while (t--) {
    char s[144] = {0};
    int one = 0;
    int zero = 0;
    scanf("%s", s);
    for (int i = 0; s[i] != '\0'; i++) {
      if (s[i] == '1') {
        one++;
      } else {
        zero++;
      }
    }
    if ((one > zero && zero % 2 == 0) || (zero >= one && one % 2 == 0)) {
      printf("NET\n");
    } else {
      printf("DA\n");
    }
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let cs: Vec<char> = lines.next().unwrap().unwrap().chars().collect();
        let zeros = cs.iter().filter(|&&c| c == '0').count();
        let ones = cs.len() - zeros;
        let x = min(zeros, ones);
        println!("{}", if x % 2 == 0 { "NET" } else { "DA" });
    }
}


Score : <var>300</var> points

Problem Statement

A sequence <var>a_1,a_2,... ,a_n</var> is said to be /\/\/\/ when the following conditions are satisfied:

For each <var>i = 1,2,..., n-2</var>, <var>a_i = a_{i+2}</var>.

Exactly two different numbers appear in the sequence.

You are given a sequence <var>v_1,v_2,...,v_n</var> whose length is even.
We would like to make this sequence /\/\/\/ by replacing some of its elements.
Find the minimum number of elements that needs to be replaced.

Constraints

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

<var>n</var> is even.

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

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

Input

Input is given from Standard Input in the following format:

<var>n</var>
<var>v_1</var> <var>v_2</var> <var>...</var> <var>v_n</var>

Output

Print the minimum number of elements that needs to be replaced.

Sample Input 1

4
3 1 3 2

Sample Output 1

1

The sequence <var>3,1,3,2</var> is not /\/\/\/, but we can make it /\/\/\/ by replacing one of its elements: for example, replace the fourth element to make it <var>3,1,3,1</var>.

Sample Input 2

6
105 119 105 119 105 119

Sample Output 2

0

The sequence <var>105,119,105,119,105,119</var> is /\/\/\/.

Sample Input 3

4
1 1 1 1

Sample Output 3

2

The elements of the sequence <var>1,1,1,1</var> are all the same, so it is not /\/\/\/.

fn solution() {
    let mut buf: String = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let n: usize = buf.trim().parse::<usize>().unwrap();
    let mut v1: Vec<usize> = vec![0; 100001];
    let mut v2: Vec<usize> = vec![0; 100001];
    let mut buf: String = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let mut itr = buf.split_whitespace();
    while let Some(i) = itr.next() {
        v1[i.parse::<usize>().unwrap()] += 1;
        if let Some(i) = itr.next() {
            v2[i.parse::<usize>().unwrap()] += 1;
        }
    }
    let (mut m11, mut m12, mut m21, mut m22, mut m31, mut m32): (
        usize,
        usize,
        usize,
        usize,
        usize,
        usize,
    ) = (0, 0, 0, 0, 0, 0);
    for x in 0..100001 {
        if v1[x] > m12 {
            if v1[x] > m11 {
                m12 = m11;
                m11 = v1[x];
                m31 = x;
            } else {
                m12 = v1[x];
            }
        }
        if v2[x] > m22 {
            if v2[x] > m21 {
                m22 = m21;
                m21 = v2[x];
                m32 = x;
            } else {
                m22 = v2[x];
            }
        }
    }
    println!(
        "{}",
        if m31 != m32 {
            n - m11 - m21
        } else {
            std::cmp::min(n - m11 - m22, n - m12 - m21)
        }
    );
}


William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $$$n$$$ cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way:  If the element is dead and it has exactly $$$1$$$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $$$i$$$ the neighbors would be elements with indices $$$i - 1$$$ and $$$i + 1$$$. If there is no element at that index, it is considered to be a dead neighbor.  William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after $$$m$$$ iterations of evolution.

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::<usize>().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 m = it.next().unwrap();

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

        let s = lines.next().unwrap();
        a.extend(
            s.chars()
                .enumerate()
                .filter_map(|(i, c)| if c == '1' { Some(i) } else { None }),
        );

        if let Some(&i) = a.first() {
            let j = i.saturating_sub(m);

            for _ in 0..j {
                write!(&mut output, "0").unwrap();
            }
            for _ in j..i {
                write!(&mut output, "1").unwrap();
            }
        }

        for b in a.windows(2) {
            let i = b[0];
            let j = b[1];
            let k = j - i - 1;
            let q = k / 2;

            let x = std::cmp::min(m, q);

            write!(&mut output, "1").unwrap();

            for _ in 0..x {
                write!(&mut output, "1").unwrap();
            }
            for _ in 2 * x..k {
                write!(&mut output, "0").unwrap();
            }
            for _ in 0..x {
                write!(&mut output, "1").unwrap();
            }
        }

        if let Some(&i) = a.last() {
            let x = std::cmp::min(m + 1, n - i);

            for _ in 0..x {
                write!(&mut output, "1").unwrap();
            }
            for _ in x..n - i {
                write!(&mut output, "0").unwrap();
            }
        } else {
            write!(&mut output, "{}", s).unwrap();
        }

        writeln!(&mut output).unwrap();
    }
}


Debt Hell

Your friend who lives in undisclosed country is involved in debt. He is borrowing 100,000-yen from a loan shark. The loan shark adds 5% interest of the debt and rounds it to the nearest 1,000 above week by week.

Write a program which computes the amount of the debt in <var>n</var> weeks.

Input

An integer <var>n</var> (0 ≤ <var>n</var> ≤ 100) is given in a line.

Output

Print the amout of the debt in a line.

Sample Input

5

Output for the Sample Input

130000

fn solution() {
    let mut debt = 100000;
    let mut buf = String::new();
    if let Ok(_) = stdin().read_line(&mut buf) {
        let week: u32 = buf.trim().parse::<u32>().unwrap();
        for _ in 1..week + 1 {
            let interest = debt * 5 / 100;
            debt += (interest / 1000) * 1000;
            if interest % 1000 > 0 {
                debt += 1000;
            }
        }
        println!("{}", debt);
    }
}


Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.

fn solution() {
    let stdin = io::stdin();
    let mut iter = stdin.lock().lines();
    iter.next().unwrap().unwrap();
    let line = iter.next().unwrap().unwrap();
    let (n, v) = line.bytes().fold((0, vec![]), |(n, mut v), c| {
        v.push(c == 49);
        (n + 1, v)
    });
    println!(
        "{}",
        min(
            n,
            3 + v
                .iter()
                .fold((0, None), |(r, last), c| (
                    if last == Some(!c) { r + 1 } else { r },
                    Some(*c)
                ))
                .0
        )
    );
}


The robot is located on a checkered rectangular board of size $$$n \times m$$$ ($$$n$$$ rows, $$$m$$$ columns). The rows in the board are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and the columns — from $$$1$$$ to $$$m$$$ from left to right.The robot is able to move from the current cell to one of the four cells adjacent by side.The sequence of commands $$$s$$$ executed by the robot is given. Each command is denoted by one of the symbols 'L', 'R', 'D' or 'U', and triggers the movement to left, right, down or up, respectively.The robot can start its movement in any cell. The robot executes the commands starting from the first one, strictly in the order in which they are listed in $$$s$$$. If the robot moves beyond the edge of the board, it falls and breaks. A command that causes the robot to break is not considered successfully executed.The robot's task is to execute as many commands as possible without falling off the board. For example, on board $$$3 \times 3$$$, if the robot starts a sequence of actions $$$s=$$$"RRDLUU" ("right", "right", "down", "left", "up", "up") from the central cell, the robot will perform one command, then the next command will force him to cross the edge. If the robot starts moving from the cell $$$(2, 1)$$$ (second row, first column) then all commands will be executed successfully and the robot will stop at the cell $$$(1, 2)$$$ (first row, second column).    The robot starts from cell $$$(2, 1)$$$ (second row, first column). It moves right, right, down, left, up, and up. In this case it ends in the cell $$$(1, 2)$$$ (first row, second column). Determine the cell from which the robot should start its movement in order to execute as many commands as possible.

int solution() {
  int n;
  int m;
  int i;
  int j;
  int t;
  int up;
  int down;
  int right;
  int left;
  int row;
  int column;
  int h;
  int v;
  scanf("%d", &t);
  char s[1000000 + 1];
  for (j = 0; j < t; j++) {
    up = 0;
    down = 0;
    right = 0;
    left = 0;
    column = 0;
    row = 0;
    scanf("%d%d", &m, &n);
    scanf("%s", s);
    i = 0;
    while (s[i] != '\0') {
      if (s[i] == 'L') {
        row--;
        if ((-row) > left) {
          left = -row;
          if ((left + right) >= n) {
            left--;
            break;
          }
        }
      }
      if (s[i] == 'R') {
        row++;
        if (row > right) {
          right = row;
          if ((left + right) >= n) {
            right--;
            break;
          }
        }
      }
      if (s[i] == 'D') {
        column--;
        if ((-column) > down) {
          down = -column;
          if ((up + down) >= m) {
            down--;
            break;
          }
        }
      }
      if (s[i] == 'U') {
        column++;
        if ((column) > up) {
          up = column;
          if ((up + down) >= m) {
            up--;
            break;
          }
        }
      }
      i++;
    }

    h = 1 + left;
    v = 1 + up;
    printf("%d %d\n", v, h);
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).unwrap();
    let mut input = input.split_ascii_whitespace();

    let t: u64 = input.next().unwrap().parse().unwrap();
    'main_loop: for _ in 0..t {
        let rows: i64 = input.next().unwrap().parse().unwrap();
        let cols: i64 = input.next().unwrap().parse().unwrap();
        let s = input.next().unwrap();
        let mut x = 0i64;
        let mut y = 0i64;
        let mut left = 0;
        let mut right = 0;
        let mut top = 0;
        let mut bottom = 0;
        let mut offsets = Vec::with_capacity(s.len() + 1);
        offsets.push((0, 0, 0, 0));
        for c in s.chars() {
            match c {
                'L' => x -= 1,
                'R' => x += 1,
                'D' => y += 1,
                'U' => y -= 1,
                _ => unreachable!(),
            }
            left = min(x, left);
            right = max(x, right);
            top = min(y, top);
            bottom = max(y, bottom);
            offsets.push((left, right, top, bottom))
        }

        let check = |curr: (i64, i64, i64, i64)| {
            -curr.0 <= cols - 1 - curr.1 && -curr.2 <= rows - 1 - curr.3
        };
        let mut l = 0;
        let mut r = s.len();
        while r - l > 1 {
            let m = l + (r - l) / 2;
            let curr = offsets[m];
            if check(curr) {
                l = m;
            } else {
                r = m;
            }
        }
        if check(offsets[r]) {
            println!("{} {}", -offsets[r].2 + 1, -offsets[r].0 + 1)
        } else {
            println!("{} {}", -offsets[l].2 + 1, -offsets[l].0 + 1)
        }
    }
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> students and <var>M</var> checkpoints on the <var>xy</var>-plane.

The coordinates of the <var>i</var>-th student <var>(1 \leq i \leq N)</var> is <var>(a_i,b_i)</var>, and the coordinates of the checkpoint numbered <var>j</var> <var>(1 \leq j \leq M)</var> is <var>(c_j,d_j)</var>.

When the teacher gives a signal, each student has to go to the nearest checkpoint measured in Manhattan distance.

The Manhattan distance between two points <var>(x_1,y_1)</var> and <var>(x_2,y_2)</var> is <var>|x_1-x_2|+|y_1-y_2|</var>.

Here, <var>|x|</var> denotes the absolute value of <var>x</var>.

If there are multiple nearest checkpoints for a student, he/she will select the checkpoint with the smallest index.

Which checkpoint will each student go to?

Constraints

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

<var>-10^8 \leq a_i,b_i,c_j,d_j \leq 10^8</var>

All input values are integers.

Input

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

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_N</var> <var>b_N</var>
<var>c_1</var> <var>d_1</var>
<var>:</var>
<var>c_M</var> <var>d_M</var>

Output

Print <var>N</var> lines.

The <var>i</var>-th line <var>(1 \leq i \leq N)</var> should contain the index of the checkpoint for the <var>i</var>-th student to go.

Sample Input 1

2 2
2 0
0 0
-1 0
1 0

Sample Output 1

2
1

The Manhattan distance between the first student and each checkpoint is:

For checkpoint <var>1</var>: <var>|2-(-1)|+|0-0|=3</var>

For checkpoint <var>2</var>: <var>|2-1|+|0-0|=1</var>

The nearest checkpoint is checkpoint <var>2</var>. Thus, the first line in the output should contain <var>2</var>.

The Manhattan distance between the second student and each checkpoint is:

For checkpoint <var>1</var>: <var>|0-(-1)|+|0-0|=1</var>

For checkpoint <var>2</var>: <var>|0-1|+|0-0|=1</var>

When there are multiple nearest checkpoints, the student will go to the checkpoint with the smallest index. Thus, the second line in the output should contain <var>1</var>.

Sample Input 2

3 4
10 10
-10 -10
3 3
1 2
2 3
3 5
3 5

Sample Output 2

3
1
2

There can be multiple checkpoints at the same coordinates.

Sample Input 3

5 5
-100000000 -100000000
-100000000 100000000
100000000 -100000000
100000000 100000000
0 0
0 0
100000000 100000000
100000000 -100000000
-100000000 100000000
-100000000 -100000000

Sample Output 3

5
4
3
2
1

int solution() {
  int a;
  int b;
  scanf("%d %d", &a, &b);
  int vetor[2 * a];
  int vet[2 * b];
  for (int x = 0; x < 2 * a; ++x) {
    scanf("%d", &vetor[x]);
  }
  for (int z = 0; z < 2 * b; ++z) {
    scanf("%d", &vet[z]);
  }

  for (int f = 0; f < 2 * a; f += 2) {
    int val = 0;
    int v = 1000000000;
    int pos = 0;
    for (int g = 0; g < 2 * b; g += 2) {
      val = abs(vetor[f] - vet[g]) + abs(vetor[f + 1] - vet[g + 1]);
      if (val < v) {
        v = val;
        pos = (g / 2) + 1;
      }
    }
    printf("%d\n", pos);
  }
  return 0;
}

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    let mut itr = is.split_whitespace().map(|e| e.parse::<i64>().unwrap());
    let n = itr.next().unwrap();
    let m = itr.next().unwrap();
    let mut x = vec![];
    let mut y = vec![];

    for _ in 0..n {
        let mut is = String::new();
        stdin().read_line(&mut is).ok();
        let mut itr = is.split_whitespace().map(|e| e.parse::<i64>().unwrap());
        let a = itr.next().unwrap();
        let b = itr.next().unwrap();
        x.push((a, b));
    }

    for _ in 0..m {
        let mut is = String::new();
        stdin().read_line(&mut is).ok();
        let mut itr = is.split_whitespace().map(|e| e.parse::<i64>().unwrap());
        let a = itr.next().unwrap();
        let b = itr.next().unwrap();
        y.push((a, b));
    }

    for (a, b) in x {
        let mut h = 1 << 30;
        let mut ans = 0;
        for (i, &(c, d)) in y.iter().enumerate() {
            let t = (a - c).abs() + (b - d).abs();
            if t < h {
                h = t;
                ans = i;
            }
        }

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


Score : <var>400</var> points

Problem Statement

You are given <var>N</var> items.

The value of the <var>i</var>-th item <var>(1 \leq i \leq N)</var> is <var>v_i</var>.

Your have to select at least <var>A</var> and at most <var>B</var> of these items.

Under this condition, find the maximum possible arithmetic mean of the values of selected items.

Additionally, find the number of ways to select items so that the mean of the values of selected items is maximized.

Constraints

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

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

<var>1 \leq v_i \leq 10^{15}</var>

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

Input

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

<var>N</var> <var>A</var> <var>B</var>
<var>v_1</var>
<var>v_2</var>
...
<var>v_N</var>

Output

Print two lines.

The first line should contain the maximum possible arithmetic mean of the values of selected items. The output should be considered correct if the absolute or relative error is at most <var>10^{-6}</var>.

The second line should contain the number of ways to select items so that the mean of the values of selected items is maximized.

Sample Input 1

5 2 2
1 2 3 4 5

Sample Output 1

4.500000
1

The mean of the values of selected items will be maximized when selecting the fourth and fifth items. Hence, the first line of the output should contain <var>4.5</var>.

There is no other way to select items so that the mean of the values will be <var>4.5</var>, and thus the second line of the output should contain <var>1</var>.

Sample Input 2

4 2 3
10 20 10 10

Sample Output 2

15.000000
3

There can be multiple ways to select items so that the mean of the values will be maximized.

Sample Input 3

5 1 5
1000000000000000 999999999999999 999999999999998 999999999999997 999999999999996

Sample Output 3

1000000000000000.000000
1

int solution(void) {
  int n;
  int l;
  int r;
  scanf("%i %i %i", &n, &l, &r);

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

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

    unsigned long long tmp = a[i];
    a[i] = a[min_idx];
    a[min_idx] = tmp;
  }

  unsigned long long f[51][51];
  for (int i = 0; i <= 50; i++) {
    f[i][0] = f[i][i] = 1;
    for (int j = 1; j < i; j++) {
      f[i][j] = f[i - 1][j] + f[i - 1][j - 1];
    }
  }

  unsigned long long p = 0;
  unsigned long long q = 1;
  for (int j = l; j <= r; j++) {
    unsigned long long sum = 0;
    for (int i = n - j; i < n; i++) {
      sum += a[i];
    }
    if (sum * q > p * j) {
      p = sum;
      q = j;
    }
  }

  unsigned long long tot = 0;
  for (int j = l; j <= r; j++) {
    unsigned long long sum = 0;
    for (int i = n - j; i < n; i++) {
      sum += a[i];
    }

    if (sum * q == p * j) {
      int count = 0;
      for (int i = 0; i < n; i++) {
        if (a[n - j] == a[i]) {
          count++;
        }
      }

      int m = 1;
      for (int i = n - j + 1; i < n && a[i] == a[i - 1]; i++) {
        m++;
      }

      tot += f[count][m];
    }
  }

  printf("%.7f\n%llu\n", (double)p / q, tot);

  return 0;
}

fn solution() {
    input! {
        N: usize,
        A: usize,
        B: usize,
        V: [u64; N],
    }
    let mut V = V;
    V.sort();
    V.reverse();

    let mut total = 0;
    for i in 0..A {
        total += V[i];
    }
    let ans1 = (total as f64) / (A as f64);

    let mut cnt0 = 0;
    let mut cnt1 = 0;
    let mut cnt2 = 0;
    for i in 0..N {
        if V[i] == V[0] {
            cnt0 += 1;
        }
        if V[i] == V[A - 1] {
            cnt1 += 1;
        }
        if V[i] > V[A - 1] {
            cnt2 += 1;
        }
    }

    let mut ans2 = 1;

    if cnt0 > A {
        ans2 = 0;
        for i in A..(min(cnt0, B) + 1) {
            let mut tmp = 1;
            let c = cnt0;
            let r = i;
            for j in 0..r {
                tmp *= c - j;
                tmp /= j + 1;
            }
            ans2 += tmp;
        }
    } else {
        if cnt1 + cnt2 > A {
            let c = cnt1;
            let r = A - cnt2;
            for i in 0..r {
                ans2 *= c - i;
                ans2 /= i + 1;
            }
        }
    }

    println!("{}", ans1);
    println!("{}", ans2);
}


Stanley has decided to buy a new desktop PC made by the company "Monoblock", and to solve captcha on their website, he needs to solve the following task.The awesomeness of an array is the minimum number of blocks of consecutive identical numbers in which the array could be split. For example, the awesomeness of an array   $$$[1, 1, 1]$$$ is $$$1$$$;  $$$[5, 7]$$$ is $$$2$$$, as it could be split into blocks $$$[5]$$$ and $$$[7]$$$;  $$$[1, 7, 7, 7, 7, 7, 7, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9]$$$ is 3, as it could be split into blocks $$$[1]$$$, $$$[7, 7, 7, 7, 7, 7, 7]$$$, and $$$[9, 9, 9, 9, 9, 9, 9, 9, 9]$$$. You are given an array $$$a$$$ of length $$$n$$$. There are $$$m$$$ queries of two integers $$$i$$$, $$$x$$$. A query $$$i$$$, $$$x$$$ means that from now on the $$$i$$$-th element of the array $$$a$$$ is equal to $$$x$$$.After each query print the sum of awesomeness values among all subsegments of array $$$a$$$. In other words, after each query you need to calculate $$$$$$\sum\limits_{l = 1}^n \sum\limits_{r = l}^n g(l, r),$$$$$$ where $$$g(l, r)$$$ is the awesomeness of the array $$$b = [a_l, a_{l + 1}, \ldots, a_r]$$$.

fn solution() -> io::Result<()> {
    let stdin_ = io::stdin();
    let mut stdin = stdin_.lock();
    let stdout_ = io::stdout();
    let mut stdout = BufWriter::new(stdout_.lock());

    let mut buf = String::new();
    stdin.read_line(&mut buf)?;
    let toks: Vec<&str> = buf.split_whitespace().collect();
    let N: usize = toks[0].parse().unwrap();
    let M: i64 = toks[1].parse().unwrap();

    let mut buf = String::new();
    stdin.read_line(&mut buf)?;
    let mut A: Vec<i64> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let mut Adiff: Vec<i64> = vec![0; N - 1];
    let mut acc = ((N * (N + 1)) / 2) as i64;
    for i in 1..N {
        Adiff[i - 1] = (A[i] != A[i - 1]) as i64;
        acc += Adiff[i - 1] * ((i * (N - i)) as i64);
    }
    eprintln!("starting acc: {acc}");
    for _ in 0..M {
        let mut buf = String::new();
        stdin.read_line(&mut buf)?;
        let toks: Vec<&str> = buf.split_whitespace().collect();
        let ix: usize = toks[0].parse().unwrap();
        let val: i64 = toks[1].parse().unwrap();

        A[ix - 1] = val;

        if ix < N {
            let prev = Adiff[ix - 1];
            Adiff[ix - 1] = (A[ix - 1] != A[ix]) as i64;
            acc += (Adiff[ix - 1] - prev) * ((ix * (N - ix)) as i64);
        }

        if ix > 1 {
            let prev = Adiff[ix - 1 - 1];
            Adiff[ix - 1 - 1] = (A[ix - 1] != A[ix - 2]) as i64;
            acc += (Adiff[ix - 1 - 1] - prev) * (((ix - 1) * (N - (ix - 1))) as i64);
        }

        stdout.write_fmt(format_args!("{acc}\n"))?;
    }

    Ok(())
}


You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

int solution() {
  int t;
  int n;
  int x;
  int m;
  int i;
  int l;
  int r;
  int l_v = -1;
  int r_v = -1;
  int flag = 0;
  scanf("%d", &t);
  while (t--) {
    scanf("%d %d %d", &n, &x, &m);
    flag = 0;
    l_v = -1;
    r_v = -1;
    for (i = 1; i <= m; i++) {
      scanf("%d %d", &l, &r);
      if (x >= l && x <= r && flag == 0) {
        l_v = l;
        r_v = r;
        flag = 1;
      }
      if (l < l_v && r >= l_v && flag) {
        l_v = l;
      }
      if (r > r_v && l <= r_v && flag) {
        r_v = r;
      }
    }
    printf("%d\n", r_v - l_v + 1);
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut buffer = String::with_capacity(32);

    stdin.read_line(&mut buffer).unwrap();
    let t: i32 = buffer.trim_end().parse().unwrap();

    for _ in 0..t {
        buffer.clear();
        stdin.read_line(&mut buffer).unwrap();
        let data = buffer
            .split_whitespace()
            .map(|x| x.parse::<i32>().unwrap())
            .collect::<Vec<_>>();

        let x = data[1];
        let m = data[2];

        let mut l = x;
        let mut r = x;

        for _ in 0..m {
            buffer.clear();
            stdin.read_line(&mut buffer).unwrap();
            let data = buffer
                .split_whitespace()
                .map(|x| x.parse::<i32>().unwrap())
                .collect::<Vec<_>>();

            let l_i = data[0];
            let r_i = data[1];

            if i32::abs(l + r - l_i - r_i) <= r_i - l_i + r - l {
                l = i32::min(l_i, l);
                r = i32::max(r_i, r);
            }
        }

        println!("{}", r - l + 1);
    }
}


Gardener Alexey teaches competitive programming to high school students. To congratulate Alexey on the Teacher's Day, the students have gifted him a collection of wooden sticks, where every stick has an integer length. Now Alexey wants to grow a tree from them.The tree looks like a polyline on the plane, consisting of all sticks. The polyline starts at the point $$$(0, 0)$$$. While constructing the polyline, Alexey will attach sticks to it one by one in arbitrary order. Each stick must be either vertical or horizontal (that is, parallel to $$$OX$$$ or $$$OY$$$ axis). It is not allowed for two consecutive sticks to be aligned simultaneously horizontally or simultaneously vertically. See the images below for clarification.Alexey wants to make a polyline in such a way that its end is as far as possible from $$$(0, 0)$$$. Please help him to grow the tree this way.Note that the polyline defining the form of the tree may have self-intersections and self-touches, but it can be proved that the optimal answer does not contain any self-intersections or self-touches.

int solution() {
  long long n;
  long long a[10000] = {0};
  long long b;
  long long sum = 0;
  long long d = 0;
  long long e = 0;
  scanf("%lld", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld", &b);
    a[b]++;
    sum += b;
  }
  for (int i = 0;; i++) {
    if (a[i] == n) {
      d = n / 2 * i;
    } else {
      if (e + a[i] <= n / 2) {
        e += a[i];
        if (a[i] > 0) {
          d += i * a[i];
        }
      } else {
        d = d + (n / 2 - e) * i;

        break;
      }
    }
  }
  printf("%lld\n", (d * d) + ((sum - d) * (sum - d)));
  return 0;
}

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

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("failed to read input");

    let mut sticks: Vec<u64> = input
        .split_whitespace()
        .map(|x| x.parse::<u64>().unwrap())
        .collect();
    sticks.sort();

    let sum1: u64 = sticks[0..(sticks.len() / 2)].iter().sum();
    let sum2: u64 = sticks[(sticks.len() / 2)..].iter().sum();

    println!("{}", sum1 * sum1 + sum2 * sum2);
}


Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.

int solution() {
  int n = 0;

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

  int sd[2] = {0};
  int inicio = 0;
  int fim = n - 1;
  for (l = 0; l < n; l++) {
    if (cartas[inicio] > cartas[fim]) {
      sd[l % 2] += cartas[inicio];
      inicio++;

    } else {
      sd[l % 2] += cartas[fim];
      fim--;
    }
  }

  printf("%i %i\n", sd[0], sd[1]);
  return 0;
}

fn solution() {
    use std::io;
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<u32>().unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let ns: Vec<u32> = buf
        .split(" ")
        .map(|str| str.trim().parse::<u32>().unwrap())
        .collect();
    let (mut i, mut j) = (0, ns.len() - 1);
    let (mut s, mut d) = (0, 0);
    for k in 0..n {
        let picked;
        if ns[i] > ns[j] {
            picked = ns[i];
            i += 1;
        } else {
            picked = ns[j];
            j = j.saturating_sub(1)
        }
        if k % 2 == 0 {
            s += picked;
        } else {
            d += picked;
        }
    }
    println!("{} {}", s, d);
}


Score : <var>200</var> points

Problem Statement

We have a grid with <var>N</var> rows and <var>M</var> columns of squares. Initially, all the squares are white.

There is a button attached to each row and each column.
When a button attached to a row is pressed, the colors of all the squares in that row are inverted; that is, white squares become black and vice versa.
When a button attached to a column is pressed, the colors of all the squares in that column are inverted.

Takahashi can freely press the buttons any number of times. Determine whether he can have exactly <var>K</var> black squares in the grid.

Constraints

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

<var>0 \leq K \leq NM</var>

Input

Input is given from Standard Input in the following format:

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

Output

If Takahashi can have exactly <var>K</var> black squares in the grid, print Yes; otherwise, print No.

Sample Input 1

2 2 2

Sample Output 1

Yes

Press the buttons in the order of the first row, the first column.

Sample Input 2

2 2 1

Sample Output 2

No

Sample Input 3

3 5 8

Sample Output 3

Yes

Press the buttons in the order of the first column, third column, second row, fifth column.

Sample Input 4

7 9 20

Sample Output 4

No

int solution(void) {

  int n = 0;
  int m = 0;
  int k = 0;

  int ans = 0;

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

  for (int a = 0; a <= n && ans == 0; a++) {
    for (int b = 0; b <= m && ans == 0; b++) {
      if ((a * m - 2 * a * b + b * n) == k) {
        ans = 1;
        break;
      }
    }
  }
  if (ans) {
    printf("Yes\n");
  } else {
    printf("No\n");
  }
}

fn solution() {
    let mut string = String::new();
    io::stdin().read_line(&mut string).expect("read error");
    let int_vec: Vec<u32> = string
        .trim()
        .split(" ")
        .map(|x| x.parse::<u32>().expect("Not an integer!"))
        .collect();

    let m = min(int_vec[0], int_vec[1]);
    let n = max(int_vec[0], int_vec[1]);
    let k = int_vec[2];

    for i in 0..(m + 1) {
        for j in 0..(n + 1) {
            if m * n - (m - i) * (n - j) - i * j == k {
                println!("Yes");
                return;
            }
        }
    }
    println!("No");
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> of length <var>N</var>.
Among its subsequences, count the ones such that all characters are different, modulo <var>10^9+7</var>. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.

Here, a subsequence of a string is a concatenation of one or more characters from the string without changing the order.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of the subsequences such that all characters are different, modulo <var>10^9+7</var>.

Sample Input 1

4
abcd

Sample Output 1

15

Since all characters in <var>S</var> itself are different, all its subsequences satisfy the condition.

Sample Input 2

3
baa

Sample Output 2

5

The answer is five: b, two occurrences of a, two occurrences of ba. Note that we do not count baa, since it contains two as.

Sample Input 3

5
abcab

Sample Output 3

17

int solution() {
  int n;
  long mod = 1000000007;
  scanf("%d\n", &n);
  char a[n];
  int b[26];
  for (int i = 0; i < 26; ++i) {
    b[i] = 0;
  }
  for (int i = 0; i < n; ++i) {
    scanf("%c", &a[i]);
  }
  for (int i = 0; i < n; ++i) {
    b[a[i] - 'a']++;
  }
  long answer = 1;
  for (int i = 0; i < 26; ++i) {
    answer *= (1 + (long)b[i]);
    answer = answer % mod;
  }
  answer--;
  answer = answer % mod;
  printf("%ld\n", answer);
  return 0;
}

fn solution() {
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let _n = st.trim().parse::<i32>().unwrap();
    let mut st = String::new();
    stdin().read_line(&mut st).unwrap();
    let s: Vec<char> = st.trim().chars().collect();
    let mut map: HashMap<&char, i64> = HashMap::new();
    for i in &s {
        let count = map.entry(i).or_insert(1);
        *count += 1;
    }
    let mo = 1000000007;
    let mut result: i64 = 1;
    for (_i, j) in map.iter() {
        result = (result * j) % mo;
    }
    println!("{}", result - 1);
}


Score : <var>200</var> points

Problem Statement

We have an integer sequence <var>A</var>, whose length is <var>N</var>.

Find the number of the non-empty contiguous subsequences of <var>A</var> whose sums are <var>0</var>.
Note that we are counting the ways to take out subsequences.
That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from different positions.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Find the number of the non-empty contiguous subsequences of <var>A</var> whose sum is <var>0</var>.

Sample Input 1

6
1 3 -4 2 2 -2

Sample Output 1

3

There are three contiguous subsequences whose sums are <var>0</var>: <var>(1,3,-4)</var>, <var>(-4,2,2)</var> and <var>(2,-2)</var>.

Sample Input 2

7
1 -1 1 -1 1 -1 1

Sample Output 2

12

In this case, some subsequences that have the same contents but are taken from different positions are counted individually.
For example, three occurrences of <var>(1, -1)</var> are counted.

Sample Input 3

5
1 -2 3 -4 5

Sample Output 3

0

There are no contiguous subsequences whose sums are <var>0</var>.

int solution() {
  int i;
  int N;
  long long A[200001] = {};
  scanf("%d", &N);
  for (i = 1; i <= N; i++) {
    scanf("%lld", &(A[i]));
  }

  long long h;
  list *p;
  list data[200001] = {};
  list *hash[100003] = {&(data[0])};
  for (i = 1; i <= N; i++) {
    data[i].value = data[i - 1].value + A[i];
    for (h = llabs(data[i].value) % 100003, p = hash[h]; p != NULL;
         p = p->next) {
      if (data[i].value == p->value) {
        break;
      }
    }
    if (p != NULL) {
      (p->num)++;
    } else {
      data[i].next = hash[h];
      data[i].num = 0;
      hash[h] = &(data[i]);
    }
  }

  long long ans = 0;
  for (i = 0; i < 100003; i++) {
    for (p = hash[i]; p != NULL; p = p->next) {
      ans += p->num * (p->num + 1) / 2;
    }
  }

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

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let mut ary: Vec<i64> = vec![0; n];
    for i in 0..n {
        ary[i] = iter.next().unwrap().parse().unwrap();
    }
    let mut csum: Vec<i64> = vec![0; n + 1];
    for i in 0..n {
        csum[i + 1] = csum[i] + ary[i];
    }

    let mut ret: i64 = 0;
    let mut hmap: HashMap<i64, i64> = HashMap::new();
    for c in csum {
        let v = { hmap.get(&c).unwrap_or(&0) + 1 };
        hmap.insert(c, v);
    }
    for (_, v) in hmap {
        if v >= 2 {
            ret += v * (v - 1) / 2;
        }
    }
    println!("{}", ret);
}


Score : <var>400</var> points

Problem Statement

You are given a tree with <var>N</var> vertices.

Here, a tree is a kind of graph, and more specifically, a connected undirected graph with <var>N-1</var> edges, where <var>N</var> is the number of its vertices.

The <var>i</var>-th edge <var>(1≤i≤N-1)</var> connects Vertices <var>a_i</var> and <var>b_i</var>, and has a length of <var>c_i</var>.

You are also given <var>Q</var> queries and an integer <var>K</var>. In the <var>j</var>-th query <var>(1≤j≤Q)</var>:

find the length of the shortest path from Vertex <var>x_j</var> and Vertex <var>y_j</var> via Vertex <var>K</var>.

Constraints

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

<var>1≤a_i,b_i≤N (1≤i≤N-1)</var>

<var>1≤c_i≤10^9 (1≤i≤N-1)</var>

The given graph is a tree.

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

<var>1≤K≤N</var>

<var>1≤x_j,y_j≤N (1≤j≤Q)</var>

<var>x_j≠y_j (1≤j≤Q)</var>

<var>x_j≠K,y_j≠K (1≤j≤Q)</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>a_1</var> <var>b_1</var> <var>c_1</var>
<var>:</var>
<var>a_{N-1}</var> <var>b_{N-1}</var> <var>c_{N-1}</var>
<var>Q</var> <var>K</var>
<var>x_1</var> <var>y_1</var>
<var>:</var>
<var>x_{Q}</var> <var>y_{Q}</var>

Output

Print the responses to the queries in <var>Q</var> lines.

In the <var>j</var>-th line <var>j(1≤j≤Q)</var>, print the response to the <var>j</var>-th query.

Sample Input 1

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

Sample Output 1

3
2
4

The shortest paths for the three queries are as follows:

Query <var>1</var>: Vertex <var>2</var> → Vertex <var>1</var> → Vertex <var>2</var> → Vertex <var>4</var> : Length <var>1+1+1=3</var>

Query <var>2</var>: Vertex <var>2</var> → Vertex <var>1</var> → Vertex <var>3</var> : Length <var>1+1=2</var>

Query <var>3</var>: Vertex <var>4</var> → Vertex <var>2</var> → Vertex <var>1</var> → Vertex <var>3</var> → Vertex <var>5</var> : Length <var>1+1+1+1=4</var>

Sample Input 2

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

Sample Output 2

5
14
22

The path for each query must pass Vertex <var>K=2</var>.

Sample Input 3

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

Sample Output 3

17000000000

fn solution() {
    input! {
        n: usize,
        es: [(usize1, usize1, usize); n - 1],
        q: usize,
        k: usize1,
        qs: [(usize1, usize1); q]
    }
    let mut t = vec![vec![]; n];
    for &(a, b, c) in &es {
        t[a].push((b, c));
        t[b].push((a, c));
    }
    let mut d = vec![1 << 60; n];
    d[k] = 0;
    let mut q = VecDeque::new();
    q.push_back((k, k));
    while let Some((u, p)) = q.pop_front() {
        for &(v, c) in &t[u] {
            if v == p {
                continue;
            }
            d[v] = d[u] + c;
            q.push_back((v, u));
        }
    }
    for &(x, y) in &qs {
        println!("{}", d[x] + d[y]);
    }
}


There are $$$n$$$ cats in a line, labeled from $$$1$$$ to $$$n$$$, with the $$$i$$$-th cat at position $$$i$$$. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.For example, if there are $$$3$$$ cats, this is a valid reordering: $$$[3, 1, 2]$$$. No cat is in its original position. The total distance the cats move is $$$1 + 1 + 2 = 4$$$ as cat $$$1$$$ moves one place to the right, cat $$$2$$$ moves one place to the right, and cat $$$3$$$ moves two places to the left.

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(1) {
        let n: u32 = l.unwrap().parse().unwrap();
        let mut x = 1;
        let mut r = String::new();
        if !n.is_multiple_of(2) {
            write!(r, "3 1 2 ").ok();
            x = 4;
        }
        for y in (x..n).step_by(2) {
            write!(r, "{} {} ", y + 1, y).ok();
        }
        writeln!(o, "{}", r.trim()).ok();
    }
}


You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.

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

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

    let stdin = io::stdin();

    let mut handle = stdin.lock();

    handle.read_to_string(&mut buffer).unwrap();

    let s = buffer
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .collect::<Vec<i32>>();
    let mut it = s.iter();
    let n = *it.next().unwrap();
    let m = *it.next().unwrap();
    let mut pos = 0;
    for _ in 0..n {
        let num = *it.next().unwrap();
        pos += num;
        let num_pages = pos / m;
        pos %= m;
        println!("{}", num_pages);
    }
}


Score : <var>100</var> points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most <var>X</var> pieces of takoyaki at a time, taking <var>T</var> minutes regardless of the number of pieces to make.

How long does it take to make <var>N</var> takoyaki?

Constraints

<var>1 \leq N,X,T \leq 1000</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>T</var>

Output

Print an integer representing the minimum number of minutes needed to make <var>N</var> pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make <var>12</var> pieces of takoyaki in the first <var>6</var> minutes and <var>8</var> more in the next <var>6</var> minutes, so he can make <var>20</var> in a total of <var>12</var> minutes.

Note that being able to make <var>12</var> in <var>6</var> minutes does not mean he can make <var>2</var> in <var>1</var> minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.

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

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

    let mut iter = buf.split_whitespace();

    let n: usize = iter.next().unwrap().parse().unwrap();
    let x: usize = iter.next().unwrap().parse().unwrap();
    let t: usize = iter.next().unwrap().parse().unwrap();

    println!("{}", n.div_ceil(x) * t);
}


Mihai has an $$$8 \times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked.     An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.

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

    let mut buffer = String::new();

    stdin.read_line(&mut buffer).unwrap();
    let count: u32 = buffer.trim().parse().unwrap();

    for _ in 0..count {
        stdin.read_line(&mut buffer).unwrap();
        let mut candidate_x = 0;
        let mut candidate_y = 0;

        let mut has_had_2s = false;
        let mut has_had_1 = false;

        for y in 1..=8 {
            buffer.clear();
            stdin.read_line(&mut buffer).unwrap();

            let mut count_acc = 0;
            let mut acc_pos = 0;

            for (x, value) in buffer.trim().bytes().enumerate() {
                let x = x + 1;

                if value == b'#' {
                    count_acc += 1;
                    acc_pos = x;
                }
            }
            if count_acc == 2 {
                has_had_2s = true;
            }

            let x = acc_pos;
            if count_acc == 1 && has_had_2s && !has_had_1 {
                candidate_x = x;
                candidate_y = y;
                has_had_1 = true;
            }
        }
        println!("{} {}", candidate_y, candidate_x);
    }
}


Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.According to the schedule, a student can take the exam for the i-th subject on the day number ai. However, Valera has made an arrangement with each teacher and the teacher of the i-th subject allowed him to take an exam before the schedule time on day bi (bi < ai). Thus, Valera can take an exam for the i-th subject either on day ai, or on day bi. All the teachers put the record of the exam in the student's record book on the day of the actual exam and write down the date of the mark as number ai.Valera believes that it would be rather strange if the entries in the record book did not go in the order of non-decreasing date. Therefore Valera asks you to help him. Find the minimum possible value of the day when Valera can take the final exam if he takes exams so that all the records in his record book go in the order of non-decreasing date.

int solution() {
  int n;
  int arr[5001];
  int arr2[5001];
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d %d", &arr[i], &arr2[i]);
  }
  for (int i = 1; i <= n; i++) {
    for (int j = i + 1; j <= n; j++) {
      if (arr[j] < arr[i]) {
        int x = arr[i];
        arr[i] = arr[j];
        arr[j] = x;

        x = arr2[i];
        arr2[i] = arr2[j];
        arr2[j] = x;
      }

      if (arr[j] == arr[i]) {
        if (arr2[j] < arr2[i]) {
          int y = arr2[i];
          arr2[i] = arr2[j];
          arr2[j] = y;
        }
      }
    }
  }

  int d = arr2[1];
  for (int i = 2; i <= n; i++) {
    if (arr2[i] >= d) {
      d = arr2[i];
    } else {
      d = arr[i];
    }
  }
  printf("%d", d);

  return 0;
}

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

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

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

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

        input.push(words)
    }

    input.sort();

    let mut c: i32 = 0;

    for i in input {
        if i[1] < c {
            c = i[0];
        } else {
            c = i[1];
        }
    }

    println!("{}", c)
}


There is a string $$$s$$$ of length $$$3$$$, consisting of uppercase and lowercase English letters. Check if it is equal to "YES" (without quotes), where each letter can be in any case. For example, "yES", "Yes", "yes" are all allowable.

fn solution() {
    std::io::stdin().lines().skip(1).flatten().for_each(|s| {
        if let &[a, b, c] = s.as_bytes() {
            if [a | b' ', b | b' ', c | b' '] == [b'y', b'e', b's'] {
                println!("YES");
            } else {
                println!("NO");
            }
        };
    });
}


Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x that a ≤ x ≤ b and x is divisible by k.

int solution() {
  long long int a;
  long long int b;
  long long int k;
  long long int r;
  long long int ra;
  long long int rb;
  long long int temp;
  scanf("%lli", &k);
  scanf("%lli", &a);
  scanf("%lli", &b);
  if (k != 0) {
    if (b > 0) {
      if (a == b) {
        if (k > llabs(b)) {
          r = 0;
        } else if ((b + (b % k)) > b) {
          r = 0;
        } else {
          r = 1;
        }
      } else {

        if (k <= b) {
          if (b % k != 0) {
            b = b - (b % k);
            rb = (b / k) + 1;
          } else {
            rb = (b / k) + 1;
          }
          if (a > 0)

          {
            if (a % k != 0) {
              a = a - (a % k) + k;
              ra = (a / k);
            } else {
              ra = (a / k);
            }
            r = rb - llabs(ra);
          } else {
            if (a % k != 0) {
              a = a - (a % k);
              ra = (a / k);
            } else {
              ra = (a / k);
            }
            r = rb + llabs(ra);
          }

        } else {
          if (a <= 0) {
            r = 1;
          } else {
            r = 0;
          }
        }
      }
    } else {
      if (b == 0) {
        if (a == 0) {
          r = 1;
        } else {

          temp = llabs(a);
          a = llabs(b);
          b = temp;
          if (b % k != 0) {
            b = b - (b % k);
            rb = (b / k) + 1;
          } else {
            rb = (b / k) + 1;
          }
          r = rb;
        }
      } else {
        if (a == b) {
          if (k > llabs(b)) {
            r = 0;
          } else {
            r = 1;
          }
        } else {

          temp = llabs(a);
          a = llabs(b);
          b = temp;
          if (b % k != 0) {
            b = b - (b % k);
            rb = (b / k) + 1;
          } else {
            rb = (b / k) + 1;
          }
          if (a % k != 0) {
            a = a - (a % k) + k;
            ra = (a / k);
          } else {
            ra = (a / k);
          }
          r = llabs(rb) - llabs(ra);
        }
      }
    }
  } else {
    r = 0;
  }
  printf("%lli", r);
  return 0;
}

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

    let k: u64 = line.next().unwrap().parse().unwrap();
    let a: i64 = line.next().unwrap().parse().unwrap();
    let b: i64 = line.next().unwrap().parse().unwrap();

    let first = a + (k as i64 - a % k as i64) % k as i64;
    let last = b - (k as i64 + b % k as i64) % k as i64;

    println!("{}", (last - first) / k as i64 + 1);
}


Luca has a cypher made up of a sequence of $$$n$$$ wheels, each with a digit $$$a_i$$$ written on it. On the $$$i$$$-th wheel, he made $$$b_i$$$ moves. Each move is one of two types:   up move (denoted by $$$\texttt{U}$$$): it increases the $$$i$$$-th digit by $$$1$$$. After applying the up move on $$$9$$$, it becomes $$$0$$$.  down move (denoted by $$$\texttt{D}$$$): it decreases the $$$i$$$-th digit by $$$1$$$. After applying the down move on $$$0$$$, it becomes $$$9$$$.     Example for $$$n=4$$$. The current sequence is 0 0 0 0. Luca knows the final sequence of wheels and the moves for each wheel. Help him find the original sequence and crack the cypher.

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let t: i32 = input.trim().parse().unwrap();
    for _ in 0..t {
        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        let n: usize = input.trim().parse().unwrap();

        input.clear();
        io::stdin().read_line(&mut input).unwrap();
        let mut final_state: Vec<i32> = input
            .split_whitespace()
            .map(|x| x.parse().unwrap())
            .collect();

        for i in 0..n {
            input.clear();
            io::stdin().read_line(&mut input).unwrap();
            let input: Vec<&str> = input.split_whitespace().collect();
            let input = String::from(input[1]);
            for j in input.chars() {
                if j == 'D' {
                    final_state[i] += 1;
                    if final_state[i] == 10 {
                        final_state[i] = 0;
                    }
                } else {
                    final_state[i] -= 1;
                    if final_state[i] == -1 {
                        final_state[i] = 9
                    }
                }
            }
        }
        for i in final_state {
            print!("{} ", i);
        }
        println!();
    }
}


Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person.    A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.

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

  int a[t];
  int b[t];
  int c[t];

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

  int ans[t];

  for (int i = 0; i < t; i++) {
    int ab = abs(a[i] - b[i]);
    if (2 * ab < c[i] || 2 * ab < a[i] || 2 * ab < b[i]) {
      ans[i] = -1;
      continue;
    }

    ans[i] = c[i] > ab ? c[i] - ab : c[i] + ab;
  }

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

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(1) {
        if let [a, b, c] = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<i32>().unwrap())
            .collect::<Vec<_>>()[..]
        {
            let m = (a - b).abs();
            let p = if m < c { c - m } else { m + c };
            writeln!(
                o,
                "{}",
                if c > 2 * m || p > 2 * m || a.max(b) > 2 * m {
                    -1
                } else {
                    p
                }
            )
            .ok();
        }
    }
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var> consisting of lowercase English letters. Determine whether all the characters in <var>S</var> are different.

Constraints

<var>2 ≤ |S| ≤ 26</var>, where <var>|S|</var> denotes the length of <var>S</var>.

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If all the characters in <var>S</var> are different, print yes (case-sensitive); otherwise, print no.

Sample Input 1

uncopyrightable

Sample Output 1

yes

Sample Input 2

different

Sample Output 2

no

Sample Input 3

no

Sample Output 3

yes

int solution(void) {
  char S[100];
  scanf("%s\n", S);
  int tbl[26];
  memset(tbl, 0, sizeof(tbl));
  char *p = S;
  while (*p) {
    int index = (*p) - 'a';
    if (tbl[index] > 0) {
      printf("no\n");
      return 0;
    }
    tbl[index]++;
    p++;
  }
  printf("yes\n");
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let s: Vec<char> = buf.trim().chars().collect();
    let mut set = HashSet::new();
    let mut flag = true;
    for i in s {
        if !set.insert(i) {
            flag = false;
            println!("no");
            break;
        }
    }
    if flag {
        println!("yes");
    }
}


A sequence of $$$n$$$ numbers is called permutation if it contains all numbers from $$$1$$$ to $$$n$$$ exactly once. For example, the sequences $$$[3, 1, 4, 2]$$$, [$$$1$$$] and $$$[2,1]$$$ are permutations, but $$$[1,2,1]$$$, $$$[0,1]$$$ and $$$[1,3,4]$$$ are not.For a given number $$$n$$$ you need to make a permutation $$$p$$$ such that two requirements are satisfied at the same time:  For each element $$$p_i$$$, at least one of its neighbors has a value that differs from the value of $$$p_i$$$ by one. That is, for each element $$$p_i$$$ ($$$1 \le i \le n$$$), at least one of its neighboring elements (standing to the left or right of $$$p_i$$$) must be $$$p_i + 1$$$, or $$$p_i - 1$$$.  the permutation must have no fixed points. That is, for every $$$i$$$ ($$$1 \le i \le n$$$), $$$p_i \neq i$$$ must be satisfied. Let's call the permutation that satisfies these requirements funny.For example, let $$$n = 4$$$. Then [$$$4, 3, 1, 2$$$] is a funny permutation, since:   to the right of $$$p_1=4$$$ is $$$p_2=p_1-1=4-1=3$$$;  to the left of $$$p_2=3$$$ is $$$p_1=p_2+1=3+1=4$$$;  to the right of $$$p_3=1$$$ is $$$p_4=p_3+1=1+1=2$$$;  to the left of $$$p_4=2$$$ is $$$p_3=p_4-1=2-1=1$$$.  for all $$$i$$$ is $$$p_i \ne i$$$. For a given positive integer $$$n$$$, output any funny permutation of length $$$n$$$, or output -1 if funny permutation of length $$$n$$$ does not exist.

int solution(void) {
  int n = 0;
  int number = 0;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &number);
    if (number == 3) {
      printf("-1\n");
    } else {
      printf("%d %d", number, number - 1);
      for (int j = 1; j <= number - 2; j++) {
        printf(" %d", j);
      }
      printf("\n");
    }
  }
}

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

    for _ in 0..tests {
        let mut testline = String::new();
        io::stdin().read_line(&mut testline).unwrap();
        let length = testline.trim().parse().unwrap();
        match length {
            3 => println!("-1"),
            _ => {
                for i in 3..=length {
                    print!("{i} ")
                }
                println!("2 1")
            }
        }
    }
}


Score : <var>200</var> points

Problem Statement

The word internationalization is sometimes abbreviated to i18n.
This comes from the fact that there are <var>18</var> letters between the first i and the last n.

You are given a string <var>s</var> of length at least <var>3</var> consisting of lowercase English letters.
Abbreviate <var>s</var> in the same way.

Constraints

<var>3 ≤ |s| ≤ 100</var> (<var>|s|</var> denotes the length of <var>s</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 abbreviation of <var>s</var>.

Sample Input 1

internationalization

Sample Output 1

i18n

Sample Input 2

smiles

Sample Output 2

s4s

Sample Input 3

xyz

Sample Output 3

x1z

int solution(void) {
  char s[101] = {0};
  char n[256] = {0};
  char r[256] = {0};
  int len = 0;
  int sum = 0;

  scanf("%s", s);

  len = strlen(s);

  if (3 <= len && len <= 100) {
    int len_tmp = 0;
    sum = len - 2;
    sprintf(n, "%d", sum);
    r[0] = s[0];
    strncpy(&r[1], &n[0], strlen(n));
    len_tmp = strlen(r);
    r[len_tmp] = s[len - 1];
  }

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

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let len = s.trim().len();
    let ss = s.chars().collect::<Vec<char>>();
    println!("{}{}{}", ss[0], len - 2, ss[len - 1]);
}


Score : <var>700</var> points

Problem Statement

You are given sequences <var>A</var> and <var>B</var> consisting of non-negative integers.
The lengths of both <var>A</var> and <var>B</var> are <var>N</var>, and the sums of the elements in <var>A</var> and <var>B</var> are equal.
The <var>i</var>-th element in <var>A</var> is <var>A_i</var>, and the <var>i</var>-th element in <var>B</var> is <var>B_i</var>.

Tozan and Gezan repeats the following sequence of operations:

If <var>A</var> and <var>B</var> are equal sequences, terminate the process.

Otherwise, first Tozan chooses a positive element in <var>A</var> and decrease it by <var>1</var>.

Then, Gezan chooses a positive element in <var>B</var> and decrease it by <var>1</var>.

Then, give one candy to Takahashi, their pet.

Tozan wants the number of candies given to Takahashi until the process is terminated to be as large as possible, while Gezan wants it to be as small as possible.
Find the number of candies given to Takahashi when both of them perform the operations optimally.

Constraints

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

<var>0 \leq A_i,B_i \leq 10^9(1\leq i\leq N)</var>

The sums of the elements in <var>A</var> and <var>B</var> are equal.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>B_1</var>
<var>:</var>
<var>A_N</var> <var>B_N</var>

Output

Print the number of candies given to Takahashi when both Tozan and Gezan perform the operations optimally.

Sample Input 1

2
1 2
3 2

Sample Output 1

2

When both Tozan and Gezan perform the operations optimally, the process will proceed as follows:

Tozan decreases <var>A_1</var> by <var>1</var>.

Gezan decreases <var>B_1</var> by <var>1</var>.

One candy is given to Takahashi.

Tozan decreases <var>A_2</var> by <var>1</var>.

Gezan decreases <var>B_1</var> by <var>1</var>.

One candy is given to Takahashi.

As <var>A</var> and <var>B</var> are equal, the process is terminated.

Sample Input 2

3
8 3
0 1
4 8

Sample Output 2

9

Sample Input 3

1
1 1

Sample Output 3

0

int solution(void) {
  int N;
  scanf("%d", &N);
  long long int a[N];
  long long int b[N];
  long long int ans = 0;
  long long int min = 1000000007;
  int zero = 1;
  for (int i = 0; i < N; i++) {
    scanf("%lld %lld", &a[i], &b[i]);
    if (a[i] != b[i]) {
      zero = 0;
    }
    ans += b[i];
    if (a[i] > b[i] && b[i] < min) {
      min = b[i];
    }
  }
  if (zero == 1) {
    printf("0");
  } else {
    printf("%lld", ans - min);
  }
  return 0;
}

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

    let s = B.iter().sum::<i64>();
    let m = (0..N)
        .filter(|&i| A[i] > B[i])
        .min_by_key(|&i| B[i])
        .map_or(s, |i| B[i]);
    let ans = s - m;

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


There is a grid with $$$n$$$ rows and $$$m$$$ columns. Some cells are colored black, and the rest of the cells are colored white.In one operation, you can select some black cell and do exactly one of the following:   color all cells in its row black, or  color all cells in its column black. You are given two integers $$$r$$$ and $$$c$$$. Find the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black, or determine that it is impossible.

fn solution() {
    let mut handle = io::BufWriter::new(io::stdout());
    let mut test_no = String::new();
    io::stdin().read_line(&mut test_no).unwrap();
    let test_no = test_no.trim().parse().unwrap();
    let mut loop_count = 0;
    loop {
        loop_count += 1;
        let mut numberstr = String::new();
        io::stdin().read_line(&mut numberstr).unwrap();
        let numbers = numberstr
            .trim()
            .split(' ')
            .collect::<Vec<&str>>()
            .iter()
            .map(|x| x.parse().unwrap())
            .collect::<Vec<u8>>();
        let mut grid: Vec<Vec<char>> = Vec::new();
        let mut loop_countt = 0;
        loop {
            loop_countt += 1;
            let mut string = String::new();
            io::stdin().read_line(&mut string).unwrap();
            let array: Vec<char> = string
                .trim()
                .split(' ')
                .collect::<String>()
                .chars()
                .collect::<Vec<char>>();
            grid.push(array);
            if loop_countt == numbers[0] {
                break;
            }
        }
        if grid[numbers[2] as usize - 1][numbers[3] as usize - 1] == 'B' {
            writeln!(handle, "0").expect("");
        } else if grid[numbers[2] as usize - 1].contains(&'B') {
            writeln!(handle, "1").expect("");
        } else {
            let mut num: i8 = 3;
            for i in &grid {
                if i[numbers[3] as usize - 1] == 'B' {
                    num = 1;
                    break;
                }
            }
            if num != 1 {
                for i in &grid {
                    if i.contains(&'B') {
                        num = 2;
                        break;
                    } else {
                        num = -1;
                    }
                }
            }
            writeln!(handle, "{}", num).expect("");
        }
        if loop_count == test_no {
            break;
        }
    }
}


Score : <var>200</var> points

Problem Statement

An integer <var>N</var> is a multiple of <var>9</var> if and only if the sum of the digits in the decimal representation of <var>N</var> is a multiple of <var>9</var>.

Determine whether <var>N</var> is a multiple of <var>9</var>.

Constraints

<var>0 \leq N < 10^{200000}</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If <var>N</var> is a multiple of <var>9</var>, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is <var>1+2+3+4+5+6+7+8+9=45</var>, which is a multiple of <var>9</var>, so <var>123456789</var> is a multiple of <var>9</var>.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No

int solution() {
  char x[1];
  long long count = 0;
  scanf("%c", &x[0]);
  while (x[0] != 10 && x[0] != ' ') {
    count += x[0] - 48;
    scanf("%c", &x[0]);
  }
  if (count % 9 == 0) {
    printf("Yes\n");
  } else {
    printf("No\n");
  }
  return 0;
}

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

    let r: u32 = buf
        .trim()
        .chars()
        .fold(0, |r, c| (c.to_digit(10).unwrap() + r) % 9);
    println!("{}", if r == 0 { "Yes" } else { "No" })
}


You are given an integer $$$k$$$ and a string $$$s$$$ that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).Each asterisk should be replaced with several (from $$$0$$$ to $$$k$$$ inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.The result of the replacement is called a BA-string.Two strings $$$a$$$ and $$$b$$$ are different if they either have different lengths or there exists such a position $$$i$$$ that $$$a_i \neq b_i$$$.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$$$. Now consider all different BA-strings and find the $$$x$$$-th lexicographically smallest of them.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let k = xs[1];
        let mut x = xs[2] - 1;
        let cs: Vec<char> = lines.next().unwrap().unwrap().chars().collect();
        let mut is_ast = true;
        let mut xs: Vec<usize> = vec![];
        let mut ys: Vec<usize> = vec![];
        let mut v: usize = 0;
        for c in cs {
            if c == '*' {
                if is_ast {
                    v += 1;
                } else {
                    xs.push(v);
                    is_ast = true;
                    v = 1;
                }
            } else {
                if is_ast {
                    ys.push(v);
                    is_ast = false;
                    v = 1;
                } else {
                    v += 1;
                }
            }
        }
        if is_ast {
            ys.push(v);
        } else {
            xs.push(v);
            ys.push(0);
        }
        let mut zs: Vec<usize> = vec![0; ys.len()];
        for i in (0..ys.len()).rev() {
            if ys[i] == 0 {
                zs[i] = 0;
            } else {
                zs[i] = x % (ys[i] * k + 1);
                x /= ys[i] * k + 1;
            }
        }
        for i in 0..zs.len() {
            if i > 0 {
                print!(
                    "{}",
                    std::iter::repeat_n("a", xs[i - 1]).collect::<String>()
                );
            }
            if zs[i] != 0 {
                print!("{}", std::iter::repeat_n("b", zs[i]).collect::<String>());
            }
        }
        println!();
    }
}


Score : <var>400</var> points

Problem Statement

Snuke has <var>N</var> strings. The <var>i</var>-th string is <var>s_i</var>.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

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

<var>2 \leq |s_i| \leq 10</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>s_1</var>
<var>\vdots</var>
<var>s_N</var>

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4

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

  int numBxA = 0;
  int numBeginB = 0;
  int numEndA = 0;
  int numAB = 0;
  char str[11] = {0};
  for (int i = 0; i < numOfStrings; i++) {
    scanf("%s", str);
    int len = strlen(str);

    if (str[0] == 'B' && str[len - 1] == 'A') {
      numBxA++;
    } else if (str[0] == 'B') {
      numBeginB++;
    } else if (str[len - 1] == 'A') {
      numEndA++;
    }

    for (int j = 0; j < len - 1; j++) {
      if (str[j] == 'A' && str[j + 1] == 'B') {
        numAB++;
      }
    }
  }
  if (numBeginB + numEndA != 0) {
    numAB += numBxA + ((numBeginB < numEndA) ? numBeginB : numEndA);
  } else if (numBxA != 0) {
    numAB += numBxA - 1;
  }

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

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let s = (0..n).map(|_| it.next().unwrap()).collect::<Vec<_>>();
    let mut res = 0;
    let mut cnt_a = 0;
    let mut cnt_b = 0;
    let mut check_ab = false;
    for &c in &s {
        res += c.matches("AB").count();
        let start_b = c.starts_with("B");
        let end_a = c.ends_with("A");
        if start_b && end_a {
            if check_ab {
                res += 1;
            } else {
                check_ab = true;
            }
        } else if start_b {
            cnt_b += 1;
        } else if end_a {
            cnt_a += 1;
        }
    }
    if check_ab {
        if cnt_a > 0 {
            res += 1;
            cnt_a -= 1;
        }
        if cnt_b > 0 {
            res += 1;
            cnt_b -= 1;
        }
    }
    res += std::cmp::min(cnt_a, cnt_b);
    println!("{}", res);
}


Score : <var>200</var> points

Problem Statement

You are given a string <var>S</var>. Each character of <var>S</var> is uppercase or lowercase English letter.
Determine if <var>S</var> satisfies all of the following conditions:

The initial character of <var>S</var> is an uppercase A.

There is exactly one occurrence of C between the third character from the beginning and the second to last character (inclusive).

All letters except the A and C mentioned above are lowercase.

Constraints

<var>4 ≤ |S| ≤ 10</var> (<var>|S|</var> is the length of the string <var>S</var>.)

Each character of <var>S</var> is uppercase or lowercase English letter.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> satisfies all of the conditions in the problem statement, print AC; otherwise, print WA.

Sample Input 1

AtCoder

Sample Output 1

AC

The first letter is A, the third letter is C and the remaining letters are all lowercase, so all the conditions are satisfied.

Sample Input 2

ACoder

Sample Output 2

WA

The second letter should not be C.

Sample Input 3

AcycliC

Sample Output 3

WA

The last letter should not be C, either.

Sample Input 4

AtCoCo

Sample Output 4

WA

There should not be two or more occurrences of C.

Sample Input 5

Atcoder

Sample Output 5

WA

The number of C should not be zero, either.

int solution() {
  char s[11];
  scanf("%s", s);
  if (s[0] != 'A') {
    printf("WA");
    return 0;
  }
  int len = strlen(s);

  int count = 0;
  int i = 1;
  while (s[i]) {
    if (i >= 2 && i <= len - 2) {
      if (s[i] == 'C') {
        count++;
      }
      if (s[i] != 'C' && s[i] >= 'A' && s[i] <= 'Z') {
        printf("WA");
        return 0;
      }
    } else if (s[i] >= 'A' && s[i] <= 'Z') {
      printf("WA");
      return 0;
    }
    i++;
  }
  if (count == 1) {
    printf("AC");
  } else {
    printf("WA");
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).ok();
    let input = input.trim();
    let len = input.len();

    let mut input = input.chars();

    let mut i = 0;
    let mut countC = 0;
    let mut countU = 0;
    let mut ans = true;

    loop {
        i += 1;
        let buf = input.next();
        if buf.is_none() {
            break;
        }
        let buf = buf.unwrap();

        if i == 1 && buf != 'A' {
            ans = false;
            break;
        }
        if i >= 3 && i < len && buf == 'C' {
            countC += 1;
        }
        if buf.is_uppercase() {
            countU += 1;
        }
    }
    if ans && countC == 1 && countU == 2 {
        println!("AC");
    } else {
        println!("WA");
    }
}


fn solution(text: &str) -> String {
    let to_enc = text.to_uppercase();
    to_enc
        .chars()
        .map(|c| match c {
            'A'..='M' => ((c as u8) + 13) as char,
            'N'..='Z' => ((c as u8) - 13) as char,
            _ => c,
        })
        .collect()
}


Score : <var>600</var> points

Problem Statement

Given is a positive integer <var>N</var>.

We will choose an integer <var>K</var> between <var>2</var> and <var>N</var> (inclusive), then we will repeat the operation below until <var>N</var> becomes less than <var>K</var>.

Operation: if <var>K</var> divides <var>N</var>, replace <var>N</var> with <var>N/K</var>; otherwise, replace <var>N</var> with <var>N-K</var>.

In how many choices of <var>K</var> will <var>N</var> become <var>1</var> in the end?

Constraints

<var>2 \leq N \leq 10^{12}</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the number of choices of <var>K</var> in which <var>N</var> becomes <var>1</var> in the end.

Sample Input 1

6

Sample Output 1

3

There are three choices of <var>K</var> in which <var>N</var> becomes <var>1</var> in the end: <var>2</var>, <var>5</var>, and <var>6</var>.

In each of these choices, <var>N</var> will change as follows:

When <var>K=2</var>: <var>6 \to 3 \to 1</var>

When <var>K=5</var>: <var>6 \to 1</var>

When <var>K=6</var>: <var>6 \to 1</var>

Sample Input 2

3141

Sample Output 2

13

Sample Input 3

314159265358

Sample Output 3

9

int solution() {
  long n;
  scanf("%ld", &n);
  if (n == 2) {
    printf("1\n");
    return 0;
  }
  long ans = 2;
  for (long i = 2; i * i <= n; i++) {
    if (i * i == n - 1) {
      ans++;
    } else if ((n - 1) % i == 0) {
      ans += 2;
    }
    if (n % i != 0) {
      continue;
    }
    long p = n / i;
    long m = n;
    while (m % i == 0) {
      m /= i;
    }
    if (m % i == 1) {
      ans++;
    }
    m = n;
    while (m % p == 0) {
      m /= p;
    }
    if (m % p == 1 && i != p) {
      ans++;
    }
  }
  printf("%ld\n", ans);
  return 0;
}

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

    let mut ans = 0;

    {
        let mut k = 1;
        while k * k < n {
            if (n - 1).is_multiple_of(k) {
                ans += if k == (n - 1) / k { 1 } else { 2 };
            }
            k += 1;
        }
        ans -= 1;
    }

    {
        let mut k = 2;
        while k * k <= n {
            if n.is_multiple_of(k) {
                let mut x = n;
                while x.is_multiple_of(k) {
                    x /= k;
                }
                if x % k == 1 {
                    ans += 1;
                }
                let l = n / k;
                if k != l {
                    let mut y = n;
                    while y.is_multiple_of(l) {
                        y /= l;
                    }
                    if y % l == 1 {
                        ans += 1;
                    }
                }
            }
            k += 1;
        }
        ans += 1;
    }

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


QQ

Write a program which prints multiplication tables in the following format:

1x1=1
1x2=2
.
.
9x8=72
9x9=81

Input

No input.

Output

1x1=1
1x2=2
.
.
9x8=72
9x9=81

Template for C

#include<stdio.h>

int main(){

    return 0;
}

Template for C++

#include<iostream>
using namespace std;

int main(){

    return 0;
}

Template for Java

class Main{
    public static void main(String[] a){

    }
}

fn solution() {
    let mut i = 1;
    let mut j = 1;
    let _done = false;

    while i != 10 {
        while j != 10 {
            println!("{}x{}={}", i, j, i * j);
            j += 1;
        }
        j = 1;
        i += 1;
    }
}


void solution(int *arr, int size) {
  bool isSorted = false;

  while (!isSorted) {
    isSorted = true;

    for (int i = 0; i <= size - 2; i += 2) {
      if (arr[i] > arr[i + 1]) {
        int temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;

        isSorted = false;
      }
    }

    for (int i = 1; i <= size - 2; i += 2) {
      if (arr[i] > arr[i + 1]) {
        int temp = arr[i];
        arr[i] = arr[i + 1];
        arr[i + 1] = temp;

        isSorted = false;
      }
    }
  }
}

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

    let mut sorted = false;
    while !sorted {
        sorted = true;

        for i in (1..len - 1).step_by(2) {
            if arr[i] > arr[i + 1] {
                arr.swap(i, i + 1);
                sorted = false;
            }
        }

        for i in (0..len - 1).step_by(2) {
            if arr[i] > arr[i + 1] {
                arr.swap(i, i + 1);
                sorted = false;
            }
        }
    }
}


In Aramic language words can only represent objects.Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

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

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

    let mut it = input.split_whitespace();

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

    let f = |s: &str| -> usize {
        let bl = s.as_bytes();
        let mut retval = 0;
        for &b in bl {
            let shift = b - b'a';
            let bit = 1 << shift;
            retval |= bit;
        }
        retval
    };

    use std::collections::HashSet;
    let mut mask = HashSet::new();
    let mut ans = 0;
    for s in it {
        let idx = f(s);
        if mask.insert(idx) {
            ans += 1;
        }
    }

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


There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third — at time $$$2 \cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second — at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.

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

  for (int i = 1; i <= setsData; i++) {
    long long numberOfParticipants;
    long long intervalBetweenStudents;
    long long timeOfOlympiad;
    scanf("%lld %lld %lld", &numberOfParticipants, &intervalBetweenStudents,
          &timeOfOlympiad);

    long long averageParticipants =
        1 + (timeOfOlympiad / intervalBetweenStudents);
    if (averageParticipants > numberOfParticipants) {
      averageParticipants = numberOfParticipants;
    }
    long long durationOfOlympiad =
        timeOfOlympiad + (intervalBetweenStudents * (numberOfParticipants - 1));
    long long averageDiscontent =
        (1 + (durationOfOlympiad - timeOfOlympiad -
              (averageParticipants - 1) * intervalBetweenStudents) /
                 intervalBetweenStudents) *
        (averageParticipants - 1);
    long long additionalDiscontent =
        (1 + (averageParticipants - 2)) * (averageParticipants - 2) / 2;
    long long fullDiscontent = averageDiscontent + additionalDiscontent;

    printf("%lld \n", fullDiscontent);
  }

  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 k = it.next().unwrap();

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

        let q = t / x;

        let full = if q < n { (n - q) * q } else { 0 };

        let m = std::cmp::min(q, n);
        let part = (m * (m - 1)) / 2;

        let ans = full + part;

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


Score : <var>200</var> points

Problem Statement

Akaki, a patissier, can make <var>N</var> kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut <var>1</var>, Doughnut <var>2</var>, <var>...,</var> Doughnut <var>N</var>. In order to make one Doughnut <var>i</var> <var>(1 ≤ i ≤ N)</var>, she needs to consume <var>m_i</var> grams of Moto. She cannot make a non-integer number of doughnuts, such as <var>0.5</var> doughnuts.

Now, she has <var>X</var> grams of Moto. She decides to make as many doughnuts as possible for a party tonight. However, since the tastes of the guests differ, she will obey the following condition:

For each of the <var>N</var> kinds of doughnuts, make at least one doughnut of that kind.

At most how many doughnuts can be made here? She does not necessarily need to consume all of her Moto. Also, under the constraints of this problem, it is always possible to obey the condition.

Constraints

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

<var>1 ≤ m_i ≤ 1000</var>

<var>m_1 + m_2 + ... + m_N ≤ X ≤ 10^5</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>m_1</var>
<var>m_2</var>
<var>:</var>
<var>m_N</var>

Output

Print the maximum number of doughnuts that can be made under the condition.

Sample Input 1

3 1000
120
100
140

Sample Output 1

9

She has <var>1000</var> grams of Moto and can make three kinds of doughnuts. If she makes one doughnut for each of the three kinds, she consumes <var>120 + 100 + 140 = 360</var> grams of Moto. From the <var>640</var> grams of Moto that remains here, she can make additional six Doughnuts <var>2</var>. This is how she can made a total of nine doughnuts, which is the maximum.

Sample Input 2

4 360
90
90
90
90

Sample Output 2

4

Making one doughnut for each of the four kinds consumes all of her Moto.

Sample Input 3

5 3000
150
130
150
130
110

Sample Output 3

26

int solution(void) {

  static int n;
  static int x;
  static int min = 100000;
  scanf("%d%d", &n, &x);

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

    int m[i];
    scanf("%d", &m[i]);

    x -= m[i];

    if (min > m[i]) {
      min = m[i];
    }
  }

  printf("%d\n", n + (x / min));

  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let n = iter.next().unwrap().parse::<usize>().unwrap();
    let x = iter.next().unwrap().parse::<i64>().unwrap();
    let mut t = 0;
    let mut num = 0;
    let mut min = 1001;
    for _ in 0..n {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        let a = buf.trim().parse::<i64>().unwrap();
        t += a;
        num += 1;
        if min > a {
            min = a;
        }
    }
    let x = x - t;
    println!("{}", x / min + num);
}


Score : <var>200</var> points

Problem Statement

Snuke has <var>N</var> sticks.
The length of the <var>i</var>-th stick is <var>l_i</var>.

Snuke is making a snake toy by joining <var>K</var> of the sticks together.

The length of the toy is represented by the sum of the individual sticks that compose it.
Find the maximum possible length of the toy.

Constraints

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

<var>1 \leq l_i \leq 50</var>

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

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var>
<var>l_1</var> <var>l_2</var> <var>l_3</var> <var>...</var> <var>l_{N}</var>

Output

Print the answer.

Sample Input 1

5 3
1 2 3 4 5

Sample Output 1

12

You can make a toy of length <var>12</var> by joining the sticks of lengths <var>3</var>, <var>4</var> and <var>5</var>, which is the maximum possible length.

Sample Input 2

15 14
50 26 27 21 41 7 42 35 7 5 5 36 39 1 45

Sample Output 2

386

fn solution() {
    let mut vec: Vec<usize> = Vec::new();

    let stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let mut it = buf.split_whitespace().map(|n| usize::from_str(n).unwrap());
    let (n, k) = (it.next().unwrap(), it.next().unwrap());

    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let mut it = buf.split_whitespace().map(|n| usize::from_str(n).unwrap());

    for _ in 0..n {
        let n: usize = it.next().unwrap();
        vec.push(n);
    }

    let mut sum: usize = 0;

    for _ in 0..k {
        let mut m = 0;
        for i in 0..n {
            m = if vec[m] < vec[i] { i } else { m }
        }
        sum += vec[m];
        vec[m] = 0
    }
    println!("{}", sum);
}


void solution(int *a, size_t len) {
  int i, j, max, sum;
  unsigned char *beads;

  for (i = 1, max = a[0]; i < len; i++)
    if (a[i] > max)
      max = a[i];

  beads = calloc(1, max * len);

  for (i = 0; i < len; i++)
    for (j = 0; j < a[i]; j++)
      beads[i * max + j] = 1;

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

    for (sum = i = 0; i < len; i++) {
      sum += beads[i * max + j];
      beads[i * max + j] = 0;
    }

    for (i = len - sum; i < len; i++)
      beads[i * max + j] = 1;
  }

  for (i = 0; i < len; i++) {
    for (j = 0; j < max && beads[i * max + j]; j++)
      ;
    a[i] = j;
  }
  free(beads);
}

fn solution(a: &mut [usize]) {
    let mut max = a[0];
    (1..a.len()).for_each(|i| {
        if a[i] > max {
            max = a[i];
        }
    });

    let mut beads = vec![vec![0; max]; a.len()];

    for i in 0..a.len() {
        for j in (0..a[i]).rev() {
            beads[i][j] = 1;
        }
    }

    for j in 0..max {
        let mut sum = 0;
        (0..a.len()).for_each(|i| {
            sum += beads[i][j];
            beads[i][j] = 0;
        });

        for k in ((a.len() - sum)..a.len()).rev() {
            a[k] = j + 1;
        }
    }
}