通学経路

問題

太郎君の住んでいるJOI市は，南北方向にまっすぐに伸びる a 本の道路と，東西方向にまっすぐに伸びる b 本の道路により，碁盤の目の形に区分けされている．

南北方向の a 本の道路には，西から順に 1, 2, ... , a の番号が付けられている．また，東西方向の b 本の道路には，南から順に 1, 2, ... , b の番号が付けられている．西から i 番目の南北方向の道路と，南から j 番目の東西方向の道路が交わる交差点を (i, j) で表す．

太郎君は，交差点 (1, 1) の近くに住んでおり，交差点 (a, b) の近くのJOI高校に自転車で通っている．自転車は道路に沿ってのみ移動することができる．太郎君は，通学時間を短くするため，東または北にのみ向かって移動して通学している．

現在， JOI市では， n 個の交差点 (x1, y1), (x2, y2), ... , (xn, yn) で工事を行っている．太郎君は工事中の交差点を通ることができない．

太郎君が交差点 (1, 1) から交差点 (a, b) まで，工事中の交差点を避けながら，東または北にのみ向かって移動して通学する方法は何通りあるだろうか．太郎君の通学経路の個数 m を求めるプログラムを作成せよ．

入力

入力は複数のデータセットからなる．各データセットは以下の形式で与えられる．入力はゼロを２つ含む行で終了する．

1行目には，空白を区切りとして2個の整数 a, b が書かれている．これは，南北方向の道路の本数と，東西方向の道路の本数を表す． a, b は 1 ≤ a, b ≤ 16 をみたす．

2行目には, 工事中の交差点の個数を表す整数 n が書かれている． n は 1 ≤ n ≤ 40 をみたす．

続く n 行 (3行目から n+2 行目) には，工事中の交差点の位置が書かれている． i+2 行目には空白で区切られた整数 xi, yi が書かれており，交差点 (xi, yi) が工事中であることを表す． xi, yi は 1 ≤ xi, yi ≤ 16 をみたす．

データセットの数は 5 を超えない．

出力

データセットごとに, 太郎君の通学経路の個数 m を1行に出力する．

入出力例

入力例

5 4
3
2 2
2 3
4 2
5 4
3
2 2
2 3
4 2
0 0

出力例

5
5

下図は a=5, b=4, n=3 で，工事中の交差点が (2,2), (2,3), (4,2) の場合を表している．

この場合，通学経路は m=5 通りある． 5通りの通学経路を全て図示すると，以下の通り．

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

fn solution() {
    let mut stdin = io::stdin();
    let mut buf = String::new();
    stdin.read_to_string(&mut buf);
    let mut iter = buf.split_whitespace();

    loop {
        let a: usize = iter.next().unwrap().parse().unwrap();
        let b: usize = iter.next().unwrap().parse().unwrap();
        if (a, b) == (0, 0) {
            break;
        }
        let n: usize = iter.next().unwrap().parse().unwrap();
        let c: Vec<(usize, usize)> = (0..n)
            .map(|_| {
                (
                    iter.next().unwrap().parse().unwrap(),
                    iter.next().unwrap().parse().unwrap(),
                )
            })
            .collect();

        let mut path: Vec<Vec<u64>> =
            std::iter::repeat_n(std::iter::repeat_n(0, b + 1).collect(), a + 1).collect();
        path[1][1] = 1;

        for d in 3..(a + b + 1) {
            for x in 1..min(d, a + 1) {
                let y = d - x;
                if y > b || c.contains(&(x, y)) {
                    continue;
                }
                path[x][y] = path[x - 1][y] + path[x][y - 1];
            }
        }

        println!("{}", path[a][b]);
    }
}


Score : <var>300</var> points

Problem Statement

You are taking a computer-based examination. The examination consists of <var>N</var> questions, and the score allocated to the <var>i</var>-th question is <var>s_i</var>. Your answer to each question will be judged as either "correct" or "incorrect", and your grade will be the sum of the points allocated to questions that are answered correctly. When you finish answering the questions, your answers will be immediately judged and your grade will be displayed... if everything goes well.

However, the examination system is actually flawed, and if your grade is a multiple of <var>10</var>, the system displays <var>0</var> as your grade. Otherwise, your grade is displayed correctly. In this situation, what is the maximum value that can be displayed as your grade?

Constraints

All input values are integers.

<var>1 ≤ N ≤ 100</var>

<var>1 ≤ s_i ≤ 100</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>s_1</var>
<var>s_2</var>
<var>:</var>
<var>s_N</var>

Output

Print the maximum value that can be displayed as your grade.

Sample Input 1

3
5
10
15

Sample Output 1

25

Your grade will be <var>25</var> if the <var>10</var>-point and <var>15</var>-point questions are answered correctly and the <var>5</var>-point question is not, and this grade will be displayed correctly. Your grade will become <var>30</var> if the <var>5</var>-point question is also answered correctly, but this grade will be incorrectly displayed as <var>0</var>.

Sample Input 2

3
10
10
15

Sample Output 2

35

Your grade will be <var>35</var> if all the questions are answered correctly, and this grade will be displayed correctly.

Sample Input 3

3
10
20
30

Sample Output 3

0

Regardless of whether each question is answered correctly or not, your grade will be a multiple of <var>10</var> and displayed as <var>0</var>.

fn solution() {
    let N: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let s: Vec<usize> = (0..N)
        .map(|_| {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        })
        .collect();

    const M: usize = 10000;
    let mut dp = vec![false; M + 1];
    dp[0] = true;
    for i in 0..N {
        for j in (s[i]..(M + 1)).rev() {
            if dp[j - s[i]] {
                dp[j] = true;
            }
        }
    }
    let ans = (0..(M + 1))
        .rev()
        .find(|&i| dp[i] && i % 10 != 0)
        .unwrap_or(0);

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


Score : <var>200</var> points

Problem Statement

Takahashi lives in another world. There are slimes (creatures) of <var>10000</var> colors in this world. Let us call these colors Color <var>1, 2, ..., 10000</var>.

Takahashi has <var>N</var> slimes, and they are standing in a row from left to right. The color of the <var>i</var>-th slime from the left is <var>a_i</var>.
If two slimes of the same color are adjacent, they will start to combine themselves. Because Takahashi likes smaller slimes, he has decided to change the colors of some of the slimes with his magic.

Takahashi can change the color of one slime to any of the <var>10000</var> colors by one spell.
How many spells are required so that no slimes will start to combine themselves?

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum number of spells required.

Sample Input 1

5
1 1 2 2 2

Sample Output 1

2

For example, if we change the color of the second slime from the left to <var>4</var>, and the color of the fourth slime to <var>5</var>, the colors of the slimes will be <var>1, 4, 2, 5, 2</var>, which satisfy the condition.

Sample Input 2

3
1 2 1

Sample Output 2

0

Although the colors of the first and third slimes are the same, they are not adjacent, so no spell is required.

Sample Input 3

5
1 1 1 1 1

Sample Output 3

2

For example, if we change the colors of the second and fourth slimes from the left to <var>2</var>, the colors of the slimes will be <var>1, 2, 1, 2, 1</var>, which satisfy the condition.

Sample Input 4

14
1 2 2 3 3 3 4 4 4 4 1 2 3 4

Sample Output 4

4

int solution() {

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

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut buf_it = buf.split_whitespace();
    let N = buf_it.next().unwrap().parse::<usize>().unwrap();
    let mut A = (0..N)
        .map(|_| buf_it.next().unwrap().parse::<isize>().unwrap())
        .collect::<Vec<_>>();
    let mut ans = 0;
    for i in 1..N {
        if A[i - 1] == A[i] {
            ans += 1;
            A[i] = 0;
        }
    }

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


Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    scanf("%d", &n);
    int a[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    int flag = 0;
    for (int i = 0; i < n; i++) {
      int temp = sqrt(a[i]);
      if (a[i] != temp * temp) {
        printf("Yes\n");
        flag = 1;
        break;
      }
    }
    if (flag == 0) {
      printf("NO\n");
    }
  }

  return 0;
}

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

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

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

    let mut output = String::new();

    for _ in 0..t {
        let n = it.next().unwrap();
        let mut ans = false;
        for ai in (&mut it).take(n) {
            if (0..=101).all(|i| i * i != ai) {
                ans = true;
            }
        }

        output.push_str(if ans { "YES\n" } else { "NO\n" });
    }

    print!("{}", output);
}


Score : <var>100</var> points

Problem Statement

Takahashi is a user of a site that hosts programming contests.

When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:

Let the current rating of the user be <var>a</var>.

Suppose that the performance of the user in the contest is <var>b</var>.

Then, the new rating of the user will be the avarage of <var>a</var> and <var>b</var>.

For example, if a user with rating <var>1</var> competes in a contest and gives performance <var>1000</var>, his/her new rating will be <var>500.5</var>, the average of <var>1</var> and <var>1000</var>.

Takahashi's current rating is <var>R</var>, and he wants his rating to be exactly <var>G</var> after the next contest.

Find the performance required to achieve it.

Constraints

<var>0 \leq R, G \leq 4500</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>R</var>
<var>G</var>

Output

Print the performance required to achieve the objective.

Sample Input 1

2002
2017

Sample Output 1

2032

Takahashi's current rating is <var>2002</var>.

If his performance in the contest is <var>2032</var>, his rating will be the average of <var>2002</var> and <var>2032</var>, which is equal to the desired rating, <var>2017</var>.

Sample Input 2

4500
0

Sample Output 2

-4500

Although the current and desired ratings are between <var>0</var> and <var>4500</var>, the performance of a user can be below <var>0</var>.

int solution() {
  int R = 0;
  int G = 0;
  int ans = 0;
  scanf("%d\n%d", &R, &G);
  ans = (2 * G) - R;
  printf("%d", ans);

  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let a: i32 = s.trim().parse().ok().unwrap();
    let mut t = String::new();
    std::io::stdin().read_line(&mut t).ok();
    let b: i32 = t.trim().parse().ok().unwrap();
    println!("{}", (2 * b - a));
}


You are given an array of $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$You can apply the following operation an arbitrary number of times:   select an index $$$i$$$ ($$$1 \le i \le n$$$) and replace the value of the element $$$a_i$$$ with the value $$$a_i + (a_i \bmod 10)$$$, where $$$a_i \bmod 10$$$ is the remainder of the integer dividing $$$a_i$$$ by $$$10$$$. For a single index (value $$$i$$$), this operation can be applied multiple times. If the operation is applied repeatedly to the same index, then the current value of $$$a_i$$$ is taken into account each time. For example, if $$$a_i=47$$$ then after the first operation we get $$$a_i=47+7=54$$$, and after the second operation we get $$$a_i=54+4=58$$$.Check if it is possible to make all array elements equal by applying multiple (possibly zero) operations.For example, you have an array $$$[6, 11]$$$.   Let's apply this operation to the first element of the array. Let's replace $$$a_1 = 6$$$ with $$$a_1 + (a_1 \bmod 10) = 6 + (6 \bmod 10) = 6 + 6 = 12$$$. We get the array $$$[12, 11]$$$.  Then apply this operation to the second element of the array. Let's replace $$$a_2 = 11$$$ with $$$a_2 + (a_2 \bmod 10) = 11 + (11 \bmod 10) = 11 + 1 = 12$$$. We get the array $$$[12, 12]$$$. Thus, by applying $$$2$$$ operations, you can make all elements of an array equal.

fn solution() {
    let mut tln = String::new();
    std::io::stdin().read_line(&mut tln).unwrap();
    let tcn = tln.trim_end().parse::<i32>().unwrap();

    for _k in 0..tcn {
        let mut sln = String::new();
        std::io::stdin().read_line(&mut sln).unwrap();

        let _n = sln.trim_end().parse::<i32>().unwrap();

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

        let mut groups = vec![0, 0, 0];
        let mut zero_idx = -1;
        let mut unique_zero = true;
        thln.trim_end()
            .split_ascii_whitespace()
            .map(|s| {
                let cur = s.parse::<i32>().unwrap();
                (cur / 10, cur % 10)
            })
            .for_each(|i| match i {
                (idx, 0 | 5) => {
                    groups[0] = 1;
                    let z_i = idx + if i.1 == 0 { 0 } else { 1 };
                    if zero_idx != -1 && zero_idx != z_i {
                        unique_zero = false;
                    }

                    zero_idx = z_i;
                }
                (idx, rem) => {
                    let idx =
                        (idx + (match rem {
                            3 | 6 | 7 | 9 => 1,
                            _ => 0,
                        })) % 2;
                    if idx == 0 {
                        groups[1] = 1;
                    } else {
                        groups[2] = 1;
                    }
                }
            });

        println!(
            "{}",
            if groups.into_iter().sum::<i32>() == 1 && unique_zero {
                "Yes"
            } else {
                "No"
            }
        );
    }
}


Vasya is preparing a contest, and now he has written a statement for an easy problem. The statement is a string of length $$$n$$$ consisting of lowercase Latin latters. Vasya thinks that the statement can be considered hard if it contains a subsequence hard; otherwise the statement is easy. For example, hard, hzazrzd, haaaaard can be considered hard statements, while har, hart and drah are easy statements. Vasya doesn't want the statement to be hard. He may remove some characters from the statement in order to make it easy. But, of course, some parts of the statement can be crucial to understanding. Initially the ambiguity of the statement is $$$0$$$, and removing $$$i$$$-th character increases the ambiguity by $$$a_i$$$ (the index of each character is considered as it was in the original statement, so, for example, if you delete character r from hard, and then character d, the index of d is still $$$4$$$ even though you delete it from the string had).Vasya wants to calculate the minimum ambiguity of the statement, if he removes some characters (possibly zero) so that the statement is easy. Help him to do it!Recall that subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

int solution() {
  int n;
  int i;
  scanf("%d%*c", &n);
  long long int minimum_values[n][4];
  int values[n];
  char str[n];
  for (i = 0; i < n; i++) {
    scanf("%c", &str[i]);
    minimum_values[i][0] = minimum_values[i][1] = minimum_values[i][2] =
        minimum_values[i][3] = 0;
  }
  for (i = 0; i < n; i++) {
    scanf("%d", &values[i]);
  }
  if (str[n - 1] == 'd') {
    minimum_values[n - 1][3] = values[n - 1];
  }
  for (i = n - 2; i >= 0; i--) {
    if (str[i] == 'd') {
      minimum_values[i][3] = minimum_values[i + 1][3] + values[i];
    } else {
      minimum_values[i][3] = minimum_values[i + 1][3];
    }
    if (str[i] == 'r') {
      if (minimum_values[i + 1][2] + values[i] < minimum_values[i][3]) {
        minimum_values[i][2] = minimum_values[i + 1][2] + values[i];
      } else {
        minimum_values[i][2] = minimum_values[i][3];
      }
    } else {
      minimum_values[i][2] = minimum_values[i + 1][2];
    }
    if (str[i] == 'a') {
      if (minimum_values[i + 1][1] + values[i] < minimum_values[i][2]) {
        minimum_values[i][1] = minimum_values[i + 1][1] + values[i];
      } else {
        minimum_values[i][1] = minimum_values[i][2];
      }
    } else {
      minimum_values[i][1] = minimum_values[i + 1][1];
    }
    if (str[i] == 'h') {
      if (minimum_values[i + 1][0] + values[i] < minimum_values[i][1]) {
        minimum_values[i][0] = minimum_values[i + 1][0] + values[i];
      } else {
        minimum_values[i][0] = minimum_values[i][1];
      }
    } else {
      minimum_values[i][0] = minimum_values[i + 1][0];
    }
  }
  printf("%d", minimum_values[0][0]);
  return 0;
}

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

    s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let chars: Vec<char> = s.trim().chars().collect();

    s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let a: Vec<u64> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();

    #[derive(Clone)]
    struct Prefix {
        empty: u64,
        h: u64,
        ha: u64,
        har: u64,
    }

    let mut mem: Vec<Prefix> = vec![
        Prefix {
            empty: 0,
            h: 0,
            ha: 0,
            har: 0
        };
        n + 1
    ];

    for i in 0..n {
        mem[i + 1] = match chars[i] {
            'h' => Prefix {
                empty: mem[i].empty + a[i],
                h: min(mem[i].empty, mem[i].h),
                ha: mem[i].ha,
                har: mem[i].har,
            },

            'a' => Prefix {
                empty: mem[i].empty,
                h: mem[i].h + a[i],
                ha: min(mem[i].ha, mem[i].h),
                har: mem[i].har,
            },

            'r' => Prefix {
                empty: mem[i].empty,
                h: mem[i].h,
                ha: mem[i].ha + a[i],
                har: min(mem[i].har, mem[i].ha),
            },

            'd' => Prefix {
                empty: mem[i].empty,
                h: mem[i].h,
                ha: mem[i].ha,
                har: mem[i].har + a[i],
            },

            _ => mem[i].clone(),
        }
    }

    let p = &mem[n];
    println!("{}", min(p.empty, min(p.h, min(p.ha, p.har))));
}


Nauuo is a girl who loves playing cards.One day she was playing cards but found that the cards were mixed with some empty ones.There are $$$n$$$ cards numbered from $$$1$$$ to $$$n$$$, and they were mixed with another $$$n$$$ empty cards. She piled up the $$$2n$$$ cards and drew $$$n$$$ of them. The $$$n$$$ cards in Nauuo's hands are given. The remaining $$$n$$$ cards in the pile are also given in the order from top to bottom.In one operation she can choose a card in her hands and play it — put it at the bottom of the pile, then draw the top card from the pile.Nauuo wants to make the $$$n$$$ numbered cards piled up in increasing order (the $$$i$$$-th card in the pile from top to bottom is the card $$$i$$$) as quickly as possible. Can you tell her the minimum number of operations?

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

    let n = get!(usize);
    let mut zeros = 0;
    for _ in 0..n {
        let h = get!();
        if h == 0 {
            zeros += 1;
        }
    }
    if zeros == 0 {
        println!("{}", n);
        return;
    }
    let mut vs = vec![0; n + 1];
    let mut ps = vec![0; n + 1];
    for i in 0..n {
        let p = get!(usize);
        ps[i + 1] = p;
        vs[p] = i as i64 + 2;
    }
    if n == 1 {
        if ps[1] == 1 {
            println!("0");
        } else {
            println!("1");
        }
        return;
    }
    let mut x = 1;
    for i in 0..n {
        let i = n - i;
        if ps[i] == 1 {
            x = i;
            break;
        } else if ps[i] == 0 {
            x = 0;
            break;
        } else if i < n && ps[i] + 1 != ps[i + 1] {
            x = 0;
            break;
        }
    }
    if zeros == n && x == 1 {
        println!("0");
        return;
    }
    if zeros < n && x > 0 {
        let mut c = 1;
        for i in ps[n] + 1..n {
            if vs[i] > c {
                x = 0;
                break;
            }
            c += 1;
        }
    }
    let mut min = 0;
    if zeros < n && x > 0 {
        min = -((n - x + 1) as i64);
        for i in x..n + 1 {
            vs[ps[i]] = -((n - i + 1) as i64);
        }
    }
    let mut ans = vs[n];
    for i in 1..n + 1 {
        let mut v = vs[i];
        if v == 0 {
            v = min;
        }
        ans = std::cmp::max(ans, min + i as i64);
        ans = std::cmp::max(ans, v + (n - i) as i64);
    }

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


Polycarp has $$$26$$$ tasks. Each task is designated by a capital letter of the Latin alphabet.The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot return to the previous task.Polycarp can only solve one task during the day. Every day he wrote down what task he solved. Now the teacher wants to know if Polycarp followed his advice.For example, if Polycarp solved tasks in the following order: "DDBBCCCBBEZ", then the teacher will see that on the third day Polycarp began to solve the task 'B', then on the fifth day he got distracted and began to solve the task 'C', on the eighth day Polycarp returned to the task 'B'. Other examples of when the teacher is suspicious: "BAB", "AABBCCDDEEBZZ" and "AAAAZAAAAA".If Polycarp solved the tasks as follows: "FFGZZZY", then the teacher cannot have any suspicions. Please note that Polycarp is not obligated to solve all tasks. Other examples of when the teacher doesn't have any suspicious: "BA", "AFFFCC" and "YYYYY".Help Polycarp find out if his teacher might be suspicious.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    scanf("%d", &n);
    char string[n + 1];
    scanf("%s", string);
    int flag1 = 0;
    {
      for (char c = 'A'; c <= 'Z' && flag1 == 0; c++) {
        int count = 0;
        for (int i = 0; i < n; i++) {
          if (string[i] == c) {
            count++;
          }
        }

        int l[count];
        int j = 0;
        if (count > 1) {
          for (int i = 0; i < n; i++) {
            if (string[i] == c) {
              l[j] = i;
              j++;
            }
          }

          {
            for (int i = 0; i < count - 1 && flag1 == 0; i++) {
              if (l[i + 1] - l[i] > 1 && l[i + 1] - l[i] != 1) {
                printf("No\n");
                flag1 = 1;
              }
            }
          }
        }
      }
    }
    if (flag1 == 0) {
      printf("Yes\n");
    }
  }
  return 0;
}

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

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

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

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

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

        let mut a = [false; 26];
        let mut it = s.bytes();
        let mut x = it.next().unwrap();
        loop {
            let next = it.next();
            match next {
                Some(y) if y == x => {}
                y => {
                    let i = (x - b'A') as usize;
                    if a[i] {
                        writeln!(&mut output, "NO").unwrap();
                        continue 'cases;
                    } else {
                        a[i] = true;
                    }
                    if let Some(y) = y {
                        x = y;
                    } else {
                        break;
                    }
                }
            }
        }
        writeln!(&mut output, "YES").unwrap();
    }
}


Score : <var>300</var> points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of <var>N</var> books on it, and Desk B similarly has <var>M</var> books on it.

It takes us <var>A_i</var> minutes to read the <var>i</var>-th book from the top on Desk A <var>(1 \leq i \leq N)</var>, and <var>B_i</var> minutes to read the <var>i</var>-th book from the top on Desk B <var>(1 \leq i \leq M)</var>.

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most <var>K</var> minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

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

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

<var>1 \leq A_i, B_i \leq 10^9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>K</var>
<var>A_1</var> <var>A_2</var> <var>\ldots</var> <var>A_N</var>
<var>B_1</var> <var>B_2</var> <var>\ldots</var> <var>B_M</var>

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us <var>60</var>, <var>90</var>, <var>120</var> minutes to read the <var>1</var>-st, <var>2</var>-nd, <var>3</var>-rd books from the top on Desk A, and <var>80</var>, <var>150</var>, <var>80</var>, <var>150</var> minutes to read the <var>1</var>-st, <var>2</var>-nd, <var>3</var>-rd, <var>4</var>-th books from the top on Desk B, respectively.

We can read three books in <var>230</var> minutes, as shown below, and this is the maximum number of books we can read within <var>240</var> minutes.

Read the topmost book on Desk A in <var>60</var> minutes, and remove that book from the desk.

Read the topmost book on Desk B in <var>80</var> minutes, and remove that book from the desk.

Read the topmost book on Desk A in <var>90</var> minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.

int solution(void) {

  long int desk1;
  long int desk2;
  long int limit;
  scanf("%ld%ld%ld", &desk1, &desk2, &limit);

  long int now1 = 0;
  long int now2 = desk2;
  long int sum1 = 0;
  long int sum2 = 0;
  long int max = 0;
  long int read1[desk1 + 1];
  long int read2[desk2 + 1];

  for (long int i = 0; i < desk1; i++) {
    scanf("%ld", &read1[i]);
  }

  for (long int i = 0; i < desk2; i++) {
    scanf("%ld", &read2[i]);
    sum2 += read2[i];
  }

  for (long int i = 0; i <= desk1; i++) {
    if (sum1 > limit) {
      break;
    }
    for (int j = 0; j < desk2; j++) {

      if (sum1 + sum2 > limit && now2 > 0) {
        now2--;

        sum2 -= read2[now2];
      } else {
        if (max < now1 + now2) {
          max = now1 + now2;
        }
        break;
      }
    }

    sum1 += read1[now1];
    now1++;
  }

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

  return 0;
}

fn solution() {
    let (n, m, k): (usize, usize, usize) = {
        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };
    let a: Vec<usize> = {
        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()
    };
    let b: Vec<usize> = {
        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()
    };

    let mut t = 0;
    let mut i = 0;
    while i < n && t + a[i] <= k {
        t += a[i];
        i += 1;
    }
    let mut ans = i;
    let mut j = 0;
    while j < m {
        while j < m && t + b[j] <= k {
            t += b[j];
            j += 1;
        }
        ans = std::cmp::max(ans, i + j);
        if i == 0 {
            break;
        }
        i -= 1;
        t -= a[i];
    }
    println!("{}", ans);
}


Alice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains $$$a$$$ stones, the second of them contains $$$b$$$ stones and the third of them contains $$$c$$$ stones.Each time she can do one of two operations:  take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);  take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $$$0$$$ stones. Can you help her?

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

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

        let mut input_iter = input.split_whitespace();
        let a: u8 = input_iter.next().unwrap().parse().unwrap();
        let b: u8 = input_iter.next().unwrap().parse().unwrap();
        let c: u8 = input_iter.next().unwrap().parse().unwrap();

        let op2 = b.min(c / 2);
        let op1 = a.min((b - op2) / 2);
        println!("{}", 3 * (op1 + op2));
    }
}


Score : <var>500</var> points

Problem Statement

Snuke, who loves animals, built a zoo.

There are <var>N</var> animals in this zoo. They are conveniently numbered <var>1</var> through <var>N</var>, and arranged in a circle.
The animal numbered <var>i (2≤i≤N-1)</var> is adjacent to the animals numbered <var>i-1</var> and <var>i+1</var>. Also, the animal numbered <var>1</var> is adjacent to the animals numbered <var>2</var> and <var>N</var>, and the animal numbered <var>N</var> is adjacent to the animals numbered <var>N-1</var> and <var>1</var>.

There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.

Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered <var>i</var> answered <var>s_i</var>. Here, if <var>s_i</var> is o, the animal said that the two neighboring animals are of the same species, and if <var>s_i</var> is x, the animal said that the two neighboring animals are of different species.

More formally, a sheep answered o if the two neighboring animals are both sheep or both wolves, and answered x otherwise.
Similarly, a wolf answered x if the two neighboring animals are both sheep or both wolves, and answered o otherwise.

Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print -1.

Constraints

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

<var>s</var> is a string of length <var>N</var> consisting of o and x.

Input

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

<var>N</var>
<var>s</var>

Output

If there does not exist an valid assignment that is consistent with <var>s</var>, print -1.
Otherwise, print an string <var>t</var> in the following format. The output is considered correct if the assignment described by <var>t</var> is consistent with <var>s</var>.

<var>t</var> is a string of length <var>N</var> consisting of S and W.

If <var>t_i</var> is S, it indicates that the animal numbered <var>i</var> is a sheep. If <var>t_i</var> is W, it indicates that the animal numbered <var>i</var> is a wolf.

Sample Input 1

6
ooxoox

Sample Output 1

SSSWWS

For example, if the animals numbered <var>1</var>, <var>2</var>, <var>3</var>, <var>4</var>, <var>5</var> and <var>6</var> are respectively a sheep, sheep, sheep, wolf, wolf, and sheep, it is consistent with their responses. Besides, there is another valid assignment of species: a wolf, sheep, wolf, sheep, wolf and wolf.

Let us remind you: if the neiboring animals are of the same species, a sheep answers o and a wolf answers x. If the neiboring animals are of different species, a sheep answers x and a wolf answers o.

Sample Input 2

3
oox

Sample Output 2

-1

Print -1 if there is no valid assignment of species.

Sample Input 3

10
oxooxoxoox

Sample Output 3

SSWWSSSWWS

fn solution() {
    let mut line1 = String::new();
    let mut line2 = String::new();
    let stdin = std::io::stdin();
    stdin.read_line(&mut line1).expect("Could not read line");
    stdin.read_line(&mut line2).expect("Could not read line");
    let p: Vec<_> = line1.trim().split(' ').collect();
    let n: usize = p[0].parse().unwrap();
    let s = line2.trim().as_bytes();
    for c1 in ['S', 'W'] {
        for c2 in ['S', 'W'] {
            let mut ret = Vec::new();
            ret.push(c1);
            ret.push(c2);
            for i in 2..n {
                if ret[i - 1] == 'S' {
                    if s[i - 1] == b'o' {
                        let x = ret[i - 2];
                        ret.push(x);
                    } else {
                        let x = if ret[i - 2] == 'S' { 'W' } else { 'S' };
                        ret.push(x);
                    }
                } else {
                    if s[i - 1] == b'o' {
                        let x = if ret[i - 2] == 'S' { 'W' } else { 'S' };
                        ret.push(x);
                    } else {
                        let x = ret[i - 2];
                        ret.push(x);
                    }
                }
            }
            if ((ret[1] == ret[n - 1]) == ((ret[0] == 'S') ^ (s[0] != b'o')))
                && ((ret[0] == ret[n - 2]) == ((ret[n - 1] == 'S') ^ (s[n - 1] != b'o')))
            {
                for i in 0..n {
                    print!("{}", ret[i]);
                }
                println!();
                return;
            }
        }
    }
    println!("-1");
}


One night, Mark realized that there is an essay due tomorrow. He hasn't written anything yet, so Mark decided to randomly copy-paste substrings from the prompt to make the essay.More formally, the prompt is a string $$$s$$$ of initial length $$$n$$$. Mark will perform the copy-pasting operation $$$c$$$ times. Each operation is described by two integers $$$l$$$ and $$$r$$$, which means that Mark will append letters $$$s_l s_{l+1} \ldots s_r$$$ to the end of string $$$s$$$. Note that the length of $$$s$$$ increases after this operation.Of course, Mark needs to be able to see what has been written. After copying, Mark will ask $$$q$$$ queries: given an integer $$$k$$$, determine the $$$k$$$-th letter of the final string $$$s$$$.

int solution() {
  int t;
  scanf("%d", &t);
  int n;
  int c;
  int q;
  for (int m = 0; m < t; m++) {
    scanf("%d %d %d", &n, &c, &q);

    char str[n];
    scanf("%s", str);
    long long a = strlen(str);
    long long arr1[c];
    long long arr2[c];
    long long total[c];
    for (int i = 0; i < c; i++) {
      scanf("%lld %lld", &arr1[i], &arr2[i]);

      if (i == 0) {
        total[i] = a + arr2[i] - arr1[i] + 1;
      } else {
        total[i] = total[i - 1] + arr2[i] - arr1[i] + 1;
      }
    }
    long long temp;

    for (int i = 0; i < q; i++) {
      scanf("%lld", &temp);
      int k = 0;
      while (temp > total[k]) {
        k++;
      }

      if (temp <= a) {
        printf("%c\n", str[temp - 1]);
      }

      else {
        int flag = 0;
        long long w = total[k] - temp;
        w = arr2[k] - w;
        k--;
        while (flag == 0) {
          if (w <= a) {
            printf("%c\n", str[w - 1]);
            flag = 1;
          } else {
            long long a1 = total[k] - w;
            if (arr2[k] - a1 >= arr1[k]) {
              w = arr2[k] - a1;
            }
          }
          k--;
        }
      }
    }
  }
}

fn solution() {
    input! {
        name = reader,
        tests: usize
    }
    for _ in 0..tests {
        input! {
            use reader,
            n: usize,
            c: usize,
            q: usize,
            s: bytes,
            cs: [(usize1, usize); c],
            qs: [usize1; q]
        }
        let mut shifts = vec![];
        let mut len = n;
        for (l, r) in cs {
            shifts.push((len, len - l));
            len += r - l;
        }
        for qi in qs {
            let mut pos = qi;
            for &(a, b) in shifts.iter().rev() {
                if pos >= a {
                    pos -= b;
                }
            }
            println!("{}", s[pos] as char)
        }
    }
}


You are given an array $$$a_1, a_2, \dots a_n$$$. Count the number of pairs of indices $$$1 \leq i, j \leq n$$$ such that $$$a_i < i < a_j < j$$$.

int solution() {
  int x;
  int y;
  int z;
  int i;
  int j;
  int k;
  int a;
  int b;
  int c;
  int n;
  int m;
  int t;
  int arr[200001];
  int aa[200001];
  long long ans;
  long long d;

  scanf("%d", &t);
  while (t--) {
    ans = 0;
    scanf("%d", &n);
    aa[0] = 0;
    for (x = 1; x <= n; x++) {
      scanf("%d", &arr[x]), aa[x] = aa[x - 1] + (arr[x] < x);
    }

    for (x = n; x > 0; x--) {
      if (arr[x] && (arr[x] < x)) {
        ans += aa[arr[x] - 1];
      }
    }

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

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

    let t: i32 = inp_t.trim().parse().expect("T is not an integer");

    for _ in 0..t {
        let mut inp_n = String::new();
        io::stdin()
            .read_line(&mut inp_n)
            .expect("Failed to read line");

        let n: usize = inp_n.trim().parse().expect("N is not an integer");

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

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

        v = s.trim().split(" ").map(|x| x.parse().unwrap()).collect();

        let mut ans: i64 = 0;

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

        for i in 0..n {
            if v[i] < (i + 1) as i32 {
                all.push((v[i], (i + 1) as i32));
            }
        }

        all.sort();

        for elem in &all {
            let temp = all.binary_search(&(elem.1 + 1, -1_i32));

            match temp {
                Err(pl) => ans += all.len() as i64 - pl as i64,
                _ => continue,
            };
        }

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


Score : <var>100</var> points

Problem Statement

Takahashi wants to be a member of some web service.

He tried to register himself with the ID <var>S</var>, which turned out to be already used by another user.

Thus, he decides to register using a string obtained by appending one character at the end of <var>S</var> as his ID.

He is now trying to register with the ID <var>T</var>. Determine whether this string satisfies the property above.

Constraints

<var>S</var> and <var>T</var> are strings consisting of lowercase English letters.

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

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

Input

Input is given from Standard Input in the following format:

<var>S</var>
<var>T</var>

Output

If <var>T</var> satisfies the property in Problem Statement, print Yes; otherwise, print No.

Sample Input 1

chokudai
chokudaiz

Sample Output 1

Yes

chokudaiz can be obtained by appending z at the end of chokudai.

Sample Input 2

snuke
snekee

Sample Output 2

No

snekee cannot be obtained by appending one character at the end of snuke.

Sample Input 3

a
aa

Sample Output 3

Yes

int solution(void) {
  char *S = (char *)malloc(128);
  char *T = (char *)malloc(128);
  scanf("%s", S);
  scanf("%s", T);
  *(T + (strlen(S))) = '\0';
  if (strcmp(S, T) != 0) {
    puts("No");
  } else {
    puts("Yes");
  }
  free(S);
  free(T);
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    s.pop();
    let mut t = String::new();
    stdin().read_line(&mut t).ok();
    t.pop();
    t.pop();

    println!("{}", if s == t { "Yes" } else { "No" });
}


Score : <var>500</var> points

Problem Statement

There are <var>N</var> boxes arranged in a circle. The <var>i</var>-th box contains <var>A_i</var> stones.

Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation:

Select one box. Let the box be the <var>i</var>-th box. Then, for each <var>j</var> from <var>1</var> through <var>N</var>, remove exactly <var>j</var> stones from the <var>(i+j)</var>-th box. Here, the <var>(N+k)</var>-th box is identified with the <var>k</var>-th box.

Note that the operation cannot be performed if there is a box that does not contain enough number of stones to be removed.

Constraints

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

<var>1 ≦ A_i ≦ 10^9</var>

Input

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

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

Output

If it is possible to remove all the stones from the boxes, print YES. Otherwise, print NO.

Sample Input 1

5
4 5 1 2 3

Sample Output 1

YES

All the stones can be removed in one operation by selecting the second box.

Sample Input 2

5
6 9 12 10 8

Sample Output 2

YES

Sample Input 3

4
1 2 3 1

Sample Output 3

NO

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

  long long sum = 0;
  long long diff[100001];
  for (i = 1; i <= N; i++) {
    sum += A[i];
    diff[i] = A[i] - A[i - 1];
  }
  if (sum % (N * (N + 1) / 2) != 0) {
    printf("NO\n");
  } else {
    sum /= N * (N + 1) / 2;
    for (i = 1, diff[0] = 0; i <= N; i++) {
      diff[i] = (sum - diff[i]) / N;
      if (diff[i] < 0 || diff[i] > sum) {
        break;
      }
      diff[0] += diff[i];
    }
    if (i <= N || diff[0] != sum) {
      printf("NO\n");
    } else {
      for (i = 1; i <= N; i++) {
        A[N] -= diff[i] * (N - i + 1);
      }
      if (A[N] != 0) {
        printf("No\n");
      } else {
        printf("YES\n");
      }
    }
  }
  fflush(stdout);
  return 0;
}

fn solution() {
    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line).unwrap();
    let N = input_line.trim().parse::<usize>().unwrap();
    let Ni = N as isize;

    let mut input_line = String::new();
    io::stdin().read_line(&mut input_line).unwrap();
    let data = input_line
        .trim()
        .split(" ")
        .map(|x| x.parse::<isize>().unwrap())
        .collect::<Vec<_>>();

    let step = (N * (N + 1) / 2) as isize;
    let total = data.iter().sum::<isize>();
    if total % step != 0 {
        println!("NO");
    } else {
        let K = total / step;
        let mut delta: Vec<isize> = Vec::with_capacity(N);
        for i in 0..N {
            delta.push(data[i] - data[(N + i - 1) % N]);
        }
        let invalid = delta
            .iter()
            .map(|x| (K - x < 0) || ((K - x) % Ni > 0))
            .fold(false, |a, b| a || b);
        if invalid {
            println!("NO");
        } else {
            let sum = delta.iter().map(|x| (K - x) / Ni).sum::<isize>();
            if sum == K {
                println!("YES");
            } else {
                println!("NO");
            }
        }
    }
}


Stanley defines the beauty of an array $$$a$$$ of length $$$n$$$, which contains non-negative integers, as follows: $$$$$$\sum\limits_{i = 1}^{n} \left \lfloor \frac{a_{i}}{k} \right \rfloor,$$$$$$ which means that we divide each element by $$$k$$$, round it down, and sum up the resulting values.Stanley told Sam the integer $$$k$$$ and asked him to find an array $$$a$$$ of $$$n$$$ non-negative integers, such that the beauty is equal to $$$b$$$ and the sum of elements is equal to $$$s$$$. Help Sam — find any of the arrays satisfying the conditions above.

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    let t: u32 = buf.trim().parse().unwrap();
    buf.clear();

    let mut out = String::new();
    for _ in 0..t {
        stdin().read_line(&mut buf).unwrap();
        let inp: Vec<&str> = buf.split_whitespace().collect();

        let n: usize = inp[0].parse().unwrap();
        let k: usize = inp[1].parse().unwrap();
        let b: usize = inp[2].parse().unwrap();
        let s: usize = inp[3].parse().unwrap();

        drop(inp);
        buf.clear();

        let first = k * b;

        if (s / k) * k < first {
            println!("-1");
            continue;
        }

        let mut rem = s - first;
        let cap = n * (k - 1);
        if cap + first < s {
            println!("-1");
            continue;
        }

        let first = first + rem.min(k - 1);
        out = first.to_string();
        rem -= rem.min(k - 1);

        for _ in 0..n - 1 {
            let t = rem.min(k - 1);
            out.push_str(&format!(" {}", t));
            rem -= t;
        }
        println!("{}", out);
        out.clear();
    }
}


Given the integer $$$n$$$ — the number of available blocks. You must use all blocks to build a pedestal. The pedestal consists of $$$3$$$ platforms for $$$2$$$-nd, $$$1$$$-st and $$$3$$$-rd places respectively. The platform for the $$$1$$$-st place must be strictly higher than for the $$$2$$$-nd place, and the platform for the $$$2$$$-nd place must be strictly higher than for the $$$3$$$-rd place. Also, the height of each platform must be greater than zero (that is, each platform must contain at least one block).    Example pedestal of $$$n=11$$$ blocks: second place height equals $$$4$$$ blocks, first place height equals $$$5$$$ blocks, third place height equals $$$2$$$ blocks.Among all possible pedestals of $$$n$$$ blocks, deduce one such that the platform height for the $$$1$$$-st place minimum as possible. If there are several of them, output any of them.

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin()
        .lines()
        .skip(1)
        .flatten()
        .flat_map(|s| s.parse::<usize>())
        .for_each(|n| {
            let a = n.wrapping_add(1).wrapping_div(3);
            let b = n.wrapping_add(5).wrapping_div(3);
            let c = n.wrapping_div(3).wrapping_sub(1);
            writeln!(buf, "{a} {b} {c}").ok();
        });
}


Score : <var>200</var> points

Problem Statement

There are <var>K</var> pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking <var>K</var> days to eat them all.

There are <var>T</var> types of cake, and the number of the cakes of type <var>i</var> (<var>1 ≤ i ≤ T</var>) is <var>a_i</var>.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

<var>1 ≤ K ≤ 10000</var>

<var>1 ≤ T ≤ 100</var>

<var>1 ≤ a_i ≤ 100</var>

<var>a_1 + a_2 + ... + a_T = K</var>

Input

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

<var>K</var> <var>T</var>
<var>a_1</var> <var>a_2</var> <var>...</var> <var>a_T</var>

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of <var>2, 1, 2, 3, 1, 3, 1</var>, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are <var>6</var> cakes.
For example, if Mr. Takahashi eats cakes in the order of <var>2, 3, 2, 2, 1, 2</var>, he has to eat the same type of cake (i.e., type <var>2</var>) as the previous day only on the fourth day.
Since this is the minimum number, the answer is <var>1</var>.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.

int solution(void) {

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

  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 _k: usize = itr.next().unwrap().parse().unwrap();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut a: Vec<usize> = (0..t)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();
    a.sort();
    a.reverse();

    let s = a.iter().sum::<usize>() - a[0];
    println!("{}", a[0].saturating_sub(s + 1));
}


Score : <var>400</var> points

Problem Statement

Find the largest integer that can be formed with exactly <var>N</var> matchsticks, under the following conditions:

Every digit in the integer must be one of the digits <var>A_1, A_2, ..., A_M (1 \leq A_i \leq 9)</var>.

The number of matchsticks used to form digits <var>1, 2, 3, 4, 5, 6, 7, 8, 9</var> should be <var>2, 5, 5, 4, 5, 6, 3, 7, 6</var>, respectively.

Constraints

All values in input are integers.

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

<var>1 \leq M \leq 9</var>

<var>1 \leq A_i \leq 9</var>

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

There exists an integer that can be formed by exactly <var>N</var> matchsticks under the conditions.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_M</var>

Output

Print the largest integer that can be formed with exactly <var>N</var> matchsticks under the conditions in the problem statement.

Sample Input 1

20 4
3 7 8 4

Sample Output 1

777773

The integer <var>777773</var> can be formed with <var>3 + 3 + 3 + 3 + 3 + 5 = 20</var> matchsticks, and this is the largest integer that can be formed by <var>20</var> matchsticks under the conditions.

Sample Input 2

101 9
9 8 7 6 5 4 3 2 1

Sample Output 2

71111111111111111111111111111111111111111111111111

The output may not fit into a <var>64</var>-bit integer type.

Sample Input 3

15 3
5 4 6

Sample Output 3

654

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 a: Vec<usize> = (0..m)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();

    let mut dp = vec!["unko".to_string(); n + 9];
    dp[0] = "".to_string();
    let maxs = |a: String, b: String| -> String {
        if a == "unko" || a.len() < b.len() {
            b
        } else if a.len() > b.len() {
            a
        } else {
            max(a, b)
        }
    };
    let b = [0, 2, 5, 5, 4, 5, 6, 3, 7, 6].to_vec();
    for i in 0..n {
        for &j in a.iter() {
            if dp[i] == "unko" {
                continue;
            }
            dp[i + b[j]] = maxs(dp[i + b[j]].clone(), dp[i].clone() + &j.to_string());
        }
    }
    println!("{}", dp[n]);
}


Is it a Right Triangle?

Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.

Input

Input consists of several data sets. In the first line, the number of data set, <var>N</var> is given. Then, <var>N</var> lines follow, each line corresponds to a data set. A data set consists of three integers separated by a single space.

Constraints

 1 ≤ length of the side ≤ 1,000

 <var>N</var> ≤ 1,000

Output

For each data set, print "YES" or "NO".

Sample Input

3
4 3 5
4 3 6
8 8 8

Output for the Sample Input

YES
NO
NO

int solution(void) {
  int kosu = 0;
  int a = 0;
  int b = 0;
  int c = 0;

  scanf("%d", &kosu);

  for (; kosu > 0; --kosu) {
    scanf("%d%d%d", &a, &b, &c);
    if (a * a == b * b + c * c || b * b == a * a + c * c ||
        c * c == a * a + b * b) {
      puts("YES");
    } else {
      puts("NO");
    }
    a = 0;
    b = 0;
    c = 0;
  }

  return (0);
}

fn solution() {
    let input = BufReader::new(stdin());
    for line in input.lines() {
        let mut values: Vec<u32> = line
            .unwrap()
            .split_whitespace()
            .filter_map(|x| x.parse::<u32>().ok())
            .collect();
        if values.len() == 1 {
            continue;
        }
        values.sort();
        let values: Vec<u32> = values.into_iter().map(|x| x.pow(2)).collect();
        if values[2] == (values[0] + values[1]) {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score: <var>500</var> points

Problem Statement

<var>N</var> programmers are going to participate in the preliminary stage of DDCC 20XX. Due to the size of the venue, however, at most <var>9</var> contestants can participate in the finals.

The preliminary stage consists of several rounds, which will take place as follows:

All the <var>N</var> contestants will participate in the first round.

When <var>X</var> contestants participate in some round, the number of contestants advancing to the next round will be decided as follows:

The organizer will choose two consecutive digits in the decimal notation of <var>X</var>, and replace them with the sum of these digits. The number resulted will be the number of contestants advancing to the next round.

For example, when <var>X = 2378</var>, the number of contestants advancing to the next round will be <var>578</var> (if <var>2</var> and <var>3</var> are chosen), <var>2108</var> (if <var>3</var> and <var>7</var> are chosen), or <var>2315</var> (if <var>7</var> and <var>8</var> are chosen).

When <var>X = 100</var>, the number of contestants advancing to the next round will be <var>10</var>, no matter which two digits are chosen.

The preliminary stage ends when <var>9</var> or fewer contestants remain.

Ringo, the chief organizer, wants to hold as many rounds as possible.
Find the maximum possible number of rounds in the preliminary stage.

Since the number of contestants, <var>N</var>, can be enormous, it is given to you as two integer sequences <var>d_1, \ldots, d_M</var> and <var>c_1, \ldots, c_M</var>, which means the following: the decimal notation of <var>N</var> consists of <var>c_1 + c_2 + \ldots + c_M</var> digits, whose first <var>c_1</var> digits are all <var>d_1</var>, the following <var>c_2</var> digits are all <var>d_2</var>, <var>\ldots</var>, and the last <var>c_M</var> digits are all <var>d_M</var>.

Constraints

<var>1 \leq M \leq 200000</var>

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

<var>d_1 \neq 0</var>

<var>d_i \neq d_{i+1}</var>

<var>c_i \geq 1</var>

<var>2 \leq c_1 + \ldots + c_M \leq 10^{15}</var>

Input

Input is given from Standard Input in the following format:

<var>M</var>
<var>d_1</var> <var>c_1</var>
<var>d_2</var> <var>c_2</var>
<var>:</var>
<var>d_M</var> <var>c_M</var>

Output

Print the maximum possible number of rounds in the preliminary stage.

Sample Input 1

2
2 2
9 1

Sample Output 1

3

In this case, <var>N = 229</var> contestants will participate in the first round. One possible progression of the preliminary stage is as follows:

<var>229</var> contestants participate in Round <var>1</var>, <var>49</var> contestants participate in Round <var>2</var>, <var>13</var> contestants participate in Round <var>3</var>, and <var>4</var> contestants advance to the finals.

Here, three rounds take place in the preliminary stage, which is the maximum possible number.

Sample Input 2

3
1 1
0 8
7 1

Sample Output 2

9

In this case, <var>1000000007</var> will participate in the first round.

int solution() {
  int m;
  scanf("%d", &m);
  int i;
  long long int d[200005];
  long long int c[200005];
  for (i = 0; i < m; i++) {
    scanf("%lld %lld", &d[i], &c[i]);
  }
  long long int ans = 0;
  for (i = 0; i < m; i++) {
    ans += c[i];
  }
  ans--;
  long long int v = 0;
  for (i = 0; i < m; i++) {
    v += d[i] * c[i];
  }
  ans += v / 10;
  while (v > 9) {
    v = v / 10 + v % 10;
    ans += v / 10;
  }
  printf("%lld\n", ans);
  return 0;
}

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

    let s = (0..M).map(|i| d[i] * c[i]).sum::<usize>();
    let y = if s <= 9 { 0 } else { 1 + (s - 10) / 9 };
    let ans = c.iter().sum::<usize>() - 1 + y;

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


Score : <var>400</var> points

Problem Statement

We have a board with a <var>2 \times N</var> grid.
Snuke covered the board with <var>N</var> dominoes without overlaps.
Here, a domino can cover a <var>1 \times 2</var> or <var>2 \times 1</var> square.

Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.

Find the number of such ways to paint the dominoes, modulo <var>1000000007</var>.

The arrangement of the dominoes is given to you as two strings <var>S_1</var> and <var>S_2</var> in the following manner:

Each domino is represented by a different English letter (lowercase or uppercase).

The <var>j</var>-th character in <var>S_i</var> represents the domino that occupies the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left.

Constraints

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

<var>|S_1| = |S_2| = N</var>

<var>S_1</var> and <var>S_2</var> consist of lowercase and uppercase English letters.

<var>S_1</var> and <var>S_2</var> represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var>
<var>S_2</var>

Output

Print the number of such ways to paint the dominoes, modulo <var>1000000007</var>.

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

Note that it is not always necessary to use all the colors.

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902

int solution(void) {
  int n;
  scanf("%d", &n);
  char s1[n];
  char s2[n];
  scanf("%s", s1);
  scanf("%s", s2);

  long long exp = 1;
  int leftis2 = 0;
  int leftis1 = 0;
  for (int i = 0; i < n; i++) {
    if (s1[i] == s2[i]) {
      if (leftis1 == 1) {
        exp *= 2;
      } else if (leftis2 == 1) {
        exp *= 1;
      } else {
        exp *= 3;
      }
      leftis1 = 1;
      leftis2 = 0;
    } else {
      if (leftis1 == 1) {
        exp *= 2;
      } else if (leftis2 == 1) {
        exp *= 3;
      } else {
        exp *= 6;
      }
      leftis1 = 0;
      leftis2 = 1;
      i++;
    }
    if (exp > 1000000008) {
      exp = exp % 1000000007;
    }
  }
  printf("%lld", exp);
  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 s: Vec<char> = itr.next().unwrap().chars().collect();
    let t: Vec<char> = itr.next().unwrap().chars().collect();

    let mut op = Vec::new();
    const MOD: u64 = 1_000_000_007;

    let mut i = 0;
    while i < n {
        if s[i] != t[i] {
            op.push(0);
            i += 1;
        } else {
            op.push(1);
        }
        i += 1;
    }

    let mut ans = 0u64;
    if op[0] == 0 {
        ans += 6;
    } else {
        ans += 3;
    }
    for i in 1..op.len() {
        if op[i - 1] == 0 {
            if op[i] == 0 {
                ans = ans * 3 % MOD;
            }
        } else {
            ans = ans * 2 % MOD;
        }
    }
    println!("{}", ans);
}


You are given two binary strings $$$x$$$ and $$$y$$$, which are binary representations of some two integers (let's denote these integers as $$$f(x)$$$ and $$$f(y)$$$). You can choose any integer $$$k \ge 0$$$, calculate the expression $$$s_k = f(x) + f(y) \cdot 2^k$$$ and write the binary representation of $$$s_k$$$ in reverse order (let's denote it as $$$rev_k$$$). For example, let $$$x = 1010$$$ and $$$y = 11$$$; you've chosen $$$k = 1$$$ and, since $$$2^1 = 10_2$$$, so $$$s_k = 1010_2 + 11_2 \cdot 10_2 = 10000_2$$$ and $$$rev_k = 00001$$$.For given $$$x$$$ and $$$y$$$, you need to choose such $$$k$$$ that $$$rev_k$$$ is lexicographically minimal (read notes if you don't know what does "lexicographically" means).It's guaranteed that, with given constraints, $$$k$$$ exists and is finite.

int solution() {
  int T;
  char strX[100001];
  char strY[100001];
  scanf("%d", &T);
  while (T--) {
    scanf("%s %s", strX, strY);
    int lenX = strlen(strX);
    int lenY = strlen(strY);
    int idxY = -1;
    for (int i = lenY - 1; i >= 0; --i) {
      if (strY[i] == '1') {
        idxY = i;
        break;
      }
    }
    if (idxY == -1) {
      puts("0");
    } else {
      char find = 0;
      int ans = 0;
      for (int i = lenX - 1 - (lenY - 1 - idxY); i >= 0; --i) {
        if (strX[i] == '1') {
          find = 1;
          break;
        }
        ++ans;
      }
      printf("%d\n", find ? ans : 0);
    }
  }
  return 0;
}

fn solution() {
    let stdin = stdin();
    let mut stdin = stdin.lock();
    let t: usize = {
        let mut string = String::new();
        stdin.read_line(&mut string);
        string
            .split_ascii_whitespace()
            .next()
            .unwrap()
            .parse()
            .unwrap()
    };

    for _ in 0..t {
        let mut x = String::new();
        let mut y = String::new();
        stdin.read_line(&mut x);
        stdin.read_line(&mut y);
        let x = x.bytes().collect::<Vec<u8>>();
        let y = y.bytes().collect::<Vec<u8>>();

        let yf = y
            .iter()
            .rev()
            .enumerate()
            .find(|&it| *it.1 == b'1')
            .unwrap()
            .0;
        let xf = x
            .iter()
            .rev()
            .enumerate()
            .skip(yf)
            .find(|&it| *it.1 == b'1')
            .unwrap()
            .0;

        println!("{}", xf - yf);
    }
}


Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with $$$n$$$ integers written on it.Polycarp wrote the numbers from the disk into the $$$a$$$ array. It turned out that the drive works according to the following algorithm:   the drive takes one positive number $$$x$$$ as input and puts a pointer to the first element of the $$$a$$$ array;  after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the $$$a$$$ array, the last element is again followed by the first one;  as soon as the sum is at least $$$x$$$, the drive will shut down. Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you $$$m$$$ questions. To answer the $$$i$$$-th of them, you need to find how many seconds the drive will work if you give it $$$x_i$$$ as input. Please note that in some cases the drive can work infinitely.For example, if $$$n=3, m=3$$$, $$$a=[1, -3, 4]$$$ and $$$x=[1, 5, 2]$$$, then the answers to the questions are as follows:   the answer to the first query is $$$0$$$ because the drive initially points to the first item and the initial sum is $$$1$$$.  the answer to the second query is $$$6$$$, the drive will spin the disk completely twice and the amount becomes $$$1+(-3)+4+1+(-3)+4+1=5$$$.  the answer to the third query is $$$2$$$, the amount is $$$1+(-3)+4=2$$$.

int solution() {
  int t;
  int n;
  int m;
  static long long a[200000] = {[0 ... 199999] = 0};
  static long long ascA[200000] = {[0 ... 199999] = 0};
  static long long x[200000] = {[0 ... 199999] = 0};
  int ans;
  int rm;
  int upbound;
  long long step;
  long long lcnt;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    scanf("%d %d", &n, &m);
    lcnt = 0;
    scanf("%d", &a[0]);
    ascA[lcnt++] = 0;
    for (int j = 1; j < n; j++) {
      scanf("%d", &a[j]);
      a[j] += a[j - 1];
      if (a[j] > a[ascA[lcnt - 1]]) {
        ascA[lcnt++] = j;
      }
    }
    upbound = (int)lcnt;
    lcnt = a[n - 1];
    for (int j = 0; j < m; j++) {
      scanf("%d", &ans);
      step = 0;
      int up = upbound;
      int low = -1;
      int mid = (up + low) / 2;
      if (lcnt > 0) {
        if (a[ascA[up - 1]] < ans) {
          rm = ans - a[ascA[up - 1]];
          step = rm / lcnt + !!(rm % lcnt);
          ans -= lcnt * step;
          step *= n;
        }
      } else {
        if (a[ascA[up - 1]] < ans) {
          step = -1;
        }
      }
      if (step != -1) {
        while (up - low > 1) {
          if (a[ascA[mid]] >= ans) {
            up = mid;
          } else {
            low = mid;
          }
          mid = (up + low) / 2;
        }
        step += ascA[up];
      }
      x[j] = step;
    }
    for (int j = 0; j < m; j++) {
      printf("%d ", x[j]);
    }
    printf("\n");
  }
}

fn solution() {
    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, q): (usize, usize) = (sc.next(), sc.next());
        let arr: Vec<i64> = (0..n).map(|_| sc.next()).collect();

        let mut pref_sum: Vec<i64> = arr.clone();
        (1..n).for_each(|i| pref_sum[i] += pref_sum[i - 1]);

        let mut max_arr: Vec<i64> = pref_sum.clone();
        (1..n).for_each(|i| max_arr[i] = max(max_arr[i], max_arr[i - 1]));

        let mx: i64 = *pref_sum.iter().max().unwrap();
        let sum: i64 = pref_sum[n - 1];

        for _ in 0..q {
            let mut x: i64 = sc.next();
            let mut ans: i64 = 0;
            if mx < x {
                if sum <= 0 {
                    write!(out, "-1 ").unwrap();
                    continue;
                }
                let times = (x - mx + sum - 1) / sum;
                ans += times * n as i64;
                x -= times * sum;
            }
            let (mut start, mut end, mut idx): (i32, i32, i32) = (0, n as i32 - 1, 0);
            while start <= end {
                let mid: i32 = (start + end) >> 1;
                if max_arr[mid as usize] >= x {
                    idx = mid;
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            }
            ans += idx as i64;
            write!(out, "{} ", ans).unwrap();
        }
        writeln!(out).unwrap();
    }
}


How Many Divisors?

  Write a program which reads three integers <var>a</var>, <var>b</var> and <var>c</var>, and prints the number of divisors of <var>c</var> between <var>a</var> and <var>b</var>.

Input

  Three integers <var>a</var>, <var>b</var> and <var>c</var> are given in a line separated by a single space.

Output

Print the number of divisors in a line.

Constraints

 1 ≤ <var>a</var>, <var>b</var>, <var>c</var> ≤ 10000

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

Sample Input 1

5 14 80

Sample Output 1

3

int solution(void) {

  int a = 0;
  scanf("%d", &a);
  int b = 0;
  scanf("%d", &b);
  int c = 0;
  scanf("%d", &c);

  int counter = 0;

  for (int i = 1; i <= c; i++) {

    if (c % i == 0) {

      if (((c / i) >= a) && ((c / i) <= b)) {
        counter++;
      }
    }
  }

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

  return 0;
}

fn solution() {
    let v: Vec<u32> = {
        let mut b = String::new();
        let s = std::io::stdin();
        s.read_line(&mut b).unwrap();
        b.split_whitespace().flat_map(str::parse).collect()
    };
    println!(
        "{}",
        (v[0]..v[1] + 1).filter(|i| v[2].is_multiple_of(*i)).count()
    );
}


Score : <var>700</var> points

Problem Statement

<var>10^{10^{10}}</var> participants, including Takahashi, competed in two programming contests.
In each contest, all participants had distinct ranks from first through <var>10^{10^{10}}</var>-th.

The score of a participant is the product of his/her ranks in the two contests.

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

In the <var>i</var>-th query, you are given two positive integers <var>A_i</var> and <var>B_i</var>. Assuming that Takahashi was ranked <var>A_i</var>-th in the first contest and <var>B_i</var>-th in the second contest, find the maximum possible number of participants whose scores are smaller than Takahashi's.

Constraints

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

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>Q</var>
<var>A_1</var> <var>B_1</var>
<var>:</var>
<var>A_Q</var> <var>B_Q</var>

Output

For each query, print the maximum possible number of participants whose scores are smaller than Takahashi's.

Sample Input 1

8
1 4
10 5
3 3
4 11
8 9
22 40
8 36
314159265 358979323

Sample Output 1

1
12
4
11
14
57
31
671644785

Let us denote a participant who was ranked <var>x</var>-th in the first contest and <var>y</var>-th in the second contest as <var>(x,y)</var>.

In the first query, <var>(2,1)</var> is a possible candidate of a participant whose score is smaller than Takahashi's. There are never two or more participants whose scores are smaller than Takahashi's, so we should print <var>1</var>.

int solution() {
  int i;
  int Q;
  long long A;
  long long B;
  long long C;
  long long ans;
  scanf("%d", &Q);
  for (i = 1; i <= Q; i++) {
    scanf("%lld %lld", &A, &B);
    C = (long long)sqrt(A * B);
    ans = (C - 1) * 2;
    if (C * (C + 1) < A * B) {
      ans++;
    } else if (C * C == A * B) {
      ans--;
    }
    if (A != B) {
      printf("%lld\n", ans);
    } else {
      printf("%lld\n", A + B - 2);
    }
  }

  fflush(stdout);
  return 0;
}

fn solution() {
    input! {
        q: usize,
        v: [(usize, usize); q]
    }
    for &(a, b) in &v {
        let x = min(a, b);
        let y = max(a, b);
        let mut l = 0;
        let mut r = y;
        while l + 1 < r {
            let m = (l + r) / 2;
            if m * m < x * y {
                l = m;
            } else {
                r = m;
            }
        }
        if x == y || x + 1 == y {
            println!("{}", 2 * x - 2);
        } else if l * (l + 1) >= x * y {
            println!("{}", 2 * l - 2);
        } else {
            println!("{}", 2 * l - 1);
        }
    }
}


The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.

int solution() {
  int n;
  int i;
  int t[1005] = {0};
  int g[1005];
  int yer = 0;
  int kontrol;
  int k;
  int j;
  int max;
  int sonuc;
  int puan[1005] = {0};
  char c[1005][35] = {0};
  char s[1005][35];
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    kontrol = 1;
    scanf("%s %d", s[i], &g[i]);
    for (j = 0; j < yer; j++) {
      if (!strcmp(c[j], s[i])) {
        t[j] += g[i];
        kontrol = 0;
      }
    }
    if (kontrol) {
      for (k = 0; k < 35; k++) {
        c[yer][k] = s[i][k];
      }
      t[yer] += g[i];
      yer++;
    }
  }

  max = t[0];
  for (i = 1; i < yer; i++) {
    if (t[i] > max) {
      max = t[i];
    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < yer; j++) {
      if (!strcmp(c[j], s[i])) {
        puan[j] += g[i];
        if (puan[j] >= max && t[j] == max) {
          printf("%s", c[j]);
          return 0;
        }
      }
    }
  }
  return 0;
}

fn solution() -> Result<(), Box<dyn std::error::Error>> {
    let stdin = std::io::stdin();
    let stdin = stdin.lock();
    let mut lines = stdin.lines();

    let n = lines.next().unwrap()?.parse::<usize>().unwrap();
    let mut a = Vec::<(String, i32)>::new();
    let mut scores = HashMap::<String, i32>::new();
    for _ in 0..n {
        let line = lines.next().unwrap().unwrap();
        let mut line = line.split_whitespace();
        let (name, score) = (line.next().unwrap(), line.next().unwrap());
        let score = score.parse::<i32>()?;
        a.push((name.to_string(), score));
        *scores.entry(name.to_string()).or_default() += score;
    }
    let mx = *scores.values().max().unwrap();
    let cnt = scores.values().filter(|s| **s == mx).count();
    let mut ans = String::new();

    if cnt == 1 {
        ans = scores
            .iter()
            .find(|(_, v)| **v == mx)
            .unwrap()
            .0
            .to_string();
    } else {
        let mut scores2 = HashMap::<String, i32>::new();
        for (name, score) in a {
            *scores2.entry(name.clone()).or_default() += score;
            if scores2[&name] >= mx && scores[&name] == mx {
                ans = name;
                break;
            }
        }
    }

    println!("{}", ans);

    Ok(())
}


Recall that the sequence $$$b$$$ is a a subsequence of the sequence $$$a$$$ if $$$b$$$ can be derived from $$$a$$$ by removing zero or more elements without changing the order of the remaining elements. For example, if $$$a=[1, 2, 1, 3, 1, 2, 1]$$$, then possible subsequences are: $$$[1, 1, 1, 1]$$$, $$$[3]$$$ and $$$[1, 2, 1, 3, 1, 2, 1]$$$, but not $$$[3, 2, 3]$$$ and $$$[1, 1, 1, 1, 2]$$$.You are given a sequence $$$a$$$ consisting of $$$n$$$ positive and negative elements (there is no zeros in the sequence).Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.In other words, if the maximum length of alternating subsequence is $$$k$$$ then your task is to find the maximum sum of elements of some alternating subsequence of length $$$k$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int size = 0;
    long long int sum = 0;
    scanf("%d", &size);
    long long int arr[size];
    for (int i = 1; i <= size; i++) {
      scanf("%lld", &arr[i]);
    }

    arr[0] = -arr[1];

    int j = 0;
    int k = 1;
    while (k <= size) {
      if (arr[k] * arr[j] < 0) {
        if (k <= size - 1) {
          int p = k + 1;
          while (arr[p] * arr[k] > 0 && p <= size) {
            if (arr[p] >= arr[k]) {
              k = p;
            }
            p++;
          }
        }

        sum = sum + arr[k];
        j = k;
      }
      k++;
    }
    printf("%lld\n", sum);
  }
}

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: usize = itr.next().unwrap().parse().unwrap();
        let a: Vec<i64> = (0..n)
            .map(|_| itr.next().unwrap().parse().unwrap())
            .collect();
        if a.iter().all(|&x| x > 0) || a.iter().all(|&x| x < 0) {
            writeln!(out, "{}", a.iter().max().unwrap()).ok();
        } else {
            let mut i = 0;
            let mut arr = Vec::new();
            let mut max = -(1 << 60);
            while i < n {
                max = std::cmp::max(max, a[i]);
                if i + 1 < n && a[i] * a[i + 1] < 0 {
                    arr.push(max);
                    max = -(1 << 60);
                }
                i += 1;
            }
            arr.push(max);
            writeln!(out, "{}", arr.iter().sum::<i64>()).ok();
        }
    }
    stdout().write_all(&out).unwrap();
}


Score : <var>500</var> points

Problem Statement

There are <var>2N</var> squares arranged from left to right. You are given a string of length <var>2N</var> representing the color of each of the squares.

The color of the <var>i</var>-th square from the left is black if the <var>i</var>-th character of <var>S</var> is B, and white if that character is W.

You will perform the following operation exactly <var>N</var> times: choose two distinct squares, then invert the colors of these squares and the squares between them. Here, to invert the color of a square is to make it white if it is black, and vice versa.

Throughout this process, you cannot choose the same square twice or more. That is, each square has to be chosen exactly once.

Find the number of ways to make all the squares white at the end of the process, modulo <var>10^9+7</var>.

Two ways to make the squares white are considered different if and only if there exists <var>i</var> <var>(1 \leq i \leq N)</var> such that the pair of the squares chosen in the <var>i</var>-th operation is different.

Constraints

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

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

Each character of <var>S</var> is B or W.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of ways to make all the squares white at the end of the process, modulo <var>10^9+7</var>. If there are no such ways, print <var>0</var>.

Sample Input 1

2
BWWB

Sample Output 1

4

There are four ways to make all the squares white, as follows:

Choose Squares <var>1, 3</var> in the first operation, and choose Squares <var>2, 4</var> in the second operation.

Choose Squares <var>2, 4</var> in the first operation, and choose Squares <var>1, 3</var> in the second operation.

Choose Squares <var>1, 4</var> in the first operation, and choose Squares <var>2, 3</var> in the second operation.

Choose Squares <var>2, 3</var> in the first operation, and choose Squares <var>1, 4</var> in the second operation.

Sample Input 2

4
BWBBWWWB

Sample Output 2

288

Sample Input 3

5
WWWWWWWWWW

Sample Output 3

0

int solution() {
  long long int n;
  scanf("%lld\n", &n);
  char s[200005];
  scanf("%s", s);
  long long int p = 1e9 + 7;
  long long int i;
  long long int count = 0;
  long long int ans = 1;
  for (i = 1; i <= n; i++) {
    ans = ans * i % p;
  }
  for (i = 0; i < 2 * n; i++) {
    if (s[i] == 'B') {
      if (count % 2 == 0) {
        count++;
      } else {
        ans = ans * count % p;
        count--;
      }
    } else {
      if (count % 2 == 1) {
        count++;
      } else {
        ans = ans * count % p;
        count--;
      }
    }
  }
  if (count != 0) {
    ans = 0;
  }
  printf("%lld\n", ans);
  return 0;
}

fn solution() {
    let N: i64 = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let S: Vec<char> = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().chars().collect()
    };

    let MOD = 1_000_000_007;

    let ans = {
        let (x, y) = S.iter().fold(
            ((1..(N + 1)).fold(1, |f, i| (f * i) % MOD), 0),
            |(res, k), &c| {
                if c == 'B' && k % 2 == 0 || c == 'W' && k % 2 == 1 {
                    (res, k + 1)
                } else {
                    ((res * k) % MOD, k - 1)
                }
            },
        );
        if y == 0 {
            x
        } else {
            0
        }
    };

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


You are given an array $$$a$$$ of $$$n$$$ integers.You want to make all elements of $$$a$$$ equal to zero by doing the following operation exactly three times:  Select a segment, for each number in this segment we can add a multiple of $$$len$$$ to it, where $$$len$$$ is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of $$$a$$$ equal to zero.

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

  for (int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
  }
  if (n == 1) {
    printf("%d %d\n%d\n", 1, 1, -arr[0]);
    printf("1 1\n0\n1 1\n0");
    return 0;
  }
  printf("%d %lld\n", 1, n - 1);
  for (int i = 0; i < n - 1; i++) {
    printf("%lld ", (n - 1) * arr[i]);
  }
  printf("\n%d %lld\n", 1, n);
  for (int i = 0; i < n; i++) {
    printf("%lld ", -n * arr[i]);
  }
  printf("\n%lld %lld\n", n, n);
  printf("%lld", (arr[n - 1] * (n - 1)));
  return 0;
}

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

    let 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()
    };

    let mut ans = Vec::with_capacity(6);
    if n == 1 {
        ans.push("1 1\n0".to_string());
        ans.push("1 1\n0".to_string());
        ans.push(format!("1 1\n{}", -a[0]));
    } else {
        ans.push(format!("1 1\n{}", -a[0]));
        let tmp: Vec<_> = { (1..n).map(|i| (-a[i] * n as i64).to_string()).collect() };
        ans.push(format!("1 {}\n0 {}", n, tmp.join(" ")));
        let tmp: Vec<_> = {
            (1..n)
                .map(|i| (a[i] * (n - 1) as i64).to_string())
                .collect()
        };
        ans.push(format!("2 {}\n{}", n, tmp.join(" ")));
    }
    println!("{}", ans.join("\n"));
}


Alice and Bob are playing a game on an array $$$a$$$ of $$$n$$$ positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If $$$a_1 = 0$$$, the player loses the game, otherwise: Player chooses some $$$i$$$ with $$$2\le i \le n$$$. Then player decreases the value of $$$a_1$$$ by $$$1$$$ and swaps $$$a_1$$$ with $$$a_i$$$. Determine the winner of the game if both players play optimally.

int solution() {
  int t;
  int n;
  char c[10];
  scanf("%d", &t);
  while (t > 0) {
    scanf("%d", &n);
    int a[n];
    for (int i = 0; i < n; ++i) {
      scanf("%d", &a[i]);
    }
    for (int i = 1; i < n; ++i) {
      if (a[0] <= a[i]) {
        strcpy(c, "Bob");
      } else {
        strcpy(c, "Alice");
        break;
      }
    }
    printf("%s\n", c);
    t--;
  }

  return 0;
}

fn solution() {
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin().lines().flatten().for_each(|s| {
        let mut i = s.split_ascii_whitespace().flat_map(str::parse::<usize>);
        if let Some(a) = i.next()
            && let Some(m) = i.min() {
                writeln!(buf, "{}", if a > m { "Alice" } else { "Bob" }).ok();
            }
    });
}


Score : <var>400</var> points

Problem Statement

There is a grid with <var>H</var> horizontal rows and <var>W</var> vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given <var>H</var> strings <var>S_i</var> (<var>1 \leq i \leq H</var>), each of length <var>W</var>. If the <var>j</var>-th character (<var>1 \leq j \leq W</var>) of <var>S_i</var> is #, there is an obstacle on the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

<var>1 \leq H \leq 2,000</var>

<var>1 \leq W \leq 2,000</var>

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

. occurs at least once in one of the strings <var>S_i</var> (<var>1 \leq i \leq H</var>).

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 maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13

int solution() {
  int h;
  int w;
  scanf("%d %d", &h, &w);
  int field[2005][2005] = {0};
  for (int i = 0; i < h; i++) {
    char s[2005];
    scanf("%s", s);
    for (int j = 0; j < w; j++) {
      if (s[j] == '#') {
        field[i + 1][j + 1] = 1;
      }
    }
  }

  int tate[2020][2020] = {0};
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      if (tate[i][j] || field[i][j]) {
        continue;
      }
      int stack[2020] = {0};
      int now = i;
      while (!field[now][j] && now <= h) {
        stack[++stack[0]] = now++;
      }
      int max = stack[0];
      while (stack[0]) {
        tate[stack[stack[0]--]][j] = max;
      }
    }
  }

  int yoko[2020][2020] = {0};
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      if (yoko[i][j] || field[i][j]) {
        continue;
      }
      int stack[2020] = {0};
      int now = j;
      while (!field[i][now] && now <= w) {
        stack[++stack[0]] = now++;
      }
      int max = stack[0];
      while (stack[0]) {
        yoko[i][stack[stack[0]--]] = max;
      }
    }
  }

  int ans = 0;
  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      if (field[i][j]) {
        continue;
      }
      if (tate[i][j] + yoko[i][j] > ans) {
        ans = tate[i][j] + yoko[i][j];
      }
    }
  }

  printf("%d\n", ans - 1);
  return 0;
}

fn solution() {
    let (h, w) = {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        let mut integers = line.split_whitespace().map(|e| e.parse::<usize>().unwrap());
        (integers.next().unwrap(), integers.next().unwrap())
    };

    let mut s: Vec<Vec<char>> = Vec::new();
    for _ in 0..h {
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        s.push(line.chars().collect());
    }

    let mut l: Vec<Vec<usize>> = Vec::new();
    let mut r: Vec<Vec<usize>> = Vec::new();
    let mut u: Vec<Vec<usize>> = Vec::new();
    let mut d: Vec<Vec<usize>> = Vec::new();
    for x in 0..h {
        l.push(Vec::new());
        r.push(Vec::new());
        u.push(Vec::new());
        d.push(Vec::new());
        l[x].resize(w, 0);
        r[x].resize(w, 0);
        u[x].resize(w, 0);
        d[x].resize(w, 0);
    }

    for x in 0..h {
        for y in (0..w).rev() {
            r[x][y] = if s[x][y] == '#' {
                0
            } else {
                if y == w - 1 {
                    1
                } else {
                    r[x][y + 1] + 1
                }
            }
        }
    }

    for x in 0..h {
        for y in 0..w {
            l[x][y] = if s[x][y] == '#' {
                0
            } else {
                if y == 0 {
                    1
                } else {
                    l[x][y - 1] + 1
                }
            }
        }
    }

    for y in 0..w {
        for x in (0..h).rev() {
            u[x][y] = if s[x][y] == '#' {
                0
            } else {
                if x == h - 1 {
                    1
                } else {
                    u[x + 1][y] + 1
                }
            }
        }
    }

    for y in 0..w {
        for x in 0..h {
            d[x][y] = if s[x][y] == '#' {
                0
            } else {
                if x == 0 {
                    1
                } else {
                    d[x - 1][y] + 1
                }
            }
        }
    }

    let mut answer = 0;
    for x in 0..h {
        for y in 0..w {
            if s[x][y] == '.' {
                let t = l[x][y] + r[x][y] + u[x][y] + d[x][y] - 3;
                answer = std::cmp::max(answer, t);
            }
        }
    }

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


Score: <var>200</var> points

Problem Statement

You are an immigration officer in the Kingdom of AtCoder. The document carried by an immigrant has some number of integers written on it, and you need to check whether they meet certain criteria.

According to the regulation, the immigrant should be allowed entry to the kingdom if and only if the following condition is satisfied:

All even numbers written on the document are divisible by <var>3</var> or <var>5</var>.

If the immigrant should be allowed entry according to the regulation, output APPROVED; otherwise, print DENIED.

Notes

The condition in the statement can be rephrased as "If <var>x</var> is an even number written on the document, <var>x</var> is divisible by <var>3</var> or <var>5</var>".
Here "if" and "or" are logical terms.

Constraints

All values in input are integers.

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

<var>1 \leq A_i \leq 1000</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>A_2</var> <var>\dots</var> <var>A_N</var>

Output

If the immigrant should be allowed entry according to the regulation, print APPROVED; otherwise, print DENIED.

Sample Input 1

5
6 7 9 10 31

Sample Output 1

APPROVED

The even numbers written on the document are <var>6</var> and <var>10</var>.

All of them are divisible by <var>3</var> or <var>5</var>, so the immigrant should be allowed entry.

Sample Input 2

3
28 27 24

Sample Output 2

DENIED

<var>28</var> violates the condition, so the immigrant should not be allowed entry.

int solution(void) {
  int n = 0;
  int a = 0;
  int flag = 1;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a);
    if (a % 2 == 0) {
      if (a % 3 != 0 && a % 5 != 0) {
        flag = 0;
      }
    }
  }

  if (flag == 1) {
    printf("APPROVED");
  } else {
    printf("DENIED");
  }
  return 0;
}

fn solution() {
    let mut number_count = String::new();
    io::stdin().read_line(&mut number_count).unwrap();
    number_count.pop();
    let mut numbers = String::new();
    io::stdin().read_line(&mut numbers).unwrap();
    numbers.pop();
    let numbers: Vec<u32> = numbers
        .split(' ')
        .map(|s| u32::from_str(s).unwrap())
        .collect();
    for number in numbers {
        if number % 2 == 0 && !(number % 3 == 0 || number % 5 == 0) {
            println!("DENIED");
            return;
        }
    }
    println!("APPROVED");
}


改元

平成31年4月30日をもって現行の元号である平成が終了し，その翌日より新しい元号が始まることになった．平成最後の日の翌日は新元号元年5月1日になる．

ACM-ICPC OB/OGの会 (Japanese Alumni Group; JAG) が開発するシステムでは，日付が和暦（元号とそれに続く年数によって年を表現する日本の暦）を用いて "平成 y 年 m 月 d 日" という形式でデータベースに保存されている．この保存形式は変更することができないため，JAGは元号が変更されないと仮定して和暦で表した日付をデータベースに保存し，出力の際に日付を正しい元号を用いた形式に変換することにした．

あなたの仕事はJAGのデータベースに保存されている日付を，平成または新元号を用いた日付に変換するプログラムを書くことである．新元号はまだ発表されていないため，"?" を用いて表すことにする．

Input

入力は複数のデータセットからなる．各データセットは次の形式で表される．

g y m d

g は元号を表す文字列であり， g=HEISEI が成り立つ．y, m, d は整数であり，それぞれ年，月，日を表す．1 ≤ y ≤ 100, 1 ≤ m ≤ 12, 1 ≤ d ≤ 31 が成り立つ．

2月30日などの和暦に存在しない日付はデータセットとして与えられない．和暦として正しく変換したときに，平成よりも前の元号を用いる必要がある日付もデータセットとして与えられない．

入力の終わりは '#' 一つのみからなる行であらわされる．データセットの個数は 100 個を超えない．

Output

各データセットについて，変換後の元号，年，月，日を空白で区切って 1 行に出力せよ．変換後の元号が "平成" である場合は "HEISEI" を元号として用い，新元号であれば "?" を用いよ．

通常，元号の第 1 年目は元年と表記するが，本問題の出力ではこの規則を無視し，1 を年として出力せよ．

Sample Input

HEISEI 1 1 8
HEISEI 31 4 30
HEISEI 31 5 1
HEISEI 99 12 31
HEISEI 38 8 30
HEISEI 98 2 22
HEISEI 2 3 26
HEISEI 28 4 23
#

Output for the Sample Input

HEISEI 1 1 8
HEISEI 31 4 30
? 1 5 1
? 69 12 31
? 8 8 30
? 68 2 22
HEISEI 2 3 26
HEISEI 28 4 23

int solution() {
  int y;
  int m;
  int d;
  char g[10];

  while (1) {
    scanf("%s%d%d%d", g, &y, &m, &d);
    if (strcmp(g, "#") == 0) {
      break;
    }
    if ((y == 31 && m > 4) || y > 31) {
      printf("? %d %d %d\n", y - 30, m, d);
    } else {
      printf("%s %d %d %d\n", g, y, m, d);
    }
  }
  return 0;
}

fn solution() {
    loop {
        let reader = std::io::stdin();
        let mut line = String::new();
        let _r = reader.read_line(&mut line);
        let vec: Vec<&str> = line.split_whitespace().collect();
        let mut v = vec[0];
        if v == "#" {
            break;
        } else {
            let mut a: i64 = vec[1].parse().unwrap();
            let b: i64 = vec[2].parse().unwrap();
            let c: i64 = vec[3].parse().unwrap();
            if 31 < a {
                v = "?";
                a -= 30;
            } else if 31 == a && 5 <= b {
                v = "?";
                a -= 30;
            }
            println!("{} {} {} {}", v, a, b, c);
        }
    }
}


Score : <var>500</var> points

Problem Statement

In CODE FESTIVAL XXXX, there are <var>N+1</var> participants from all over the world, including Takahashi.

Takahashi checked and found that the time gap (defined below) between the local times in his city and the <var>i</var>-th person's city was <var>D_i</var> hours.
The time gap between two cities is defined as follows. For two cities A and B, if the local time in city B is <var>d</var> o'clock at the moment when the local time in city A is <var>0</var> o'clock, then the time gap between these two cities is defined to be <var>min(d,24-d)</var> hours.
Here, we are using <var>24</var>-hour notation.
That is, the local time in the <var>i</var>-th person's city is either <var>d</var> o'clock or <var>24-d</var> o'clock at the moment when the local time in Takahashi's city is <var>0</var> o'clock, for example.

Then, for each pair of two people chosen from the <var>N+1</var> people, he wrote out the time gap between their cities. Let the smallest time gap among them be <var>s</var> hours.

Find the maximum possible value of <var>s</var>.

Constraints

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

<var>0 \leq D_i \leq 12</var>

All input values are integers.

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 maximum possible value of <var>s</var>.

Sample Input 1

3
7 12 8

Sample Output 1

4

For example, consider the situation where it is <var>7</var>, <var>12</var> and <var>16</var> o'clock in each person's city at the moment when it is <var>0</var> o'clock in Takahashi's city. In this case, the time gap between the second and third persons' cities is <var>4</var> hours.

Sample Input 2

2
11 11

Sample Output 2

2

Sample Input 3

1
0

Sample Output 3

0

Note that Takahashi himself is also a participant.

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut d: Vec<i32> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();
    d.push(0);
    d.sort();

    let mut unko = Vec::new();
    for i in 0..n + 1 {
        if i % 2 == 0 {
            unko.push(d[i]);
        } else {
            unko.push((24 - d[i]) % 24);
        }
    }
    unko.sort();
    unko.push(24);

    let mut ans = 1 << 30;
    for i in 0..n + 1 {
        ans = min(ans, unko[i + 1] - unko[i]);
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

Given is an integer <var>r</var>.

How many times is the area of a circle of radius <var>r</var> larger than the area of a circle of radius <var>1</var>?

It can be proved that the answer is always an integer under the constraints given.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>r</var>

Output

Print the area of a circle of radius <var>r</var>, divided by the area of a circle of radius <var>1</var>, as an integer.

Sample Input 1

2

Sample Output 1

4

The area of a circle of radius <var>2</var> is <var>4</var> times larger than the area of a circle of radius <var>1</var>.

Note that output must be an integer - for example, 4.0 will not be accepted.

Sample Input 2

100

Sample Output 2

10000

int solution() {
  int r = 0;
  scanf("%d", &r);
  printf("%d\n", r * r);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    let r = buf.trim().parse::<i32>().unwrap();

    println!("{}", r * r);
}