Score : <var>600</var> points

Problem Statement

Takahashi is playing a board game called Sugoroku.

On the board, there are <var>N + 1</var> squares numbered <var>0</var> to <var>N</var>. Takahashi starts at Square <var>0</var>, and he has to stop exactly at Square <var>N</var> to win the game.

The game uses a roulette with the <var>M</var> numbers from <var>1</var> to <var>M</var>. In each turn, Takahashi spins the roulette. If the number <var>x</var> comes up when he is at Square <var>s</var>, he moves to Square <var>s+x</var>. If this makes him go beyond Square <var>N</var>, he loses the game.

Additionally, some of the squares are Game Over Squares. He also loses the game if he stops at one of those squares. You are given a string <var>S</var> of length <var>N + 1</var>, representing which squares are Game Over Squares. For each <var>i</var> <var>(0 \leq i \leq N)</var>, Square <var>i</var> is a Game Over Square if <var>S[i] = 1</var> and not if <var>S[i] = 0</var>.

Find the sequence of numbers coming up in the roulette in which Takahashi can win the game in the fewest number of turns possible. If there are multiple such sequences, find the lexicographically smallest such sequence. If Takahashi cannot win the game, print <var>-1</var>.

Constraints

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

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

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

<var>S</var> consists of 0 and 1.

<var>S[0] =</var> 0

<var>S[N] =</var> 0

Input

Input is given from Standard Input in the following format:

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

Output

If Takahashi can win the game, print the lexicographically smallest sequence among the shortest sequences of numbers coming up in the roulette in which Takahashi can win the game, with spaces in between.

If Takahashi cannot win the game, print <var>-1</var>.

Sample Input 1

9 3
0001000100

Sample Output 1

1 3 2 3

If the numbers <var>1</var>, <var>3</var>, <var>2</var>, <var>3</var> come up in this order, Takahashi can reach Square <var>9</var> via Square <var>1</var>, <var>4</var>, and <var>6</var>. He cannot reach Square <var>9</var> in three or fewer turns, and this is the lexicographically smallest sequence in which he reaches Square <var>9</var> in four turns.

Sample Input 2

5 4
011110

Sample Output 2

-1

Takahashi cannot reach Square <var>5</var>.

Sample Input 3

6 6
0101010

Sample Output 3

6

int solution() {
  int i;
  int N;
  int M;
  char S[100002];
  scanf("%d %d", &N, &M);
  scanf("%s", S);

  int j;
  int k;
  int dice[100001];
  for (i = N, k = 0; i > 0;) {
    for (j = (i < M) ? i : M; j >= 1; j--) {
      if (S[i - j] == '0') {
        break;
      }
    }
    if (j == 0) {
      break;
    }
    dice[k++] = j;
    i -= j;
  }

  if (i > 0) {
    printf("-1\n");
  } else {
    for (i = k - 1; i >= 1; i--) {
      printf("%d ", dice[i]);
    }
    printf("%d\n", dice[0]);
  }
  fflush(stdout);
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let m: usize = itr.next().unwrap().parse().unwrap();
    let mut s: Vec<char> = itr.next().unwrap().chars().collect();
    s.reverse();

    let mut used = vec![false; n + 1];
    let mut q = std::collections::VecDeque::new();
    let mut ans = Vec::new();
    q.push_back(0);
    while let Some(v) = q.pop_front() {
        for nv in (1..m + 1).rev() {
            if v + nv <= n && s[v + nv] != '1' && !used[v + nv] {
                used[nv + v] = true;
                ans.push(nv);
                q.push_back(nv + v);
                break;
            }
        }
    }
    if used[n] {
        ans.reverse();
        let mut out = Vec::new();
        for i in 0..ans.len() {
            write!(out, "{}", ans[i]).ok();
            if i == ans.len() - 1 {
                writeln!(out).ok();
            } else {
                write!(out, " ").ok();
            }
        }
        stdout().write_all(&out).unwrap();
    } else {
        println!("-1");
    }
}


Score : <var>100</var> points

Problem Statement

Determine if we can choose <var>K</var> different integers between <var>1</var> and <var>N</var> (inclusive) so that no two of them differ by <var>1</var>.

Constraints

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

<var>N</var> and <var>K</var> are integers.

Input

Input is given from Standard Input in the following format:

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

Output

If we can choose <var>K</var> integers as above, print YES; otherwise, print NO.

Sample Input 1

3 2

Sample Output 1

YES

We can choose <var>1</var> and <var>3</var>.

Sample Input 2

5 5

Sample Output 2

NO

Sample Input 3

31 10

Sample Output 3

YES

Sample Input 4

10 90

Sample Output 4

NO

int solution() {
  int n;
  int N = 0;
  int K = 0;
  scanf("%d%d", &N, &K);
  if (N % 2 != 0) {
    n = (N + 1) / 2;
  } else {
    n = N / 2;
  }
  if (n >= K) {
    printf("YES\n");
  } else {
    printf("NO\n");
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let vs: Vec<u32> = s
        .split_whitespace()
        .map(|token| token.parse().ok().unwrap())
        .collect();
    let n = vs[0];
    let k = vs[1];
    if n.div_ceil(2) >= k {
        println!("YES");
    } else {
        println!("NO");
    }
}


Given $$$n$$$, find any array $$$a_1, a_2, \ldots, a_n$$$ of integers such that all of the following conditions hold: $$$1 \le a_i \le 10^9$$$ for every $$$i$$$ from $$$1$$$ to $$$n$$$.$$$a_1 < a_2 < \ldots <a_n$$$For every $$$i$$$ from $$$2$$$ to $$$n$$$, $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$It can be shown that such an array always exists under the constraints of the problem.

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

fn solution() {
    let mut handle = std::io::BufWriter::new(std::io::stdout());
    let mut test_no = String::new();
    std::io::stdin().read_line(&mut test_no).unwrap();
    let test_no: u8 = test_no.trim().parse::<u8>().unwrap();
    for _ in 0..test_no {
        let mut case = String::new();
        std::io::stdin().read_line(&mut case).unwrap();
        let case: u16 = case.trim().parse::<u16>().unwrap();
        for i in 0..case - 1 {
            write!(handle, "{} ", i + 2).ok();
        }
        writeln!(handle, "{}", case + 1).ok();
    }
}


Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better names than his competitors, then he'll be at the top of the search results and will be a millionaire.After doing some research, you find out that search engines only sort their results lexicographically. If your friend could rename his products to lexicographically smaller strings than his competitor's, then he'll be at the top of the rankings!To make your strategy less obvious to his competitors, you decide to swap no more than two letters of the product names.Please help Jeff to find improved names for his products that are lexicographically smaller than his competitor's!Given the string $$$s$$$ representing Jeff's product name and the string $$$c$$$ representing his competitor's product name, find a way to swap at most one pair of characters in $$$s$$$ (that is, find two distinct indices $$$i$$$ and $$$j$$$ and swap $$$s_i$$$ and $$$s_j$$$) such that the resulting new name becomes strictly lexicographically smaller than $$$c$$$, or determine that it is impossible.Note: String $$$a$$$ is strictly lexicographically smaller than string $$$b$$$ if and only if one of the following holds:  $$$a$$$ is a proper prefix of $$$b$$$, that is, $$$a$$$ is a prefix of $$$b$$$ such that $$$a \neq b$$$;  There exists an integer $$$1 \le i \le \min{(|a|, |b|)}$$$ such that $$$a_i < b_i$$$ and $$$a_j = b_j$$$ for $$$1 \le j < i$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    char s[5001];
    scanf("%s", s);
    char c[5001];
    scanf("%s", c);
    int n = strlen(s);
    int m = strlen(c);
    int flag = 1;
    for (int i = 0; i < (n < m ? n : m) && flag; i++) {
      int j;
      if (s[i] < c[i]) {
        flag = 0;
      } else if (s[i] == c[i]) {
        for (j = i + 1; j < n; j++) {
          if (s[j] < s[i]) {
            break;
          }
        }
        if (j < n && s[j] < s[i]) {
          char temp;
          temp = s[j];
          s[j] = s[i];
          s[i] = temp;
          flag = 0;
        }
      } else {
        for (j = n - 1; j > i; j--) {
          if (s[j] < c[i]) {
            break;
          }
        }

        if (j > i && s[j] < c[i]) {
          char temp;
          temp = s[j];
          s[j] = s[i];
          s[i] = temp;
          flag = 0;
        } else {
          for (j = n - 1; j > i; j--) {
            if (s[j] == c[i]) {
              break;
            }
          }
          if (j > i && s[j] == c[i]) {
            char temp;
            temp = s[j];
            s[j] = s[i];
            s[i] = temp;
            flag = 0;
          } else {
            flag = 0;
          }
        }
      }
    }
    flag = 1;
    for (int i = 0; i < (n < m ? n : m) && flag; i++) {
      if (s[i] < c[i]) {
        printf("%s\n", s);
        flag = 0;
      } else if (s[i] > c[i]) {
        puts("---");
        flag = 0;
      }
    }
    if (flag == 1) {
      if (strlen(s) < strlen(c)) {
        printf("%s\n", s);
      } else {
        puts("---");
      }
    }
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut scan = Scanner::new(stdin.lock());
    let tt: usize = scan.token();
    for _ in 0..tt {
        let mut s: String = scan.token();
        let c: String = scan.token();
        let mut ss = s.clone().char_indices().collect::<Vec<_>>();
        ss.sort_by(|a, b| {
            if a.1 < b.1 || (a.1 == b.1 && a.0 < b.0) {
                std::cmp::Ordering::Less
            } else if a.1 == b.1 && a.0 == b.0 {
                std::cmp::Ordering::Equal
            } else {
                std::cmp::Ordering::Greater
            }
        });
        for i in 0..s.len() {
            if s.chars().nth(i).unwrap() > ss[i].1 {
                let mut ans = i;
                let mut j = i + 1;
                while j < ss.len() && ss[j].1 == ss[i].1 {
                    ans = j;
                    j += 1;
                }
                let mut sv = s.chars().collect::<Vec<_>>();
                sv.swap(i, ss[ans].0);
                let ms = sv.iter().collect::<String>();
                s = ms;
                break;
            }
        }
        if s < c {
            println!("{}", s);
        } else {
            println!("---");
        }
    }
}


Score : <var>600</var> points

Problem Statement

We have a rectangular grid of squares with <var>H</var> horizontal rows and <var>W</var> vertical columns. Let <var>(i,j)</var> denote the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left.
On this grid, there is a piece, which is initially placed at square <var>(s_r,s_c)</var>.

Takahashi and Aoki will play a game, where each player has a string of length <var>N</var>.
Takahashi's string is <var>S</var>, and Aoki's string is <var>T</var>. <var>S</var> and <var>T</var> both consist of four kinds of letters: L, R, U and D.

The game consists of <var>N</var> steps. The <var>i</var>-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of <var>S_i</var>, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of <var>T_i</var>, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square <var>(r,c)</var> to square <var>(r,c-1)</var>, <var>(r,c+1)</var>, <var>(r-1,c)</var> and <var>(r+1,c)</var>, respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than <var>N</var> steps are done.

Takahashi wants to remove the piece from the grid in one of the <var>N</var> steps.
Aoki, on the other hand, wants to finish the <var>N</var> steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

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

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

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

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

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

<var>S</var> and <var>T</var> consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>N</var>
<var>s_r</var> <var>s_c</var>
<var>S</var>
<var>T</var>

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at <var>(2,3)</var>.

Aoki moves the piece left. The piece is now at <var>(2,2)</var>.

Takahashi does not move the piece. The piece remains at <var>(2,2)</var>.

Aoki moves the piece up. The piece is now at <var>(1,2)</var>.

Takahashi moves the piece left. The piece is now at <var>(1,1)</var>.

Aoki does not move the piece. The piece remains at <var>(1,1)</var>.

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO

int solution() {
  int h;
  int w;
  int n;
  int sr;
  int sc;
  scanf("%d%d%d%d%d", &h, &w, &n, &sr, &sc);
  char s[n + 1];
  char t[n + 1];
  scanf("%s%s", s, t);
  int i;
  int c_l = sc;
  int c_r = sc;
  int r_u = sr;
  int r_d = sr;
  for (i = 0; i < n; i++) {
    if (s[i] == 'L') {
      c_l--;
      if (c_l < 1) {
        puts("NO");
        return 0;
      }
    } else if (s[i] == 'R') {
      c_r++;
      if (c_r > w) {
        puts("NO");
        return 0;
      }
    } else if (s[i] == 'U') {
      r_u--;
      if (r_u < 1) {
        puts("NO");
        return 0;
      }
    } else if (s[i] == 'D') {
      r_d++;
      if (r_d > h) {
        puts("NO");
        return 0;
      }
    }
    if (t[i] == 'L' && c_r > 1) {
      c_r--;
    } else if (t[i] == 'R' && c_l < w) {
      c_l++;
    } else if (t[i] == 'U' && r_d > 1) {
      r_d--;
    } else if (t[i] == 'D' && r_u < h) {
      r_u++;
    }
  }
  puts("YES");
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let h: usize = itr.next().unwrap().parse().unwrap();
    let w: usize = itr.next().unwrap().parse().unwrap();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let sr: usize = itr.next().unwrap().parse().unwrap();
    let sc: usize = itr.next().unwrap().parse().unwrap();
    let s: Vec<char> = itr.next().unwrap().chars().collect();
    let t: Vec<char> = itr.next().unwrap().chars().collect();

    let mut l = sc;
    let mut r = sc;
    for i in 0..n {
        if s[i] == 'L' {
            l -= 1;
        }
        if s[i] == 'R' {
            r += 1;
        }
        if l == 0 || r == w + 1 {
            println!("NO");
            return;
        }
        if t[i] == 'R' && l < w {
            l += 1;
        }
        if t[i] == 'L' && r > 1 {
            r -= 1;
        }
    }
    let mut u = sr;
    let mut d = sr;

    for i in 0..n {
        if s[i] == 'U' {
            u -= 1;
        }
        if s[i] == 'D' {
            d += 1;
        }
        if u == 0 || d == h + 1 {
            println!("NO");
            return;
        }
        if t[i] == 'D' && u < h {
            u += 1;
        }
        if t[i] == 'U' && d > 1 {
            d -= 1;
        }
    }
    println!("YES");
}


Connected Components

  Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Input

  In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$.

  In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other).

  In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character.

Output

  For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise.

Constraints

$2 \leq n \leq 100,000$

$0 \leq m \leq 100,000$

$1 \leq q \leq 10,000$

Sample Input

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

Sample Output

yes
yes
no

int solution() {
  int i;
  int j;
  int n;
  int m;
  int s;
  int t;
  int t1;
  int t2;
  fscanf(stdin, "%d %d", &n, &m);
  int *gg[n];
  int gid[m];

  for (i = 0; i < n; i++) {
    gg[i] = NULL;
  }
  for (i = 0; i < m; i++) {
    gid[i] = i;
  }

  int maxgrp = 0;

  for (i = 0; i < m; i++) {
    fscanf(stdin, "%d %d", &s, &t);
    if (gg[s] == NULL && gg[t] == NULL) {
      gg[s] = gid + maxgrp;
      gg[t] = gid + maxgrp;
      maxgrp++;
      continue;
    }

    if (gg[s] == NULL) {
      gg[s] = gg[t];
    } else if (gg[t] == NULL) {
      gg[t] = gg[s];
    } else {
      if (*gg[s] < *gg[t]) {
        t1 = *gg[s];
        t2 = *gg[t];
      } else {
        t1 = *gg[t];
        t2 = *gg[s];
      }
      for (j = 0; j < maxgrp; j++) {
        if (gid[j] == t2) {
          gid[j] = t1;
        }
      }
    }
  }

  fscanf(stdin, "%d", &m);
  for (i = 0; i < m; i++) {
    fscanf(stdin, "%d %d", &s, &t);

    if (gg[s] == NULL || gg[t] == NULL || *gg[s] != *gg[t]) {
      puts("no");
    } else {
      puts("yes");
    }
  }
  return 0;
}

fn solution() {
    let mut buf = String::new();
    let _ = std::io::stdin().read_line(&mut buf).ok();
    let mut buf = buf.split_whitespace();
    let n: usize = buf.next().unwrap().parse().unwrap();
    let m: usize = buf.next().unwrap().parse().unwrap();
    let mut g = vec![vec![]; n];
    for _ in 0..m {
        let mut buf = String::new();
        let _ = std::io::stdin().read_line(&mut buf).ok();
        let mut buf = buf.split_whitespace();
        let j: usize = buf.next().unwrap().parse().unwrap();
        let k: usize = buf.next().unwrap().parse().unwrap();
        g[k].push(j);
        g[j].push(k);
    }
    let mut colors = vec![-1; n];
    let mut color = 0;
    for i in 0..n {
        let mut s = Vec::new();
        if colors[i] == -1 {
            s.push(i);
            while let Some(p) = s.pop() {
                colors[p] = color;
                for j in &g[p] {
                    if colors[*j] == -1 {
                        s.push(*j);
                    }
                }
            }
            color += 1;
        }
    }

    let mut buf = String::new();
    let _ = std::io::stdin().read_line(&mut buf).ok();
    let n: usize = buf.trim().parse().unwrap();
    for _ in 0..n {
        let mut buf = String::new();
        let _ = std::io::stdin().read_line(&mut buf).ok();
        let mut buf = buf.split_whitespace();
        let j: usize = buf.next().unwrap().parse().unwrap();
        let k: usize = buf.next().unwrap().parse().unwrap();
        if colors[j] == colors[k] {
            println!("yes");
        } else {
            println!("no");
        }
    }
}


Score: <var>100</var> points

Problem Statement

In this problem, a date is written as Y-M-D. For example, <var>2019</var>-<var>11</var>-<var>30</var> means November <var>30</var>, <var>2019</var>.

Integers <var>M_1, D_1, M_2</var>, and <var>D_2</var> will be given as input.

It is known that the date <var>2019</var>-<var>M_2</var>-<var>D_2</var> follows <var>2019</var>-<var>M_1</var>-<var>D_1</var>.

Determine whether the date <var>2019</var>-<var>M_1</var>-<var>D_1</var> is the last day of a month.

Constraints

Both <var>2019</var>-<var>M_1</var>-<var>D_1</var> and <var>2019</var>-<var>M_2</var>-<var>D_2</var> are valid dates in the Gregorian calendar.

The date <var>2019</var>-<var>M_2</var>-<var>D_2</var> follows <var>2019</var>-<var>M_1</var>-<var>D_1</var>.

Input

Input is given from Standard Input in the following format:

<var>M_1</var> <var>D_1</var>
<var>M_2</var> <var>D_2</var>

Output

If the date <var>2019</var>-<var>M_1</var>-<var>D_1</var> is the last day of a month, print 1; otherwise, print 0.

Sample Input 1

11 16
11 17

Sample Output 1

0

November <var>16</var> is not the last day of a month.

Sample Input 2

11 30
12 1

Sample Output 2

1

November <var>30</var> is the last day of November.

int solution(void) {

  int M1 = 0;
  int M2 = 0;
  int D1 = 0;
  int D2 = 0;

  scanf("%d %d", &M1, &D1);
  scanf("%d %d", &M2, &D2);

  if (M1 != M2 && D2 == 1) {
    printf("1\n");
  } else {
    printf("0\n");
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let a: Vec<u32> = s
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect();

    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let b: Vec<u32> = s
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect();

    println!("{}", if a[1] > b[1] { 1 } else { 0 });
}


Score : <var>200</var> points

Problem Statement

A group of people played a game. All players had distinct scores, which are positive integers.

Takahashi knows <var>N</var> facts on the players' scores. The <var>i</var>-th fact is as follows: the <var>A_i</var>-th highest score among the players is <var>B_i</var>.

Find the maximum possible number of players in the game.

Constraints

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

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

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

If <var>i ≠ j</var>, <var>A_i ≠ A_j</var>.

There exists a possible outcome of the game that are consistent with the facts.

All input values are integers.

Inputs

Input is given from Standard Input in the following format:

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

Outputs

Print the maximum possible number of players in the game.

Sample Input 1

3
4 7
2 9
6 2

Sample Output 1

8

The maximum possible number of players is achieved when, for example, the players have the following scores: <var>12,9,8,7,5,2,1,0</var>.

Sample Input 2

5
1 10
3 6
5 2
4 4
2 8

Sample Output 2

7

Sample Input 3

2
1 1000000000
1000000000 1

Sample Output 3

1000000001

int solution(void) {

  long n;
  scanf("%ld", &n);
  long a[n];
  long b[n];
  for (long i = 0; i < n; i++) {
    scanf("%ld %ld", &a[i], &b[i]);
  }
  long max = 0;
  long n_th;
  for (long i = 0; i < n; i++) {
    if (a[i] > max) {
      max = a[i];
      n_th = i;
    }
  }
  printf("%ld\n", max + b[n_th]);

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let (a, b): (u32, u32) = stdin
        .lock()
        .lines()
        .skip(1)
        .map(|r| {
            r.as_ref()
                .map(|l| {
                    let mut s = l.split_whitespace().map(|s| s.parse().unwrap());
                    (s.next().unwrap(), s.next().unwrap())
                })
                .unwrap()
        })
        .max_by_key(|&(a, _)| a)
        .unwrap();
    println!("{}", a + b);
}


Score : <var>100</var> points

Problem Statement

We have an <var>N \times N</var> square grid.

We will paint each square in the grid either black or white.

If we paint exactly <var>A</var> squares white, how many squares will be painted black?

Constraints

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

<var>0 \leq A \leq N^2</var>

Inputs

Input is given from Standard Input in the following format:

<var>N</var>
<var>A</var>

Outputs

Print the number of squares that will be painted black.

Sample Input 1

3
4

Sample Output 1

5

There are nine squares in a <var>3 \times 3</var> square grid.
Four of them will be painted white, so the remaining five squares will be painted black.

Sample Input 2

19
100

Sample Output 2

261

Sample Input 3

10
0

Sample Output 3

100

As zero squares will be painted white, all the squares will be painted black.

int solution() {

  int N = 0;
  int A = 0;

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

  printf("%d", (N * N) - A);

  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).ok();
    let vec: Vec<&str> = line.split_whitespace().collect();
    let n: i32 = vec[0].parse().unwrap_or(0);

    let mut l = String::new();
    io::stdin().read_line(&mut l).ok();
    let v: Vec<&str> = l.split_whitespace().collect();
    let m: i32 = v[0].parse().unwrap_or(0);

    println!("{}", n * n - m);
}


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Find the maximum value of $$$max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r)$$$ over all pairs $$$(l, r)$$$ of integers for which $$$1 \le l < r \le n$$$.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    long long int a[n];
    for (int i = 0; i < n; i++) {
      scanf("%lld", &a[i]);
    }
    long long int ans = 0;
    ans = a[0] * a[1];
    if (n > 2) {
      for (int i = 1; i < n - 1; i++) {
        if ((a[i] * a[i + 1]) > ans) {
          ans = a[i] * a[i + 1];
        }
      }
    }
    printf("%lld\n", ans);
  }
}

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let m = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<u64>().unwrap())
            .fold((1, 1), |(p, m), n| (n, m.max(p * n)))
            .1;
        writeln!(o, "{}", m).ok();
    }
}


A permutation is a sequence of $$$n$$$ integers from $$$1$$$ to $$$n$$$, in which all numbers occur exactly once. For example, $$$[1]$$$, $$$[3, 5, 2, 1, 4]$$$, $$$[1, 3, 2]$$$ are permutations, and $$$[2, 3, 2]$$$, $$$[4, 3, 1]$$$, $$$[0]$$$ are not.Polycarp was presented with a permutation $$$p$$$ of numbers from $$$1$$$ to $$$n$$$. However, when Polycarp came home, he noticed that in his pocket, the permutation $$$p$$$ had turned into an array $$$q$$$ according to the following rule:   $$$q_i = \max(p_1, p_2, \ldots, p_i)$$$. Now Polycarp wondered what lexicographically minimal and lexicographically maximal permutations could be presented to him.An array $$$a$$$ of length $$$n$$$ is lexicographically smaller than an array $$$b$$$ of length $$$n$$$ if there is an index $$$i$$$ ($$$1 \le i \le n$$$) such that the first $$$i-1$$$ elements of arrays $$$a$$$ and $$$b$$$ are the same, and the $$$i$$$-th element of the array $$$a$$$ is less than the $$$i$$$-th element of the array $$$b$$$. For example, the array $$$a=[1, 3, 2, 3]$$$ is lexicographically smaller than the array $$$b=[1, 3, 4, 2]$$$.For example, if $$$n=7$$$ and $$$p=[3, 2, 4, 1, 7, 5, 6]$$$, then $$$q=[3, 3, 4, 4, 7, 7, 7]$$$ and the following permutations could have been as $$$p$$$ initially:   $$$[3, 1, 4, 2, 7, 5, 6]$$$ (lexicographically minimal permutation);  $$$[3, 1, 4, 2, 7, 6, 5]$$$;  $$$[3, 2, 4, 1, 7, 5, 6]$$$;  $$$[3, 2, 4, 1, 7, 6, 5]$$$ (lexicographically maximum permutation). For a given array $$$q$$$, find the lexicographically minimal and lexicographically maximal permutations that could have been originally presented to Polycarp.

fn solution() {
    let sin = std::io::stdin();
    let mut s = String::new();

    sin.read_line(&mut s).unwrap();
    let mut t = s.trim().parse::<usize>().unwrap();
    while t > 0 {
        t -= 1;
        let mut s = String::new();
        sin.read_line(&mut s).unwrap();
        let n = s.trim().parse::<usize>().unwrap();

        let mut minset = BTreeSet::new();

        for i in 1..n {
            minset.insert(i);
        }

        let mut maxset = minset.clone();

        let mut s = String::new();
        sin.read_line(&mut s).unwrap();
        let v: Vec<usize> = s
            .trim()
            .split(" ")
            .map(|ss| ss.parse::<usize>().unwrap())
            .collect();

        let mut cur = 0;

        let mut mmin = Vec::new();
        let mut mmax = Vec::new();
        for i in v {
            if i != cur {
                mmin.push(i);
                mmax.push(i);
                minset.remove(&i);
                maxset.remove(&i);
                cur = i;
            } else {
                let mn = *minset.range(..cur).next().unwrap();
                mmin.push(mn);
                minset.remove(&mn);
                let mx = *maxset.range(..cur).next_back().unwrap();
                mmax.push(mx);
                maxset.remove(&mx);
            }
        }
        println!(
            "{}",
            mmin.iter()
                .map(|i| format!("{}", i))
                .collect::<Vec<String>>()
                .join(" ")
        );
        println!(
            "{}",
            mmax.iter()
                .map(|i| format!("{}", i))
                .collect::<Vec<String>>()
                .join(" ")
        );
    }
}


Let's define the value of the permutation $$$p$$$ of $$$n$$$ integers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once) as follows:  initially, an integer variable $$$x$$$ is equal to $$$0$$$;  if $$$x < p_1$$$, then add $$$p_1$$$ to $$$x$$$ (set $$$x = x + p_1$$$), otherwise assign $$$0$$$ to $$$x$$$;  if $$$x < p_2$$$, then add $$$p_2$$$ to $$$x$$$ (set $$$x = x + p_2$$$), otherwise assign $$$0$$$ to $$$x$$$;  ...  if $$$x < p_n$$$, then add $$$p_n$$$ to $$$x$$$ (set $$$x = x + p_n$$$), otherwise assign $$$0$$$ to $$$x$$$;  the value of the permutation is $$$x$$$ at the end of this process. For example, for $$$p = [4, 5, 1, 2, 3, 6]$$$, the value of $$$x$$$ changes as follows: $$$0, 4, 9, 0, 2, 5, 11$$$, so the value of the permutation is $$$11$$$.You are given an integer $$$n$$$. Find a permutation $$$p$$$ of size $$$n$$$ with the maximum possible value among all permutations of size $$$n$$$. If there are several such permutations, you can print any of them.

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

    let t: i32 = lines.next().unwrap().unwrap().trim().parse().unwrap();
    for _ in 0..t {
        let n: i32 = lines.next().unwrap().unwrap().trim().parse().unwrap();
        if n % 2 == 0 {
            for i in (3..n - 1).rev() {
                print!("{i} ")
            }
            print!("{} {} {} {}", 2, 1, n - 1, n);
        } else {
            for i in (4..n - 1).rev() {
                print!("{i} ")
            }
            print!("{} {} {} {} {}", 1, 2, 3, n - 1, n);
        }
        println!()
    }
}


Score: <var>500</var> points

Problem Statement

In the Kingdom of AtCoder, only banknotes are used as currency. There are <var>10^{100}+1</var> kinds of banknotes, with the values of <var>1, 10, 10^2, 10^3, \dots, 10^{(10^{100})}</var>. You have come shopping at a mall and are now buying a takoyaki machine with a value of <var>N</var>. (Takoyaki is the name of a Japanese snack.)

To make the payment, you will choose some amount of money which is at least <var>N</var> and give it to the clerk. Then, the clerk gives you back the change, which is the amount of money you give minus <var>N</var>.

What will be the minimum possible number of total banknotes used by you and the clerk, when both choose the combination of banknotes to minimize this count?

Assume that you have sufficient numbers of banknotes, and so does the clerk.

Constraints

<var>N</var> is an integer between <var>1</var> and <var>10^{1,000,000}</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the minimum possible number of total banknotes used by you and the clerk.

Sample Input 1

36

Sample Output 1

8

If you give four banknotes of value <var>10</var> each, and the clerk gives you back four banknotes of value <var>1</var> each, a total of eight banknotes are used.

The payment cannot be made with less than eight banknotes in total, so the answer is <var>8</var>.

Sample Input 2

91

Sample Output 2

3

If you give two banknotes of value <var>100, 1</var>, and the clerk gives you back one banknote of value <var>10</var>, a total of three banknotes are used.

Sample Input 3

314159265358979323846264338327950288419716939937551058209749445923078164062862089986280348253421170

Sample Output 3

243

int solution(void) {

  char s[1000000 + 10];
  scanf("%s", s);
  int length = strlen(s);
  int num;
  long bill_a = 0;
  long bill_b = 1;
  long case1;
  long case2;
  long case3;
  long case4;
  for (int i = 0; i < length; i++) {
    num = s[i] - '0';
    case1 = bill_a + num;
    case2 = bill_b + 10 - num;
    case3 = bill_a + (num + 1);
    case4 = bill_b + 10 - (num + 1);
    bill_a = case1;
    if (case2 < bill_a) {
      bill_a = case2;
    }
    bill_b = case3;
    if (case4 < bill_b) {
      bill_b = case4;
    }
  }
  printf("%ld\n", bill_a);

  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let s: Vec<i64> = s
        .trim()
        .chars()
        .map(|c| c.to_digit(10).unwrap() as i64)
        .collect();
    let mut dp: Vec<i64> = [0, 1].to_vec();
    for &c in s.iter() {
        let tmp1 = std::cmp::min(dp[0] + c, dp[1] + 10 - c);
        let tmp2 = std::cmp::min(dp[0] + c + 1, dp[1] + 10 - (c + 1));
        dp[0] = tmp1;
        dp[1] = tmp2;
    }
    println!("{}", dp[0]);
}


Score: <var>400</var> points

Problem Statement

Amidakuji is a traditional method of lottery in Japan.

To make an amidakuji, we first draw <var>W</var> parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is <var>H+1</var> [cm], and the endpoints of the horizontal lines must be at <var>1, 2, 3, ...,</var> or <var>H</var> [cm] from the top of a vertical line.

A valid amidakuji is an amidakuji that satisfies the following conditions:

No two horizontal lines share an endpoint.

The two endpoints of each horizontal lines must be at the same height.

A horizontal line must connect adjacent vertical lines.

Find the number of the valid amidakuji that satisfy the following condition, modulo <var>1\ 000\ 000\ 007</var>: if we trace the path from the top of the leftmost vertical line to the bottom, always following horizontal lines when we encounter them, we reach the bottom of the <var>K</var>-th vertical line from the left.

For example, in the following amidakuji, we will reach the bottom of the fourth vertical line from the left.

Constraints

<var>H</var> is an integer between <var>1</var> and <var>100</var> (inclusive).

<var>W</var> is an integer between <var>1</var> and <var>8</var> (inclusive).

<var>K</var> is an integer between <var>1</var> and <var>W</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>K</var>

Output

Print the number of the amidakuji that satisfy the condition, modulo <var>1\ 000\ 000\ 007</var>.

Sample Input 1

1 3 2

Sample Output 1

1

Only the following one amidakuji satisfies the condition:

Sample Input 2

1 3 1

Sample Output 2

2

Only the following two amidakuji satisfy the condition:

Sample Input 3

2 3 3

Sample Output 3

1

Only the following one amidakuji satisfies the condition:

Sample Input 4

2 3 1

Sample Output 4

5

Only the following five amidakuji satisfy the condition:

Sample Input 5

7 1 1

Sample Output 5

1

As there is only one vertical line, we cannot draw any horizontal lines. Thus, there is only one amidakuji that satisfies the condition: the amidakuji with no horizontal lines.

Sample Input 6

15 8 5

Sample Output 6

437760187

Be sure to print the answer modulo <var>1\ 000\ 000\ 007</var>.


You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.

int solution() {
  int n;
  int k;
  int t;
  int count = 0;
  scanf("%d", &t);
  while (t--) {
    scanf("%d%d", &n, &k);
    int a[1200] = {0};
    count = n - 1;
    a[k] = 1;
    for (int i = 1; i < k; i++) {
      if (a[k - i] == 0 && k - i != i) {
        a[i] = 1;
        count--;
      }
    }
    printf("%d\n", count);
    for (int i = 1; i <= n; i++) {
      if (a[i] == 0) {
        printf("%d ", i);
      }
    }
    printf("\n");
  }
  return 0;
}

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

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

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

    while let Some(n) = it.next() {
        let k = it.next().unwrap();

        let p = k.div_ceil(2);
        println!("{}", n - p);
        for x in p..=n {
            if x != k {
                print!("{} ", x);
            }
        }
        println!();
    }
}


Let's denote correct match equation (we will denote it as CME) an equation $$$a + b = c$$$ there all integers $$$a$$$, $$$b$$$ and $$$c$$$ are greater than zero.For example, equations $$$2 + 2 = 4$$$ (||+||=||||) and $$$1 + 2 = 3$$$ (|+||=|||) are CME but equations $$$1 + 2 = 4$$$ (|+||=||||), $$$2 + 2 = 3$$$ (||+||=|||), and $$$0 + 1 = 1$$$ (+|=|) are not.Now, you have $$$n$$$ matches. You want to assemble a CME using all your matches. Unfortunately, it is possible that you can't assemble the CME using all matches. But you can buy some extra matches and then assemble CME!For example, if $$$n = 2$$$, you can buy two matches and assemble |+|=||, and if $$$n = 5$$$ you can buy one match and assemble ||+|=|||.   Calculate the minimum number of matches which you have to buy for assembling CME.Note, that you have to answer $$$q$$$ independent queries.

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

    for _ in 0..q {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let n: u32 = input.split_whitespace().next().unwrap().parse().unwrap();
        println!("{}", if n < 4 { 4 - n } else { n % 2 });
    }
}


Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int k;
    char s[100];
    scanf("%d%d %s", &n, &k, s);
    int equal = 1;
    for (int i = 0; i < n; i++) {
      if (s[i] != s[n - 1 - i]) {
        equal = 0;
      }
    }
    if (k == 0) {
      printf("1\n");
      continue;
    }
    if (equal) {
      printf("1\n");
    } else {
      printf("2\n");
    }
  }
  return 0;
}

fn solution() {
    let mut n_cases = String::new();
    io::stdin()
        .read_line(&mut n_cases)
        .expect("Failed to read input");
    let mut n_cases: i8 = n_cases.trim().parse().expect("Invalid input");

    loop {
        if n_cases == 0 {
            break;
        } else {
            n_cases -= 1
        };

        let mut case_input = String::new();
        io::stdin()
            .read_line(&mut case_input)
            .expect("Failed to read input");
        let case_input: Vec<i16> = case_input
            .split_whitespace()
            .map(|x| x.parse().expect("Invalid input"))
            .collect();

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

        match case_input.last().unwrap() == &0
            || input_str == input_str.chars().rev().collect::<String>()
        {
            true => println!("{}", 1),
            false => println!("{}", 2),
        };
    }
}


Score : <var>100</var> points

Problem Statement

A <var>3×3</var> grid with a integer written in each square, is called a magic square if and only if the integers in each row, the integers in each column, and the integers in each diagonal (from the top left corner to the bottom right corner, and from the top right corner to the bottom left corner), all add up to the same sum.

You are given the integers written in the following three squares in a magic square:

The integer <var>A</var> at the upper row and left column

The integer <var>B</var> at the upper row and middle column

The integer <var>C</var> at the middle row and middle column

Determine the integers written in the remaining squares in the magic square.

It can be shown that there exists a unique magic square consistent with the given information.

Constraints

<var>0 \leq A, B, C \leq 100</var>

Input

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

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

Output

Output the integers written in the magic square, in the following format:

<var>X_{1,1}</var> <var>X_{1,2}</var> <var>X_{1,3}</var>
<var>X_{2,1}</var> <var>X_{2,2}</var> <var>X_{2,3}</var>
<var>X_{3,1}</var> <var>X_{3,2}</var> <var>X_{3,3}</var>

where <var>X_{i,j}</var> is the integer written in the square at the <var>i</var>-th row and <var>j</var>-th column.

Sample Input 1

8
3
5

Sample Output 1

8 3 4
1 5 9
6 7 2

Sample Input 2

1
1
1

Sample Output 2

1 1 1
1 1 1
1 1 1

int solution(void) {
  int a = 0;
  int b = 0;
  int c = 0;
  int d = 0;
  int e = 0;
  int f = 0;
  int g = 0;
  int h = 0;
  int M = 0;

  scanf("%d %d %d", &a, &b, &M);

  g = 2 * M - b;
  h = 2 * M - a;
  f = 3 * M - g - h;
  c = 2 * M - f;
  e = 3 * M - c - h;
  d = 2 * M - e;

  printf("%d %d %d\n", a, b, c);
  printf("%d %d %d\n", d, M, e);
  printf("%d %d %d\n", f, g, h);

  return 0;
}

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let a: i32 = s.next().unwrap().parse().unwrap();
    let b: i32 = s.next().unwrap().parse().unwrap();
    let c: i32 = s.next().unwrap().parse().unwrap();
    let s = 3 * c;
    println!("{} {} {}", a, b, -a - b + s);
    println!("{} {} {}", 2 * s - 2 * a - b - 2 * c, c, 2 * a + b + c - s);
    println!("{} {} {}", a + b + 2 * c - s, s - b - c, s - a - c);
}


You have a statistic of price changes for one product represented as an array of $$$n$$$ positive integers $$$p_0, p_1, \dots, p_{n - 1}$$$, where $$$p_0$$$ is the initial price of the product and $$$p_i$$$ is how the price was increased during the $$$i$$$-th month.Using these price changes you are asked to calculate the inflation coefficients for each month as the ratio of current price increase $$$p_i$$$ to the price at the start of this month $$$(p_0 + p_1 + \dots + p_{i - 1})$$$.Your boss said you clearly that the inflation coefficients must not exceed $$$k$$$ %, so you decided to increase some values $$$p_i$$$ in such a way, that all $$$p_i$$$ remain integers and the inflation coefficients for each month don't exceed $$$k$$$ %.You know, that the bigger changes — the more obvious cheating. That's why you need to minimize the total sum of changes.What's the minimum total sum of changes you need to make all inflation coefficients not more than $$$k$$$ %?

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    int k;
    scanf("%d %d", &n, &k);
    long long int p[n + 1];
    long long int arr[n + 1];
    long long int max = 0;
    arr[0] = 0;
    for (int i = 0; i < n; i++) {
      scanf("%lli", &p[i]);
      if (i == 0) {
        arr[i] = p[i];
      } else {
        arr[i] = arr[i - 1] + p[i];
      }
    }

    for (int i = 1; i < n; i++) {
      if ((p[i] * 100) <= arr[i - 1] * k) {
        continue;
      }
      if (((p[i] * 100) - arr[i - 1] * k) > max)
        max = (p[i] * 100) - arr[i - 1] * k;
    }
    long long int ans = ceil((double)max / k);
    printf("%lli\n", ans);
  }
  return 0;
}

fn solution() {
    use std::io::{self, Write};

    let (stdin, stdout) = (io::stdin(), io::stdout());
    let mut sc = cf_scanner::Scanner::new(stdin.lock());
    let mut out = io::BufWriter::new(stdout.lock());

    let tc: usize = sc.next();
    for _ in 0..tc {
        let (n, k): (usize, i64) = (sc.next(), sc.next());
        let p: Vec<i64> = (0..n).map(|_| sc.next()).collect();
        let mut sum: i64 = p[0];
        let mut ans: i64 = 0;
        for i in 1..n {
            let tmp = max(0, (p[i] * 100 - k * sum + k - 1) / k);
            ans += tmp;
            sum += p[i] + tmp;
        }
        writeln!(out, "{}", ans).unwrap();
    }
}


Score : <var>500</var> points

Problem Statement

Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light.

Three mirrors of length <var>N</var> are set so that they form an equilateral triangle.
Let the vertices of the triangle be <var>a, b</var> and <var>c</var>.

Inside the triangle, the rifle is placed at the point <var>p</var> on segment <var>ab</var> such that <var>ap = X</var>.
(The size of the rifle is negligible.)
Now, the rifle is about to fire a ray of Mysterious Light in the direction of <var>bc</var>.

The ray of Mysterious Light will travel in a straight line, and will be reflected by mirrors, in the same ways as "ordinary" light.
There is one major difference, though: it will be also reflected by its own trajectory as if it is a mirror!
When the ray comes back to the rifle, the ray will be absorbed.

The following image shows the ray's trajectory where <var>N = 5</var> and <var>X = 2</var>.

It can be shown that the ray eventually comes back to the rifle and is absorbed, regardless of the values of <var>N</var> and <var>X</var>.
Find the total length of the ray's trajectory.

Constraints

<var>2≦N≦10^{12}</var>

<var>1≦X≦N-1</var>

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

Partial Points

<var>300</var> points will be awarded for passing the test set satisfying <var>N≦1000</var>.

Another <var>200</var> points will be awarded for passing the test set without additional constraints.

Input

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

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

Output

Print the total length of the ray's trajectory.

Sample Input 1

5 2

Sample Output 1

12

Refer to the image in the Problem Statement section.
The total length of the trajectory is <var>2+3+2+2+1+1+1 = 12</var>.

int solution(void) {
  long long N;
  long long X;
  scanf("%lld%lld", &N, &X);
  if (X > N / 2) {
    X = N - X;
  }
  long long sum = 0;
  long long k;
  sum += X + N - X;
  N = N - X;
  while (X != 0) {
    sum += 2 * X * (N / X);
    k = N % X;
    N = X;
    X = k;
  }

  sum -= N;

  printf("%lld", sum);
}

fn solution() {
    let stdin = std::io::stdin();
    let line = stdin.lock().lines().next().unwrap().unwrap();
    let mut split = line.split(' ').map(|x| x.parse::<u64>().unwrap());
    let (n, mut x) = (split.next().unwrap(), split.next().unwrap());

    if x * 2 == n {
        println!("{}", x * 3);
        std::process::exit(0);
    }

    if x > n / 2 {
        x = n - x;
    }
    let mut dist = n;

    let (mut a, mut b) = (n - x, x);
    loop {
        let rem = a % b;
        if rem == 0 {
            dist += (a - rem) * 2 - b;
            break;
        }
        dist += (a - rem) * 2;
        a = b;
        b = rem;
    }
    println!("{}", dist);
}


The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≤ si ≤ c).Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 ≤ c, and 0, otherwise.You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right — (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.A star lies in a rectangle if it lies on its border or lies strictly inside it.

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

    let (n, q, c) = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        let mut input = input
            .split_whitespace()
            .map(|k| k.parse::<usize>().unwrap());
        (
            input.next().unwrap(),
            input.next().unwrap(),
            input.next().unwrap(),
        )
    };

    use std::iter;

    let mut arr: Vec<_> = std::iter::repeat_n(
        std::iter::repeat_n(std::iter::repeat_n(0, 100).collect::<Vec<_>>(), 100)
            .collect::<Vec<_>>(),
        c + 1,
    )
    .collect();

    for _ in 0..n {
        let (x, y, s) = {
            let mut input = String::new();
            stdin().read_line(&mut input).unwrap();
            let mut input = input
                .split_whitespace()
                .map(|k| k.parse::<usize>().unwrap());
            (
                input.next().unwrap(),
                input.next().unwrap(),
                input.next().unwrap(),
            )
        };
        arr[s][x - 1][y - 1] += 1;
    }

    for arr in arr.iter_mut() {
        for i in 1..100 {
            arr[i][0] += arr[i - 1][0];
        }
        for j in 1..100 {
            arr[0][j] += arr[0][j - 1];
        }
        for i in 1..100 {
            for j in 1..100 {
                arr[i][j] += arr[i - 1][j] + arr[i][j - 1] - arr[i - 1][j - 1];
            }
        }
    }

    for _ in 0..q {
        let (t, x1, y1, x2, y2) = {
            let mut input = String::new();
            stdin().read_line(&mut input).unwrap();
            let mut input = input
                .split_whitespace()
                .map(|k| k.parse::<usize>().unwrap());
            (
                input.next().unwrap(),
                input.next().unwrap() - 1,
                input.next().unwrap() - 1,
                input.next().unwrap() - 1,
                input.next().unwrap() - 1,
            )
        };

        let ans: usize = arr
            .iter()
            .enumerate()
            .map(|(i, arr)| {
                (i + t) % (c + 1)
                    * (if x1 > 0 && y1 > 0 {
                        arr[x2][y2] + arr[x1 - 1][y1 - 1] - arr[x1 - 1][y2] - arr[x2][y1 - 1]
                    } else if x1 > 0 && y1 == 0 {
                        arr[x2][y2] - arr[x1 - 1][y2]
                    } else if x1 == 0 && y1 > 0 {
                        arr[x2][y2] - arr[x2][y1 - 1]
                    } else {
                        arr[x2][y2]
                    })
            })
            .sum();
        println!("{}", ans);
    }
}


Ashish has $$$n$$$ elements arranged in a line. These elements are represented by two integers $$$a_i$$$ — the value of the element and $$$b_i$$$ — the type of the element (there are only two possible types: $$$0$$$ and $$$1$$$). He wants to sort the elements in non-decreasing values of $$$a_i$$$.He can perform the following operation any number of times:  Select any two elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $$$a_i$$$ after performing any number of operations.

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int m;
    int oc = 0;
    int zc = 0;
    scanf("%d", &m);
    int arr[m];
    int arr1[m];
    for (int j = 0; j < m; j++) {
      scanf("%d", &arr[j]);
    }
    for (int j = 0; j < m; j++) {
      scanf("%d", &arr1[j]);
      if (arr1[j] == 0) {
        zc++;
      } else {
        oc++;
      }
    }
    int c = 0;
    for (int j = 0; j < m - 1; j++) {
      if (arr[j] <= arr[j + 1]) {
        c++;
      }
    }
    if (c == m - 1) {
      printf("Yes");
    } else {
      if (oc > 0 && zc > 0) {
        printf("Yes");
      } else {
        printf("No");
      }
    }

    if (i < t - 1) {
      printf("\n");
    }
  }
  return (0);
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let ys: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let zeros = ys.iter().filter(|y| **y == 0).count();
        let is_sorted = (0..(n - 1)).all(|i| xs[i] <= xs[i + 1]);
        let ok = (0 < zeros && zeros < n) || is_sorted;
        println!("{}", if ok { "Yes" } else { "No" });
    }
}


Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s.

int solution(void) {
  int n;
  char s[101];

  scanf("%s", s);
  scanf("%d", &n);
  char page[n][101];
  int ans = -1;
  int mini = 0;
  int len = strlen(s);
  for (int i = 0; i < n; i++) {
    scanf("%s", page[i]);

    if (strncmp(s, page[i], len) == 0 && strcmp(page[i], page[mini]) <= 0) {
      mini = i;
      ans = i;
    }
  }

  if (ans == -1) {
    printf("%s", s);
  } else {
    printf("%s", page[ans]);
  }

  return 0;
}

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

    let mut count = String::new();
    io::stdin().read_line(&mut count).unwrap();
    let count: u32 = match count.trim().parse() {
        Ok(num) => num,
        Err(_) => return,
    };

    let mut rows = vec![];

    for _ in 0..count {
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("err");
        let trimmed_input = input.trim();

        if trimmed_input.starts_with(&word) {
            rows.push(String::from(trimmed_input));
        }
    }
    rows.sort();

    if !rows.is_empty() {
        print!("{}\r", rows[0]);
    } else {
        print!("{}\r", word);
    }
}


Score : <var>100</var> points

Problem Statement

You are given an integer <var>K</var>.
Print the string obtained by repeating the string ACL <var>K</var> times and concatenating them.

For example, if <var>K = 3</var>, print ACLACLACL.

Constraints

<var>1 \leq K \leq 5</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print the string obtained by repeating the string ACL <var>K</var> times and concatenating them.

Sample Input 1

3

Sample Output 1

ACLACLACL

int solution() {
  int K = 0;

  scanf("%d", &K);

  for (int i = 0; i < K * 3; i++) {
    switch (i % 3) {
    case 0:
      printf("A");
      break;

    case 1:
      printf("C");
      break;

    case 2:
      printf("L");
      break;

    default:
      break;
    }
  }

  printf("\n");

  return 0;
}

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

    stdin.read_line(&mut buf)?;
    buf.retain(|c| c != '\n');

    let times: usize = buf.parse().unwrap();
    for _ in 0..times {
        print!("ACL");
    }
    println!();
    Ok(())
}


Score : <var>200</var> points

Problem Statement

You are given an <var>H × W</var> grid.

The squares in the grid are described by <var>H</var> strings, <var>S_1,...,S_H</var>.

The <var>j</var>-th character in the string <var>S_i</var> corresponds to the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left <var>(1 \leq i \leq H,1 \leq j \leq W)</var>.

. stands for an empty square, and # stands for a square containing a bomb.

Dolphin is interested in how many bomb squares are horizontally, vertically or diagonally adjacent to each empty square.

(Below, we will simply say "adjacent" for this meaning. For each square, there are at most eight adjacent squares.)

He decides to replace each . in our <var>H</var> strings with a digit that represents the number of bomb squares adjacent to the corresponding empty square.

Print the strings after the process.

Constraints

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

<var>S_i</var> is a string of length <var>W</var> consisting of # and ..

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>S_1</var>
<var>:</var>
<var>S_H</var>

Output

Print the <var>H</var> strings after the process.

The <var>i</var>-th line should contain a string <var>T_i</var> of length <var>W</var>, where the <var>j</var>-th character in <var>T_i</var> corresponds to the square at the <var>i</var>-th row from the top and <var>j</var>-th row from the left in the grid <var>(1 \leq i \leq H, 1 \leq j \leq W)</var>.

Sample Input 1

3 5
.....
.#.#.
.....

Sample Output 1

11211
1#2#1
11211

For example, let us observe the empty square at the first row from the top and first column from the left.

There is one bomb square adjacent to this empty square: the square at the second row and second column.

Thus, the . corresponding to this empty square is replaced with 1.

Sample Input 2

3 5
#####
#####
#####

Sample Output 2

#####
#####
#####

It is possible that there is no empty square.

Sample Input 3

6 6
#####.
#.#.##
####.#
.#..#.
#.##..
#.#...

Sample Output 3

#####3
#8#7##
####5#
4#65#2
#5##21
#4#310

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let v: Vec<usize> = s
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect();
    let mut mat: Vec<String> = Vec::new();
    let mut ans: Vec<Vec<i32>> = Vec::new();
    let mut ans2: Vec<String> = Vec::new();
    let h = v[0];
    let w = v[1];

    mat.push(std::iter::repeat_n(".", w + 2).collect());
    ans.push(vec![0; w + 2]);
    for _i in 0..h {
        let mut t = String::new();
        std::io::stdin().read_line(&mut t).ok();
        let mut pstr = ".".to_string();
        pstr.push_str(t.trim());
        pstr.push('.');

        mat.push(pstr);
        ans.push(vec![0; w + 2]);
    }
    mat.push(std::iter::repeat_n(".", w + 2).collect());
    ans.push(vec![0; w + 2]);

    for i in 1..(h + 1) {
        for j in 1..(w + 1) {
            if mat[i].chars().nth(j).unwrap() == '#' {
                for k in 0..3 {
                    for l in 0..3 {
                        ans[i - 1 + k][j - 1 + l] += 1;
                    }
                }
            }
        }
    }
    for i in 1..(h + 1) {
        let mut u = String::new();
        for j in 1..(w + 1) {
            if mat[i].chars().nth(j).unwrap() == '#' {
                u.push('#');
            } else {
                u.push_str(&ans[i][j].to_string());
            }
        }
        ans2.push(u);
    }

    for i in 0..(h) {
        println!("{}", ans2[i]);
    }
}


You are given two even integers $$$n$$$ and $$$m$$$. Your task is to find any binary matrix $$$a$$$ with $$$n$$$ rows and $$$m$$$ columns where every cell $$$(i,j)$$$ has exactly two neighbours with a different value than $$$a_{i,j}$$$.Two cells in the matrix are considered neighbours if and only if they share a side. More formally, the neighbours of cell $$$(x,y)$$$ are: $$$(x-1,y)$$$, $$$(x,y+1)$$$, $$$(x+1,y)$$$ and $$$(x,y-1)$$$.It can be proven that under the given constraints, an answer always exists.

int solution() {
  int t;
  scanf("%d", &t);
  for (int o = 0; o < t; o++) {
    int n;
    int m;
    scanf("%d%d", &n, &m);
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        int i1 = i / 2;
        int j1 = j / 2;
        int x = (i1 + j1) & 1;
        int y = ((i & 1) + (j & 1));
        int z = y & 1;
        int ans = x ^ z;
        printf("%d ", ans);
      }
      printf("\n");
    }
  }
  return 0;
}

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

    loop {
        if test_cases_remaining == 0 {
            break;
        }

        let mut line = String::new();
        io::stdin().read_line(&mut line).expect("input");
        let nums = line
            .trim()
            .split(' ')
            .flat_map(str::parse::<i32>)
            .collect::<Vec<_>>();
        let (n, m): (i32, i32) = (nums[0], nums[1]);

        let mut _n = 0;
        loop {
            if _n == n {
                break;
            }
            let mut _m = 0;
            loop {
                if _m == m {
                    println!();
                    break;
                }
                print!("{} ", (((_n >> 1) + (_m >> 1)) & 1) ^ ((_n + _m) & 1));
                _m += 1;
            }
            _n += 1;
        }
        test_cases_remaining -= 1;
    }
}


Score : <var>300</var> points

Problem

Takahashi, who is a novice in competitive programming, wants to learn <var>M</var> algorithms.
Initially, his understanding level of each of the <var>M</var> algorithms is <var>0</var>.

Takahashi is visiting a bookstore, where he finds <var>N</var> books on algorithms.
The <var>i</var>-th book (<var>1\leq i\leq N</var>) is sold for <var>C_i</var> yen (the currency of Japan). If he buys and reads it, his understanding level of the <var>j</var>-th algorithm will increase by <var>A_{i,j}</var> for each <var>j</var> (<var>1\leq j\leq M</var>).
There is no other way to increase the understanding levels of the algorithms.

Takahashi's objective is to make his understanding levels of all the <var>M</var> algorithms <var>X</var> or higher. Determine whether this objective is achievable. If it is achievable, find the minimum amount of money needed to achieve it.

Constraints

All values in input are integers.

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

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

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

<var>0\leq A_{i, j} \leq 10^5</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>X</var>
<var>C_1</var> <var>A_{1,1}</var> <var>A_{1,2}</var> <var>\cdots</var> <var>A_{1,M}</var>
<var>C_2</var> <var>A_{2,1}</var> <var>A_{2,2}</var> <var>\cdots</var> <var>A_{2,M}</var>
<var>\vdots</var>
<var>C_N</var> <var>A_{N,1}</var> <var>A_{N,2}</var> <var>\cdots</var> <var>A_{N,M}</var>

Output

If the objective is not achievable, print -1; otherwise, print the minimum amount of money needed to achieve it.

Sample Input 1

3 3 10
60 2 2 4
70 8 7 9
50 2 3 9

Sample Output 1

120

Buying the second and third books makes his understanding levels of all the algorithms <var>10</var> or higher, at the minimum cost possible.

Sample Input 2

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

Sample Output 2

-1

Buying all the books is still not enough to make his understanding levels of all the algorithms <var>10</var> or higher.

Sample Input 3

8 5 22
100 3 7 5 3 1
164 4 5 2 7 8
334 7 2 7 2 9
234 4 7 2 8 2
541 5 4 3 3 6
235 4 8 6 9 7
394 3 6 1 6 2
872 8 4 3 7 2

Sample Output 3

1067

int solution(void) {
  int N;
  int M;
  int X;
  int ans = 1e9;
  scanf("%d %d %d", &N, &M, &X);
  int C[N];
  int A[N][M];
  for (int i = 0; i < N; i++) {
    scanf("%d", &C[i]);
    for (int j = 0; j < M; j++) {
      scanf("%d", &A[i][j]);
    }
  }

  for (int bit = 0; bit < (1 << N); bit++) {
    int money = 0;
    int totalA[M];

    for (int j = 0; j < M; j++) {
      totalA[j] = 0;
    }
    for (int i = 0; i < N; i++) {
      if (bit & (1 << i)) {
        money += C[i];
        for (int j = 0; j < M; j++) {
          totalA[j] += A[i][j];
        }
      }
    }
    int judge = 1;
    for (int j = 0; j < M; j++) {
      if (totalA[j] < X) {
        judge = 0;
        break;
      }
    }
    if (judge == 1 && money < ans) {
      ans = money;
    }
  }
  if (ans == 1e9) {
    puts("-1");
  } else {
    printf("%d\n", ans);
  }
  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let m: usize = itr.next().unwrap().parse().unwrap();
    let x: usize = itr.next().unwrap().parse().unwrap();
    let mut c = vec![0; n];
    let mut a = vec![vec![0; m]; n];
    for i in 0..n {
        c[i] = itr.next().unwrap().parse().unwrap();
        a[i] = (0..m)
            .map(|_| itr.next().unwrap().parse().unwrap())
            .collect();
    }

    const INF: usize = 1 << 30;
    let mut ans = INF;
    for bit in 0..1 << n {
        let mut cnt = 0;
        let mut get = vec![0; m];
        let mut ok = true;
        for i in 0..n {
            if bit >> i & 1 == 1 {
                cnt += c[i];
                for j in 0..m {
                    get[j] += a[i][j];
                }
            }
        }
        for j in 0..m {
            if get[j] < x {
                ok = false;
            }
        }
        if ok {
            ans = min(ans, cnt);
        }
    }
    if ans == INF {
        println!("-1");
    } else {
        println!("{}", ans);
    }
}


You've got a string $$$a_1, a_2, \dots, a_n$$$, consisting of zeros and ones.Let's call a sequence of consecutive elements $$$a_i, a_{i + 1}, \ldots, a_j$$$ ($$$1\leq i\leq j\leq n$$$) a substring of string $$$a$$$. You can apply the following operations any number of times:  Choose some substring of string $$$a$$$ (for example, you can choose entire string) and reverse it, paying $$$x$$$ coins for it (for example, «0101101» $$$\to$$$ «0111001»);  Choose some substring of string $$$a$$$ (for example, you can choose entire string or just one symbol) and replace each symbol to the opposite one (zeros are replaced by ones, and ones — by zeros), paying $$$y$$$ coins for it (for example, «0101101» $$$\to$$$ «0110001»). You can apply these operations in any order. It is allowed to apply the operations multiple times to the same substring.What is the minimum number of coins you need to spend to get a string consisting only of ones?

int solution() {
  long long int n;
  long long int x;
  long long int y;
  long long int i;
  long long int j;
  long long int k = 0;
  scanf("%lld%lld%lld", &n, &x, &y);
  char a[300005];
  long long int b[300005];
  scanf("%s", a);

  for (i = 0; i < n - 1; i++) {
    if (a[i] == a[i + 1]) {
      continue;
    }
    b[k++] = a[i] - '0';
  }
  b[k++] = a[n - 1] - '0';
  long long int count = 0;

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

    if (b[i] == 0) {
      count++;
    }
  }
  if (x >= y) {
    printf("%lld\n", count * y);
  } else {
    if (count > 1) {
      printf("%lld\n", ((count - 1) * x) + y);
    } else {
      if (count == 1) {
        printf("%lld\n", y);
      } else {
        printf("0\n");
      }
    }
  }
  return 0;
}

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

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

    let input_strs = buffer
        .split_whitespace()
        .take(3)
        .map(|x| x.parse::<i64>().unwrap())
        .collect::<Vec<i64>>();

    let _n = *input_strs.get(0).unwrap();
    let x = *input_strs.get(1).unwrap();
    let y = *input_strs.get(2).unwrap();

    let s = buffer.split_whitespace().skip(3).next().unwrap();

    let nums = s.chars().map(|x| if x == '0' { 0 } else { 1 });

    let iter_chunks = nums.scan((false, 0), |s, x| {
        if !s.0 && x == 0 {
            s.0 = true;
            s.1 += 1;
        } else if x == 1 {
            s.0 = false;
        }
        Some(s.1)
    });

    let num_chunks = iter_chunks.max().expect("num_chunks");

    let cost_optimal = if num_chunks == 0 {
        0
    } else {
        (num_chunks - 1) * std::cmp::min(x, y) + y
    };

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


Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!A password is an array $$$a$$$ of $$$n$$$ positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them with their sum. Formally, choose an index $$$i$$$ such that $$$1 \leq i < n$$$ and $$$a_{i} \neq a_{i+1}$$$, delete both $$$a_i$$$ and $$$a_{i+1}$$$ from the array and put $$$a_{i}+a_{i+1}$$$ in their place. For example, for array $$$[7, 4, 3, 7]$$$ you can choose $$$i = 2$$$ and the array will become $$$[7, 4+3, 7] = [7, 7, 7]$$$. Note that in this array you can't apply this operation anymore.Notice that one operation will decrease the size of the password by $$$1$$$. What is the shortest possible length of the password after some number (possibly $$$0$$$) of operations?

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

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

        let a: Vec<i64> = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let iter = buf.split_whitespace();
            iter.map(|x| x.parse().unwrap()).collect()
        };

        if (0..(n - 1)).all(|i| a[i] == a[i + 1]) {
            println!("{}", n);
        } else {
            println!("1");
        }
    }
}


Vasya has got $$$n$$$ books, numbered from $$$1$$$ to $$$n$$$, arranged in a stack. The topmost book has number $$$a_1$$$, the next one — $$$a_2$$$, and so on. The book at the bottom of the stack has number $$$a_n$$$. All numbers are distinct.Vasya wants to move all the books to his backpack in $$$n$$$ steps. During $$$i$$$-th step he wants to move the book number $$$b_i$$$ into his backpack. If the book with number $$$b_i$$$ is in the stack, he takes this book and all the books above the book $$$b_i$$$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $$$[1, 2, 3]$$$ (book $$$1$$$ is the topmost), and Vasya moves the books in the order $$$[2, 1, 3]$$$, then during the first step he will move two books ($$$1$$$ and $$$2$$$), during the second step he will do nothing (since book $$$1$$$ is already in the backpack), and during the third step — one book (the book number $$$3$$$). Note that $$$b_1, b_2, \dots, b_n$$$ are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.

int solution() {
  int books[200001];
  int n = 0;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int book = 0;
    scanf("%d", &book);
    books[book] = i;
  }
  int lastInsert = 0;
  for (int j = 1; j <= n; j++) {
    int order = 0;
    scanf("%d", &order);
    order = books[order];
    if ((order - lastInsert) > 0) {
      printf("%d ", (order - lastInsert));
      lastInsert = order;
    } else {
      printf("0 ");
    }
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).expect("read_line error");
    let _n = match s.split_whitespace().next() {
        Some(s) => match s.parse::<i32>() {
            Ok(n) => n,
            _ => 0,
        },
        _ => 0,
    };
    s.clear();
    std::io::stdin().read_line(&mut s).expect("read_line error");
    let stack = s
        .split_whitespace()
        .map(|s| match s.parse::<i32>() {
            Ok(n) => n,
            _ => 0,
        })
        .collect::<Vec<i32>>();
    s.clear();
    std::io::stdin().read_line(&mut s).expect("read_line error");
    let order = s
        .split_whitespace()
        .map(|s| match s.parse::<i32>() {
            Ok(n) => n,
            _ => 0,
        })
        .collect::<Vec<i32>>();

    let mut answ: Vec<i32> = Vec::new();
    let mut stack_set = HashSet::new();
    let mut seen = HashSet::new();
    let mut idx = 0;

    for x in &stack {
        stack_set.insert(x);
    }

    for x in order {
        if !stack_set.contains(&x) {
            continue;
        }
        if seen.contains(&x) || idx == stack.len() {
            answ.push(0);
        } else {
            let mut cnt = 0;
            while idx < stack.len() {
                cnt += 1;
                if stack[idx] == x {
                    answ.push(cnt);
                    idx += 1;
                    break;
                } else {
                    seen.insert(stack[idx]);
                    idx += 1;
                }
            }
        }
    }

    for x in answ {
        print!("{} ", x);
    }
    println!();
}


Score : <var>300</var> points

Problem Statement

We will play a one-player game using a number line and <var>N</var> pieces.

First, we place each of these pieces at some integer coordinate.

Here, multiple pieces can be placed at the same coordinate.

Our objective is to visit all of the <var>M</var> coordinates <var>X_1, X_2, ..., X_M</var> with these pieces, by repeating the following move:

Move: Choose a piece and let <var>x</var> be its coordinate. Put that piece at coordinate <var>x+1</var> or <var>x-1</var>.

Note that the coordinates where we initially place the pieces are already regarded as visited.

Find the minimum number of moves required to achieve the objective.

Constraints

All values in input are integers.

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

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

<var>-10^5 \leq X_i \leq 10^5</var>

<var>X_1, X_2, ..., X_M</var> are all different.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>X_1</var> <var>X_2</var> <var>...</var> <var>X_M</var>

Output

Find the minimum number of moves required to achieve the objective.

Sample Input 1

2 5
10 12 1 2 14

Sample Output 1

5

The objective can be achieved in five moves as follows, and this is the minimum number of moves required.

Initially, put the two pieces at coordinates <var>1</var> and <var>10</var>.

Move the piece at coordinate <var>1</var> to <var>2</var>.

Move the piece at coordinate <var>10</var> to <var>11</var>.

Move the piece at coordinate <var>11</var> to <var>12</var>.

Move the piece at coordinate <var>12</var> to <var>13</var>.

Move the piece at coordinate <var>13</var> to <var>14</var>.

Sample Input 2

3 7
-10 -3 0 9 -100 2 17

Sample Output 2

19

Sample Input 3

100 1
-100000

Sample Output 3

0

fn solution() {
    let mut stdin = io::stdin();
    let mut buf = String::new();
    let _ = stdin.read_to_string(&mut buf);
    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let m: usize = iter.next().unwrap().parse().unwrap();
    let mut x: Vec<i32> = (0..m)
        .map(|_| iter.next().unwrap().parse().unwrap())
        .collect();

    x.sort();
    let mut d: Vec<i32> = (0..(m - 1)).map(|i| x[i + 1] - x[i]).collect();
    d.sort();
    println!("{}", d.iter().rev().skip(n - 1).sum::<i32>());
}


You and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let _n: i64 = buf.split_whitespace().next().unwrap().parse().unwrap();
    buf.clear();
    stdin().read_line(&mut buf).unwrap();
    let a: Vec<i64> = buf
        .split_whitespace()
        .map(|s| s.parse::<i64>().unwrap())
        .collect();
    let _quit = false;
    let _xl = 1;
    let _xr = 1000_000;
    let mut cl = 2;
    let mut cr = 999_999;
    for p in a {
        if p <= 500_000 {
            cl = p;
        } else {
            cr = p;
            break;
        }
    }

    println!("{}", (cl - 1).max(1000_000 - cr));
}


You are given two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$). Represent the number $$$n$$$ as the sum of $$$k$$$ positive integers of the same parity (have the same remainder when divided by $$$2$$$).In other words, find $$$a_1, a_2, \ldots, a_k$$$ such that all $$$a_i>0$$$, $$$n = a_1 + a_2 + \ldots + a_k$$$ and either all $$$a_i$$$ are even or all $$$a_i$$$ are odd at the same time.If such a representation does not exist, then report it.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let (n, k) = (xs[0], xs[1]);
        if n % 2 == 0 {
            if k % 2 == 0 {
                if n >= k {
                    println!("YES");
                    print!("{}", n - k + 1);
                    for _ in 1..k {
                        print!(" 1");
                    }
                    println!();
                } else {
                    println!("NO");
                }
            } else {
                if n >= k * 2 {
                    println!("YES");
                    print!("{}", n - k * 2 + 2);
                    for _ in 1..k {
                        print!(" 2");
                    }
                    println!();
                } else {
                    println!("NO");
                }
            }
        } else {
            if k % 2 == 0 {
                println!("NO");
            } else {
                if n >= k {
                    println!("YES");
                    print!("{}", n - k + 1);
                    for _ in 1..k {
                        print!(" 1");
                    }
                    println!();
                } else {
                    println!("NO")
                }
            }
        }
    }
}


Reversing Numbers

  Write a program which reads a sequence and prints it in the reverse order.

Input

The input is given in the following format:

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

<var>n</var> is the size of the sequence and <var>ai</var> is the <var>i</var>th element of the sequence.

Output

  Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).

Constraints

<var>n</var> ≤ 100

0 ≤ <var>ai</var> < 1000

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 4 3 2 1

Sample Input 2

8
3 3 4 4 5 8 7 9

Sample Output 2

9 7 8 5 4 4 3 3

Note

      解説

int solution(void) {

  int n = 100;
  scanf("%d", &n);

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

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

    let _ = stdin.read_line(&mut buf);
    buf.clear();

    let _ = stdin.read_line(&mut buf);
    let mut vec: Vec<&str> = buf.split_whitespace().collect();
    vec.reverse();

    println!("{}", vec.join(" "));
}


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

int solution() {
  int count = 2;
  int max = 0;
  int n;
  int flat = 1;
  char goingUp = '1';
  scanf("%d", &n);
  getchar();
  if (n == 1) {
    printf("%d", 1);
  } else if (n == 2) {
    printf("%d", 2);
  } else {
    int t1;
    int t2;
    scanf("%d", &t1);
    scanf("%d", &t2);
    if (t2 < t1) {
      goingUp = '0';
    }
    for (int i = 2; i < n; ++i) {
      t1 = t2;
      scanf("%d", &t2);
      if (goingUp == '1' && t2 >= t1) {
        ++count;
      } else if (goingUp == '1' && t2 < t1) {
        ++count;
        goingUp = '0';
      } else if (goingUp == '0' && t2 < t1) {
        ++count;
        flat = 1;
      } else if (goingUp == '0' && t2 == t1) {
        ++count;
        ++flat;
      } else {
        goingUp = '1';
        if (count > max) {
          max = count;
        }
        count = flat + 1;
        flat = 1;
      }
    }
    if (count > max) {
      max = count;
    }
    printf("%d", max);
  }
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf);
    buf.clear();
    io::stdin().read_line(&mut buf);
    let s: Vec<u32> = buf
        .split_whitespace()
        .map(|x| x.parse::<u32>().unwrap())
        .collect();
    let mut mx = 1;
    for i in 0..s.len() {
        let mut curr = 0;
        let mut mx_height = s[i];
        for j in i..s.len() {
            if s[j] <= mx_height {
                mx_height = s[j];
                curr += 1
            } else {
                break;
            }
        }
        mx_height = s[i];
        for j in (0..i).rev() {
            if s[j] <= mx_height {
                mx_height = s[j];
                curr += 1
            } else {
                break;
            }
        }
        mx = u32::max(mx, curr);
    }
    println!("{}", mx);
}


Polycarp wants to buy exactly $$$n$$$ shovels. The shop sells packages with shovels. The store has $$$k$$$ types of packages: the package of the $$$i$$$-th type consists of exactly $$$i$$$ shovels ($$$1 \le i \le k$$$). The store has an infinite number of packages of each type.Polycarp wants to choose one type of packages and then buy several (one or more) packages of this type. What is the smallest number of packages Polycarp will have to buy to get exactly $$$n$$$ shovels?For example, if $$$n=8$$$ and $$$k=7$$$, then Polycarp will buy $$$2$$$ packages of $$$4$$$ shovels.Help Polycarp find the minimum number of packages that he needs to buy, given that he:   will buy exactly $$$n$$$ shovels in total;  the sizes of all packages he will buy are all the same and the number of shovels in each package is an integer from $$$1$$$ to $$$k$$$, inclusive.

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut out = Vec::new();
    for _ in 0..t {
        let n: u64 = itr.next().unwrap().parse().unwrap();
        let k: u64 = itr.next().unwrap().parse().unwrap();
        let mut ans = 1u64 << 60;
        let mut i = 1;
        while i * i <= n {
            if n.is_multiple_of(i) {
                if i <= k {
                    ans = std::cmp::min(ans, n / i);
                }
                if n / i <= k {
                    ans = std::cmp::min(ans, i);
                }
            }
            i += 1;
        }
        writeln!(out, "{}", ans).ok();
    }
    stdout().write_all(&out).unwrap();
}


We say that a positive integer $$$n$$$ is $$$k$$$-good for some positive integer $$$k$$$ if $$$n$$$ can be expressed as a sum of $$$k$$$ positive integers which give $$$k$$$ distinct remainders when divided by $$$k$$$.Given a positive integer $$$n$$$, find some $$$k \geq 2$$$ so that $$$n$$$ is $$$k$$$-good or tell that such a $$$k$$$ does not exist.

int solution() {

  int t;
  scanf("%d", &t);
  while (t--) {
    long long n;
    int flag = 0;
    scanf("%lld", &n);
    long long p = n;

    while (p % 2 == 0) {
      p = p / 2;
    }

    if (p == 1) {
      printf("-1\n");
    } else if (p <= 2e9 && (p * (p + 1)) / 2 <= n) {
      printf("%lld\n", p);
    } else {
      printf("%lld\n", 2 * (n / p));
    }
  }
}

fn solution() {
    let std_in = stdin();
    let mut input = Scanner::new(std_in.lock());

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

    let tests = input.token();
    for _ in 0..tests {
        let n: i64 = input.token();
        let mut k = -1i128;
        for i in 0..62 {
            if n % (1i64 << i) != 0 {
                k = 1i128 << i;
                break;
            }
        }
        if n as i128 >= (k * (k + 1) / 2) {
            writeln!(output, "{}", k).unwrap();
            continue;
        }
        k = 2 * (n as i128) / k;
        if k == 1 {
            writeln!(output, "-1").unwrap();
            continue;
        } else {
            writeln!(output, "{}", k).unwrap();
        }
    }
}


Score : <var>100</var> points

Problem Statement

You are given strings <var>s</var> and <var>t</var>.
Find one longest string that is a subsequence of both <var>s</var> and <var>t</var>.

Notes

A subsequence of a string <var>x</var> is the string obtained by removing zero or more characters from <var>x</var> and concatenating the remaining characters without changing the order.

Constraints

<var>s</var> and <var>t</var> are strings consisting of lowercase English letters.

<var>1 \leq |s|, |t| \leq 3000</var>

Input

Input is given from Standard Input in the following format:

<var>s</var>
<var>t</var>

Output

Print one longest string that is a subsequence of both <var>s</var> and <var>t</var>.
If there are multiple such strings, any of them will be accepted.

Sample Input 1

axyb
abyxb

Sample Output 1

axb

The answer is axb or ayb; either will be accepted.

Sample Input 2

aa
xayaz

Sample Output 2

aa

Sample Input 3

a
z

Sample Output 3

The answer is  (an empty string).

Sample Input 4

abracadabra
avadakedavra

Sample Output 4

aaadara

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut it = s.split_whitespace();
    let s: Vec<_> = it.next().unwrap().chars().collect();
    let t: Vec<_> = it.next().unwrap().chars().collect();
    let mut dp = vec![vec![0u16; t.len() + 1]; s.len() + 1];
    for i in 0..s.len() {
        for j in 0..t.len() {
            if s[i] == t[j] {
                dp[i + 1][j + 1] = dp[i][j] + 1;
            } else {
                dp[i + 1][j + 1] = std::cmp::max(dp[i][j + 1], dp[i + 1][j]);
            }
        }
    }
    let mut ans = vec![];
    let mut i = s.len();
    let mut j = t.len();
    while i > 0 && j > 0 {
        if dp[i][j] == dp[i - 1][j] {
            i -= 1;
        } else if dp[i][j] == dp[i][j - 1] {
            j -= 1;
        } else {
            ans.push(s[i - 1]);
            i -= 1;
            j -= 1;
        }
    }
    println!("{}", ans.into_iter().rev().collect::<String>());
}


Suppose you have an integer $$$v$$$. In one operation, you can:   either set $$$v = (v + 1) \bmod 32768$$$  or set $$$v = (2 \cdot v) \bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$?

int solution() {

  int broj = 32768;
  int n;
  scanf("%d", &n);
  int a[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    int potezi = 30;
    for (int k = 0; k < 15; k++) {
      for (int l = 0; l < 15; l++) {
        int stepen = pow(2.0, l);
        if ((((a[i] + k) * stepen) % 32768) == 0) {
          if (potezi > k + l) {
            potezi = k + l;
            break;
          }
        }
      }
    }
    printf("%d ", potezi);
  }

  return 0;
}

fn solution() {
    let mut dp = vec![-1; 32768];
    dp[0] = 0;
    let mut q = VecDeque::with_capacity(32768);
    q.push_back(0);
    while !q.is_empty() {
        for _ in 0..q.len() {
            let x = q.pop_front().unwrap();
            let y = (x + 32768 - 1) % 32768;
            if dp[y] == -1 {
                dp[y] = dp[x] + 1;
                q.push_back(y);
            }
            if x & 1 == 0 {
                let mut y = x / 2;
                if dp[y] == -1 {
                    dp[y] = dp[x] + 1;
                    q.push_back(y);
                }
                y += 32768 / 2;
                if dp[y] == -1 {
                    dp[y] = dp[x] + 1;
                    q.push_back(y);
                }
            }
        }
    }
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let _: usize = s.trim().parse().unwrap();
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let nums = s
        .trim()
        .split_ascii_whitespace()
        .map(|x| x.parse().unwrap())
        .collect::<Vec<usize>>();
    for x in nums {
        println!("{}", dp[x]);
    }
}


Score : <var>600</var> points

Problem Statement

Snuke, a water strider, lives in a rectangular pond that can be seen as a grid with <var>H</var> east-west rows and <var>W</var> north-south columns. Let <var>(i,j)</var> be the square at the <var>i</var>-th row from the north and <var>j</var>-th column from the west.

Some of the squares have a lotus leaf on it and cannot be entered.
The square <var>(i,j)</var> has a lotus leaf on it if <var>c_{ij}</var> is @, and it does not if <var>c_{ij}</var> is ..

In one stroke, Snuke can move between <var>1</var> and <var>K</var> squares (inclusive) toward one of the four directions: north, east, south, and west.
The move may not pass through a square with a lotus leaf. Moving to such a square or out of the pond is also forbidden.

Find the minimum number of strokes Snuke takes to travel from the square <var>(x_1,y_1)</var> to <var>(x_2,y_2)</var>.
If the travel from <var>(x_1,y_1)</var> to <var>(x_2,y_2)</var> is impossible, point out that fact.

Constraints

<var>1 \leq H,W,K \leq 10^6</var>

<var>H \times W \leq 10^6</var>

<var>1 \leq x_1,x_2 \leq H</var>

<var>1 \leq y_1,y_2 \leq W</var>

<var>x_1 \neq x_2</var> or <var>y_1 \neq y_2</var>.

<var>c_{i,j}</var> is . or @.

<var>c_{x_1,y_1} =</var> .

<var>c_{x_2,y_2} =</var> .

All numbers in input are integers.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var> <var>K</var>
<var>x_1</var> <var>y_1</var> <var>x_2</var> <var>y_2</var>
<var>c_{1,1}c_{1,2}</var> <var>..</var> <var>c_{1,W}</var>
<var>c_{2,1}c_{2,2}</var> <var>..</var> <var>c_{2,W}</var>
<var>:</var>
<var>c_{H,1}c_{H,2}</var> <var>..</var> <var>c_{H,W}</var>

Output

Print the minimum number of strokes Snuke takes to travel from the square <var>(x_1,y_1)</var> to <var>(x_2,y_2)</var>, or print -1 if the travel is impossible.

Sample Input 1

3 5 2
3 2 3 4
.....
.@..@
..@..

Sample Output 1

5

Initially, Snuke is at the square <var>(3,2)</var>.
He can reach the square <var>(3, 4)</var> by making five strokes as follows:

From <var>(3, 2)</var>, go west one square to <var>(3, 1)</var>.

From <var>(3, 1)</var>, go north two squares to <var>(1, 1)</var>.

From <var>(1, 1)</var>, go east two squares to <var>(1, 3)</var>.

From <var>(1, 3)</var>, go east one square to <var>(1, 4)</var>.

From <var>(1, 4)</var>, go south two squares to <var>(3, 4)</var>.

Sample Input 2

1 6 4
1 1 1 6
......

Sample Output 2

2

Sample Input 3

3 3 1
2 1 2 3
.@.
.@.
.@.

Sample Output 3

-1

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let h: usize = s.next().unwrap().parse().unwrap();
    let w: usize = s.next().unwrap().parse().unwrap();
    let k: i32 = s.next().unwrap().parse().unwrap();
    let sy = s.next().unwrap().parse::<usize>().unwrap() - 1;
    let sx = s.next().unwrap().parse::<usize>().unwrap() - 1;
    let gy = s.next().unwrap().parse::<usize>().unwrap() - 1;
    let gx = s.next().unwrap().parse::<usize>().unwrap() - 1;
    let field: Vec<Vec<_>> = s.take(h).map(|s| s.chars().collect()).collect();

    let mut dist = vec![vec![[std::i32::MAX; 4]; w]; h];
    use std::cmp::Reverse;
    let mut q = std::collections::BinaryHeap::new();
    q.push((Reverse(0), sy, sx, 4));
    while let Some((Reverse(cost), y, x, d)) = q.pop() {
        if d != 4 && cost > dist[y][x][d] {
            continue;
        }
        for &(ny, nx, nd) in [
            (y, x + 1, 0),
            (y.wrapping_sub(1), x, 1),
            (y, x.wrapping_sub(1), 2),
            (y + 1, x, 3),
        ]
        .iter()
        .filter(|&&(ny, nx, _)| (y, x) != (ny, nx) && ny < h && nx < w && field[ny][nx] == '.')
        {
            if d == nd {
                if cost + 1 < dist[ny][nx][nd] {
                    dist[ny][nx][d] = cost + 1;
                    q.push((Reverse(cost + 1), ny, nx, d));
                }
            } else {
                let nc = 1 + (cost + k - 1) / k * k;
                if nc < dist[ny][nx][nd] {
                    dist[ny][nx][nd] = nc;
                    q.push((Reverse(nc), ny, nx, nd));
                }
            }
        }
    }
    let ans = dist[gy][gx]
        .iter()
        .map(|&d| {
            if d == std::i32::MAX {
                std::i32::MAX
            } else {
                (d + k - 1) / k
            }
        })
        .min()
        .unwrap();
    if ans == std::i32::MAX {
        println!("-1");
    } else {
        println!("{}", ans);
    }
}


Score : <var>200</var> points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, <var>N</var> takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the <var>i</var>-th takoyaki is <var>d_i</var>.

As is commonly known, when you eat two takoyaki of deliciousness <var>x</var> and <var>y</var> together, you restore <var>x \times y</var> health points.

There are <var>\frac{N \times (N - 1)}{2}</var> ways to choose two from the <var>N</var> takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these <var>\frac{N \times (N - 1)}{2}</var> values.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>d_1</var> <var>d_2</var> <var>...</var> <var>d_N</var>

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the <var>N</var> takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore <var>3</var> health points.

Eat the second and third takoyaki. You will restore <var>2</var> health points.

Eat the first and third takoyaki. You will restore <var>6</var> health points.

The sum of these values is <var>11</var>.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312

int solution(void) {
  int takoyakis = 0;
  int delicious_points_list[50];
  int sum_heal_points = 0;

  scanf("%d", &takoyakis);

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

  for (int i = 0; i < takoyakis * takoyakis; i++) {
    int base = i / takoyakis;
    int material = i % takoyakis;

    if (material >= base) {
      continue;
    }

    sum_heal_points +=
        delicious_points_list[base] * delicious_points_list[material];
  }

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

  return 0;
}

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

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    let iter = buf.split_whitespace();
    let buf: Vec<&str> = iter.collect();
    let mut d = Vec::new();
    for n in buf {
        d.push(match n.to_string().parse::<i32>() {
            Ok(m) => m,
            _ => panic!(""),
        });
    }
    let mut ret = 0;
    for i in 0..d.len() {
        for j in (i + 1)..d.len() {
            ret += d[i] * d[j];
        }
    }
    println!("{}", ret);
}