休憩スペース (Refreshment Area)

問題

世界的なプログラミングコンテストが日本で開催されることになり，現在会場の設営が行われている．この会場は南北方向に N マス，東西方向に M マスのマス目状に区切られており，いくつかのマスには競技用の機材が置かれている．

このコンテストでは，選手が競技中に休憩するために，軽食や飲み物などを置いた休憩スペースを 1 箇所会場内に設けることになった．休憩スペースは南北方向または東西方向に連続した D マスでなければならない．ただし，機材の置かれたマス目に休憩スペースを設けることはできない．

会場内に休憩スペースを設ける方法は何通りあるかを求めるプログラムを作成せよ．

入力

入力は 1 + N 行からなる．

1 行目には 3 個の整数 N, M, D (1 ≦ N ≦ 100, 1 ≦ M ≦ 100, 2 ≦ D ≦ 100) が空白を区切りとして書かれており，会場が南北方向に N マス，東西方向に M マスのマス目状に区切られており，休憩スペースが南北方向または東西方向に連続した D マスからなることを表す．

続く N 行にはそれぞれ M 文字からなる文字列が書かれており，会場の情報を表す．
N 行のうちの i 行目の j 文字目 (1 ≦ i ≦ N, 1 ≦ j ≦ M) は，会場のマス目の北から i 行目，西から j 列目のマスの状態を表す '#' または '.' のいずれかの文字である．'#' はそのマスに機材が置かれていることを，'.' はそのマスに機材が置かれていないことを表す．

出力

会場内に休憩スペースを設ける方法は何通りあるかを 1 行で出力せよ．

入出力例

入力例 1

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

出力例 1

12

入力例 2

4 7 5
.#.....
.....##
.......
#......

出力例 2

7

入出力例 1 では，下の図に示すように，休憩スペースを設ける方法は全部で 12 通りある．

情報オリンピック日本委員会作 『第 16 回日本情報オリンピック JOI 2016/2017 予選競技課題』

fn solution() {
    let input = {
        let mut buf = vec![];
        stdin().read_to_end(&mut buf);
        unsafe { String::from_utf8_unchecked(buf) }
    };
    let mut lines = input.splitn(2, '\n');

    let (n, m, d) = {
        let line = lines.next().unwrap();
        let mut iter = line.split(' ').map(|s| s.parse().unwrap());

        (
            iter.next().unwrap(),
            iter.next().unwrap(),
            iter.next().unwrap(),
        )
    };

    if n < d && m < d {
        println!("0");
        return;
    }

    let mut chars = lines.next().unwrap().bytes();

    let mut table = vec![0; m];
    let mut cnt = 0;

    for _ in 0..n {
        let mut x = 0;

        for (ch, y) in chars.by_ref().zip(table.iter_mut()) {
            if ch == b'.' {
                x += 1;
                *y += 1;
            } else {
                if x >= d {
                    cnt += x - d + 1;
                }
                if *y >= d {
                    cnt += *y - d + 1;
                }
                x = 0;
                *y = 0;
            }
        }

        if x >= d {
            cnt += x - d + 1;
        }
    }

    for y in table {
        if y >= d {
            cnt += y - d + 1;
        }
    }

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


You have a large electronic screen which can display up to $$$998244353$$$ decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of $$$7$$$ segments which can be turned on and off to compose different digits. The following picture describes how you can display all $$$10$$$ decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display $$$1$$$, you have to turn on $$$2$$$ segments of the screen, and if you want to display $$$8$$$, all $$$7$$$ segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than $$$n$$$ segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than $$$n$$$ segments.Your program should be able to process $$$t$$$ different test cases.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
    let mut inputs = Vec::new();
    for _ in 0..n {
        let tmp = lines.next().unwrap().unwrap().parse::<usize>().unwrap();
        inputs.push(tmp);
    }
    for mut input in inputs.into_iter() {
        match input % 2 == 1 {
            true => print!("{}", 7),
            false => print!("{}", 1),
        }
        input -= 2 + input % 2;
        while input > 0 {
            input -= 2;
            print!("{}", 1);
        }
        println!();
    }
}


You are given a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.A substring of string $$$s$$$ is a continuous segment of letters from $$$s$$$. For example, "defor" is a substring of "codeforces" and "fors" is not. The length of the substring is the number of letters in it.Let's call some string of length $$$n$$$ diverse if and only if there is no letter to appear strictly more than $$$\frac n 2$$$ times. For example, strings "abc" and "iltlml" are diverse and strings "aab" and "zz" are not.Your task is to find any diverse substring of string $$$s$$$ or report that there is none. Note that it is not required to maximize or minimize the length of the resulting substring.

int solution(void) {
  int ch = 0;
  while (islower(ch) == 0) {
    ch = getchar();
  }
  int prev = ch;
  int next = ch;
  while (prev == next && ch != '\n') {
    prev = next;
    next = ch;
    ch = getchar();
  }
  if (prev != next) {
    puts("YES");
    putchar(prev);
    putchar(next);
  } else {
    puts("NO");
  }
}

fn solution() {
    let mut n = String::new();
    std::io::stdin().read_line(&mut n).expect("");
    let _n: i32 = n.trim().parse().expect("");
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).expect("");
    let s = String::from(s.trim());
    let s: Vec<_> = s.chars().collect();

    let mut l = 0;
    let mut r = 0;
    for i in 0..s.len() {
        let mut cnt = [0; 26];
        for j in i..s.len() {
            cnt[s[j] as usize - 97] += 1;
            let mut ok = true;
            for k in 0..cnt.len() {
                if cnt[k] > (j - i).div_ceil(2) {
                    ok = false;
                    continue;
                }
            }
            if ok {
                l = i;
                r = j;
            }
        }
    }
    if r == 0 {
        println!("NO");
    } else {
        println!("YES");
        for k in l..r + 1 {
            print!("{}", s[k]);
        }
        println!();
    }
}


Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim.The killer starts with two potential victims on his first day, selects one of these two, kills selected victim and replaces him with a new person. He repeats this procedure each day. This way, each day he has two potential victims to choose from. Sherlock knows the initial two potential victims. Also, he knows the murder that happened on a particular day and the new person who replaced this victim.You need to help him get all the pairs of potential victims at each day so that Sherlock can observe some pattern.

int solution() {
  char StrA[11];
  char StrB[11];
  char StrC[11];
  char StrD[11];
  int n;
  scanf("%s %s", StrA, StrB);
  scanf("%d", &n);
  printf("%s %s\n", StrA, StrB);
  while (n--) {
    scanf("%s %s", StrC, StrD);
    if (strcmp(StrC, StrA) == 0) {
      memcpy(StrA, StrD, sizeof(StrA));
    } else if (strcmp(StrC, StrB) == 0) {
      memcpy(StrB, StrD, sizeof(StrB));
    }
    printf("%s %s\n", StrA, StrB);
  }
  return 0;
}

fn solution() {
    let mut names = String::new();
    let mut n = String::new();
    io::stdin().read_line(&mut names).unwrap();
    let mut iter = names.split_whitespace();
    let mut a = iter.next().unwrap().to_string();
    let mut b = iter.next().unwrap().to_string();
    io::stdin().read_line(&mut n).unwrap();
    let n: i32 = n.trim().parse().unwrap();
    println!("{} {}", a, b);
    for _ in 0..n {
        let mut next = String::new();
        io::stdin().read_line(&mut next).unwrap();
        let mut iter = next.split_whitespace();
        let c = iter.next().unwrap();
        let d = iter.next().unwrap().to_string();
        print!("{} ", d);
        if c == a {
            println!("{}", b);
            a = d;
        } else {
            println!("{}", a);
            b = d;
        }
    }
}


Score : <var>200</var> points

Problem Statement

There are <var>N + 1</var> squares arranged in a row, numbered <var>0, 1, ..., N</var> from left to right.

Initially, you are in Square <var>X</var>.
You can freely travel between adjacent squares. Your goal is to reach Square <var>0</var> or Square <var>N</var>.
However, for each <var>i = 1, 2, ..., M</var>, there is a toll gate in Square <var>A_i</var>, and traveling to Square <var>A_i</var> incurs a cost of <var>1</var>.
It is guaranteed that there is no toll gate in Square <var>0</var>, Square <var>X</var> and Square <var>N</var>.

Find the minimum cost incurred before reaching the goal.

Constraints

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

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

<var>1 \leq X \leq N - 1</var>

<var>1 \leq A_1 < A_2 < ... < A_M \leq N</var>

<var>A_i \neq X</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>X</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_M</var>

Output

Print the minimum cost incurred before reaching the goal.

Sample Input 1

5 3 3
1 2 4

Sample Output 1

1

The optimal solution is as follows:

First, travel from Square <var>3</var> to Square <var>4</var>. Here, there is a toll gate in Square <var>4</var>, so the cost of <var>1</var> is incurred.

Then, travel from Square <var>4</var> to Square <var>5</var>. This time, no cost is incurred.

Now, we are in Square <var>5</var> and we have reached the goal.

In this case, the total cost incurred is <var>1</var>.

Sample Input 2

7 3 2
4 5 6

Sample Output 2

0

We may be able to reach the goal at no cost.

Sample Input 3

10 7 5
1 2 3 4 6 8 9

Sample Output 3

3

int solution(void) {

  static int n;
  static int m;
  static int x;
  static int left;
  static int right;
  scanf("%d%d%d", &n, &m, &x);

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

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

    if (a[i] < x) {

      left++;

    } else {

      right++;
    }
  }

  if (left < right) {

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

  } else {

    printf("%d\n", right);
  }

  return 0;
}

fn solution() {
    input! {
        _n: usize,
        m: usize,
        x: u32,
        a: [u32;m]
    }
    let mut l = 0;
    let mut r = 0;
    for i in a {
        if i < x {
            l += 1;
        }
        if i > x {
            r += 1;
        }
    }
    println!("{}", std::cmp::min(l, r));
}


A big football championship will occur soon! $$$n$$$ teams will compete in it, and each pair of teams will play exactly one game against each other.There are two possible outcomes of a game:  the game may result in a tie, then both teams get $$$1$$$ point;  one team might win in a game, then the winning team gets $$$3$$$ points and the losing team gets $$$0$$$ points. The score of a team is the number of points it gained during all games that it played.You are interested in a hypothetical situation when all teams get the same score at the end of the championship. A simple example of that situation is when all games result in ties, but you want to minimize the number of ties as well.Your task is to describe a situation (choose the result of each game) so that all teams get the same score, and the number of ties is the minimum possible.

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;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    i = 1;
    j = 2;
    for (x = 1; x <= n; x++) {
      for (y = x + 1; y <= n; y++) {
        if (!(n & 1) && x == i && j == y) {
          putchar('0');
          putchar(' ');
          i += 2;
          j += 2;
        } else {
          if (!((x + y) & 1)) {
            putchar('-');
          }
          putchar('1');
          putchar(' ');
        }
      }
    }

    puts("");
  }
  return 0;
}

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: i32 = sc.next();
        let mut tot = n * (n - 1) / 2;
        let mut result: HashMap<(i32, i32), i32> = HashMap::new();
        let mut diff = 1;
        while tot >= n {
            for i in 0..n {
                result.insert((i, (i + diff) % n), i);
            }
            tot -= n;
            diff += 1;
        }
        for i in 0..n {
            for j in i + 1..n {
                let winner = if result.contains_key(&(i, j)) {
                    result.get(&(i, j))
                } else {
                    result.get(&(j, i))
                };
                if let Some(&winner) = winner {
                    write!(out, "{} ", if winner == i { 1 } else { -1 }).unwrap();
                } else {
                    write!(out, "0 ").unwrap();
                }
            }
        }
        writeln!(out).unwrap();
    }
}


You are given an array of integers $$$a$$$ of length $$$n$$$. The elements of the array can be either different or the same. Each element of the array is colored either blue or red. There are no unpainted elements in the array. One of the two operations described below can be applied to an array in a single step:  either you can select any blue element and decrease its value by $$$1$$$;  or you can select any red element and increase its value by $$$1$$$. Situations in which there are no elements of some color at all are also possible. For example, if the whole array is colored blue or red, one of the operations becomes unavailable.Determine whether it is possible to make $$$0$$$ or more steps such that the resulting array is a permutation of numbers from $$$1$$$ to $$$n$$$?In other words, check whether there exists a sequence of steps (possibly empty) such that after applying it, the array $$$a$$$ contains in some order all numbers from $$$1$$$ to $$$n$$$ (inclusive), each exactly once.

int solution() {
  int t;
  scanf("%d", &t);
  int n;
  for (int i = 0; i < t; i++) {
    scanf("%d", &n);
    long long arr[n];
    char str[n];
    int inc[n + 1];
    int dec[n + 1];
    for (int j = 0; j < n; j++) {
      scanf("%lld", &arr[j]);
      inc[j] = 0;
      dec[j] = 0;
    }
    dec[n] = 0;
    inc[n] = 0;
    scanf("%s", str);
    int flag = 0;
    for (int j = 0; j < n; j++) {
      if (arr[j] <= 0 && str[j] == 'B') {
        flag = 1;
        break;
      }
      if (arr[j] <= 0 && str[j] == 'R') {
        inc[1]++;
      } else if (arr[j] > n && str[j] == 'R') {
        flag = 1;
        break;
      } else if (arr[j] > n && str[j] == 'B') {

        dec[n]++;

      } else {
        if (str[j] == 'R') {
          inc[arr[j]]++;
        } else {
          dec[arr[j]]++;
        }
      }
    }

    if (flag == 1) {
      printf("NO\n");
    } else {
      int p = n;
      long long suminc = 0;
      long long sumdec = 0;
      int q = 1;
      for (int j = n; j > 0; j--) {
        suminc += inc[j];
        if (inc[j] != 0 && suminc > n - j + 1) {
          flag = 1;

          break;
        }
        if (inc[j] != 0) {
          p = p - inc[j];
        }
      }

      for (int j = 1; j <= n; j++) {
        sumdec += dec[j];
        if (dec[j] != 0 && sumdec > j) {
          flag = 1;
          break;
        }

        if (dec[j] != 0) {
          q = q + dec[j];
        }
      }

      if (flag == 1) {
        printf("NO\n");

      } else {
        if (p == q - 1 || p == 0 || q == n + 1) {
          printf("YES\n");
        } else {

          printf("NO\n");
        }
      }
    }
  }
}

fn solution() -> io::Result<()> {
    let mut s = String::new();
    io::stdin().read_to_string(&mut s)?;
    let mut it = s.split_whitespace().map(|s| s.to_string());
    let t: usize = it.next().unwrap().parse().unwrap();
    let mut out = String::new();
    for _case in 1..=t {
        let n: usize = it.next().unwrap().parse().unwrap();
        let mut a = Vec::with_capacity(n);
        for _ in 0..n {
            let x: i32 = it.next().unwrap().parse().unwrap();
            a.push(x);
        }
        let colors: String = it.next().unwrap().parse().unwrap();
        let mut blue = vec![];
        let mut red = vec![];
        for (c, x) in colors.bytes().zip(a.into_iter()) {
            if c == b'R' {
                red.push(x);
            } else {
                blue.push(x);
            }
        }
        red.sort();
        blue.sort();
        let _perm = vec![0; n];
        let mut ans = "YES";
        let mut right = n as i32;
        for &v in red.iter().rev() {
            if v <= right {
                right -= 1;
            } else {
                ans = "NO";
            }
        }
        let mut left = 1;
        for &v in blue.iter() {
            if v >= left {
                left += 1;
            } else {
                ans = "NO";
            }
        }
        let ans = format!("{}\n", ans);
        out.push_str(ans.as_str());
    }
    print!("{}", out);
    Ok(())
}


Given a sequence $$$a_1, a_2, \ldots, a_n$$$, find the minimum number of elements to remove from the sequence such that after the removal, the sum of every $$$2$$$ consecutive elements is even.

int solution() {
  int num_case = 0;
  scanf("%d", &num_case);

  int nums = 0;
  int number = 0;
  int odd_cnt = 0;
  for (int i = 0; i < num_case; i++) {
    scanf("%d", &nums);
    for (int j = 0; j < nums; j++) {
      scanf("%d", &number);
      if (number % 2) {
        odd_cnt++;
      }
    }
    if (odd_cnt < nums - odd_cnt) {
      printf("%d\n", odd_cnt);
    } else {
      printf("%d\n", nums - odd_cnt);
    }
    odd_cnt = 0;
  }
  return 0;
}

fn solution() {
    let stdin = stdin();

    let mut count = String::new();

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

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

        data_read.clear();

        stdin.read_line(&mut data_read).unwrap();

        let mut counts = [0, 0];

        for i in data_read.trim().split(' ') {
            let value: usize = i.parse().unwrap();
            counts[value % 2] += 1;
        }
        println!(
            "{}",
            if counts[0] > counts[1] {
                counts[1]
            } else {
                counts[0]
            }
        );
    }
}


Score : <var>100</var> points

Problem Statement

We have a <var>3×3</var> square grid, where each square contains a lowercase English letters.
The letter in the square at the <var>i</var>-th row from the top and <var>j</var>-th column from the left is <var>c_{ij}</var>.

Print the string of length <var>3</var> that can be obtained by concatenating the letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Constraints

Input consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

<var>c_{11}c_{12}c_{13}</var>
<var>c_{21}c_{22}c_{23}</var>
<var>c_{31}c_{32}c_{33}</var>

Output

Print the string of length <var>3</var> that can be obtained by concatenating the letters on the diagonal connecting the top-left and bottom-right corner of the grid, from the top-left to bottom-right.

Sample Input 1

ant
obe
rec

Sample Output 1

abc

The letters in the squares on the diagonal connecting the top-left and bottom-right corner of the grid are a, b and c from top-right to bottom-left. Concatenate these letters and print abc.

Sample Input 2

edu
cat
ion

Sample Output 2

ean

fn solution() {
    for i in 0..3 {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let v: Vec<char> = s.trim().chars().collect();
        print!("{}", v[i]);
    }
    println!();
}


A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell.  Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).unwrap();
    let mut input = input.split_ascii_whitespace().flat_map(str::parse);
    let t = input.next().unwrap();
    let mut output = String::new();
    for _ in 0..t {
        let n = input.next().unwrap();
        let m = input.next().unwrap();
        let mut rb = input.next().unwrap();
        let mut cb = input.next().unwrap();
        let rd = input.next().unwrap();
        let cd = input.next().unwrap();
        let mut r_defl = false;
        let mut c_defl = false;
        let mut t = 0;
        while rb != rd && cb != cd {
            if rb == 1 {
                r_defl = false;
            } else if rb == n {
                r_defl = true;
            }
            if cb == 1 {
                c_defl = false;
            } else if cb == m {
                c_defl = true;
            }
            if r_defl {
                rb -= 1;
            } else {
                rb += 1;
            }
            if c_defl {
                cb -= 1;
            } else {
                cb += 1;
            }
            t += 1;
        }
        writeln!(output, "{}", t).unwrap();
    }
    print!("{}", output);
}


Score : <var>600</var> points

Problem Statement

Let us consider the following operations on a string consisting of A and B:

Select a character in a string. If it is A, replace it with BB. If it is B, replace with AA.

Select a substring that is equal to either AAA or BBB, and delete it from the string.

For example, if the first operation is performed on ABA and the first character is selected, the string becomes BBBA.
If the second operation is performed on BBBAAAA and the fourth through sixth characters are selected, the string becomes BBBA.

These operations can be performed any number of times, in any order.

You are given two string <var>S</var> and <var>T</var>, and <var>q</var> queries <var>a_i, b_i, c_i, d_i</var>.
For each query, determine whether <var>S_{a_i} S_{{a_i}+1} ... S_{b_i}</var>, a substring of <var>S</var>, can be made into <var>T_{c_i} T_{{c_i}+1} ... T_{d_i}</var>, a substring of <var>T</var>.

Constraints

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

<var>S</var> and <var>T</var> consist of letters A and B.

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

<var>1 \leq a_i \leq b_i \leq |S|</var>

<var>1 \leq c_i \leq d_i \leq |T|</var>

Input

Input is given from Standard Input in the following format:

<var>S</var>
<var>T</var>
<var>q</var>
<var>a_1</var> <var>b_1</var> <var>c_1</var> <var>d_1</var>
<var>...</var>
<var>a_q</var> <var>b_q</var> <var>c_q</var> <var>d_q</var>

Output

Print <var>q</var> lines. The <var>i</var>-th line should contain the response to the <var>i</var>-th query. If <var>S_{a_i} S_{{a_i}+1} ... S_{b_i}</var> can be made into <var>T_{c_i} T_{{c_i}+1} ... T_{d_i}</var>, print YES. Otherwise, print NO.

Sample Input 1

BBBAAAABA
BBBBA
4
7 9 2 5
7 9 1 4
1 7 2 5
1 7 2 4

Sample Output 1

YES
NO
YES
NO

The first query asks whether the string ABA can be made into BBBA.
As explained in the problem statement, it can be done by the first operation.

The second query asks whether ABA can be made into BBBB, and the fourth query asks whether BBBAAAA can be made into BBB.
Neither is possible.

The third query asks whether the string BBBAAAA can be made into BBBA.
As explained in the problem statement, it can be done by the second operation.

Sample Input 2

AAAAABBBBAAABBBBAAAA
BBBBAAABBBBBBAAAAABB
10
2 15 2 13
2 13 6 16
1 13 2 20
4 20 3 20
1 18 9 19
2 14 1 11
3 20 3 15
6 16 1 17
4 18 8 20
7 20 3 14

Sample Output 2

YES
YES
YES
YES
YES
YES
NO
NO
NO
NO

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

    let mut acc_S = vec![0; S.len() + 1];
    let mut acc_T = vec![0; T.len() + 1];
    for i in 0..(S.len()) {
        acc_S[i + 1] = if S[i] == 'A' { acc_S[i] + 1 } else { acc_S[i] };
    }
    for i in 0..(T.len()) {
        acc_T[i + 1] += if T[i] == 'A' { acc_T[i] + 1 } else { acc_T[i] };
    }
    let ans = (0..q)
        .map(|i| {
            let a_s = (acc_S[b[i]] - acc_S[a[i] - 1]) as i64;
            let b_s = ((b[i] - a[i] + 1) as i64) - a_s;
            let a_t = (acc_T[d[i]] - acc_T[c[i] - 1]) as i64;
            let b_t = ((d[i] - c[i] + 1) as i64) - a_t;
            if b_t % 3 == ((b_s + (a_t - a_s)) % 3 + 3) % 3 {
                "YES"
            } else {
                "NO"
            }
        })
        .collect::<Vec<_>>()
        .join("\n");

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


Polycarp and his friends want to visit a new restaurant. The restaurant has $$$n$$$ tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from $$$1$$$ to $$$n$$$ in the order from left to right. The state of the restaurant is described by a string of length $$$n$$$ which contains characters "1" (the table is occupied) and "0" (the table is empty).Restaurant rules prohibit people to sit at a distance of $$$k$$$ or less from each other. That is, if a person sits at the table number $$$i$$$, then all tables with numbers from $$$i-k$$$ to $$$i+k$$$ (except for the $$$i$$$-th) should be free. In other words, the absolute difference of the numbers of any two occupied tables must be strictly greater than $$$k$$$.For example, if $$$n=8$$$ and $$$k=2$$$, then:  strings "10010001", "10000010", "00000000", "00100000" satisfy the rules of the restaurant;  strings "10100100", "10011001", "11111111" do not satisfy to the rules of the restaurant, since each of them has a pair of "1" with a distance less than or equal to $$$k=2$$$. In particular, if the state of the restaurant is described by a string without "1" or a string with one "1", then the requirement of the restaurant is satisfied.You are given a binary string $$$s$$$ that describes the current state of the restaurant. It is guaranteed that the rules of the restaurant are satisfied for the string $$$s$$$.Find the maximum number of free tables that you can occupy so as not to violate the rules of the restaurant. Formally, what is the maximum number of "0" that can be replaced by "1" such that the requirement will still be satisfied?For example, if $$$n=6$$$, $$$k=1$$$, $$$s=$$$ "100010", then the answer to the problem will be $$$1$$$, since only the table at position $$$3$$$ can be occupied such that the rules are still satisfied.

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

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

    for _ in 0..t {
        let (n, k): (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(),
            )
        };

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

        let mut ans = 0;
        let mut count = 0;
        let mut i = 0;
        while i < n {
            if s[i] == '1' {
                count = k;
                i += 1;
                continue;
            } else if count > 0 {
                count -= 1;
                i += 1;
                continue;
            }

            let mut j = 1;
            while j <= k && i + j < n {
                if s[i + j] == '1' {
                    break;
                }
                j += 1;
            }
            if j > k || i + j == n {
                ans += 1;
            }

            i += j;
        }

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


Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $$$n$$$ elements. The $$$i$$$-th element is $$$a_i$$$ ($$$i$$$ = $$$1, 2, \ldots, n$$$). He gradually takes the first two leftmost elements from the deque (let's call them $$$A$$$ and $$$B$$$, respectively), and then does the following: if $$$A > B$$$, he writes $$$A$$$ to the beginning and writes $$$B$$$ to the end of the deque, otherwise, he writes to the beginning $$$B$$$, and $$$A$$$ writes to the end of the deque. We call this sequence of actions an operation.For example, if deque was $$$[2, 3, 4, 5, 1]$$$, on the operation he will write $$$B=3$$$ to the beginning and $$$A=2$$$ to the end, so he will get $$$[3, 4, 5, 1, 2]$$$.The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $$$q$$$ queries. Each query consists of the singular number $$$m_j$$$ $$$(j = 1, 2, \ldots, q)$$$. It is required for each query to answer which two elements he will pull out on the $$$m_j$$$-th operation.Note that the queries are independent and for each query the numbers $$$A$$$ and $$$B$$$ should be printed in the order in which they will be pulled out of the deque.Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.

int solution() {
  int n;
  int q;
  scanf("%d %d", &n, &q);
  int a[n];
  int b[n];
  int c[n];

  int A[n];
  int B[n];
  for (int i = 0; i < n; i++) {
    scanf("%d ", &a[i]);
  }
  for (int i = 1; i < n; i++) {
    c[i] = a[0];
    if (a[0] > a[i]) {
      b[i] = a[i];
    } else {
      b[i] = a[0];
      a[0] = a[i];
    }
  }
  b[0] = a[0];

  while (q--) {
    long long int m;
    scanf("%lld", &m);
    if (m < n) {
      printf("%d %d\n", c[m], a[m]);
    } else {
      int t = (m - n) % (n - 1);
      printf("%d %d\n", b[0], b[t + 1]);
    }
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut out = io::BufWriter::new(stdout.lock());
    let line = stdin.lock().lines().next().unwrap().unwrap();
    let nq: Vec<i32> = line.split(" ").map(|i| i.parse().unwrap()).collect();
    let n = nq[0];
    let q = nq[1];

    let line = stdin.lock().lines().next().unwrap().unwrap();
    let mut a: Vec<i32> = line.split(" ").map(|i| i.parse().unwrap()).collect();

    assert_eq!(n, a.len() as i32);

    let mut ans: Vec<(i32, i32)> = vec![];
    for i in 0..2 * n as usize {
        let mut A = a[i];
        let mut B = a[i + 1];
        ans.push((A, B));
        if A < B {
            mem::swap(&mut A, &mut B);
        }
        a[i + 1] = A;
        a.push(B);
    }

    for _ in 0..q as usize {
        let line = stdin.lock().lines().next().unwrap().unwrap();
        let mj: i64 = line.parse().unwrap();
        let mj = mj - 1;
        if mj < (n - 1) as i64 {
            writeln!(out, "{} {}", ans[mj as usize].0, ans[mj as usize].1).ok();
        } else {
            let m = mj % (n - 1) as i64 + (n - 1) as i64;
            writeln!(out, "{} {}", ans[m as usize].0, ans[m as usize].1).ok();
        }
    }
}


We just discovered a new data structure in our research group: a suffix three!It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.It's super simple, 100% accurate, and doesn't involve advanced machine learning algorithms.Let us tell you how it works.  If a sentence ends with "po" the language is Filipino.  If a sentence ends with "desu" or "masu" the language is Japanese.  If a sentence ends with "mnida" the language is Korean. Given this, we need you to implement a suffix three that can differentiate Filipino, Japanese, and Korean.Oh, did I say three suffixes? I meant four.

fn solution() -> io::Result<()> {
    let mut buffer = String::new();
    let input = stdin();
    input.read_line(&mut buffer)?;
    let x: u32 = buffer.trim().parse().expect("Not int");
    for _ in 0..x {
        buffer = String::new();
        input.read_line(&mut buffer)?;
        if buffer.trim().ends_with("po") {
            println!("FILIPINO");
        } else if buffer.trim().ends_with("mnida") {
            println!("KOREAN");
        } else {
            println!("JAPANESE");
        }
    }
    Ok(())
}


A number $$$a_2$$$ is said to be the arithmetic mean of two numbers $$$a_1$$$ and $$$a_3$$$, if the following condition holds: $$$a_1 + a_3 = 2\cdot a_2$$$. We define an arithmetic mean deviation of three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ as follows: $$$d(a_1, a_2, a_3) = |a_1 + a_3 - 2 \cdot a_2|$$$.Arithmetic means a lot to Jeevan. He has three numbers $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$ and he wants to minimize the arithmetic mean deviation $$$d(a_1, a_2, a_3)$$$. To do so, he can perform the following operation any number of times (possibly zero):  Choose $$$i, j$$$ from $$$\{1, 2, 3\}$$$ such that $$$i \ne j$$$ and increment $$$a_i$$$ by $$$1$$$ and decrement $$$a_j$$$ by $$$1$$$ Help Jeevan find out the minimum value of $$$d(a_1, a_2, a_3)$$$ that can be obtained after applying the operation any number of times.

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let t = u64::from_str(s.trim_end()).unwrap();
    for _ in 0..t {
        s.clear();
        std::io::stdin().read_line(&mut s).unwrap();
        println!(
            "{}",
            if s.split(' ')
                .map(|it| i64::from_str(it.trim()).unwrap() % 3)
                .sum::<i64>()
                % 3
                == 0
            {
                0
            } else {
                1
            }
        );
    }
}


Score : <var>600</var> points

Problem Statement

There are <var>N</var> piles of stones. The <var>i</var>-th pile has <var>A_i</var> stones.

Aoki and Takahashi are about to use them to play the following game:

Starting with Aoki, the two players alternately do the following operation:

Operation: Choose one pile of stones, and remove one or more stones from it.

When a player is unable to do the operation, he loses, and the other player wins.

When the two players play optimally, there are two possibilities in this game: the player who moves first always wins, or the player who moves second always wins, only depending on the initial number of stones in each pile.

In such a situation, Takahashi, the second player to act, is trying to guarantee his win by moving at least zero and at most <var>(A_1 - 1)</var> stones from the <var>1</var>-st pile to the <var>2</var>-nd pile before the game begins.

If this is possible, print the minimum number of stones to move to guarantee his victory; otherwise, print -1 instead.

Constraints

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

<var>1 \leq A_i \leq 10^{12}</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_1</var> <var>\ldots</var> <var>A_N</var>

Output

Print the minimum number of stones to move to guarantee Takahashi's win; otherwise, print -1 instead.

Sample Input 1

2
5 3

Sample Output 1

1

Without moving stones, if Aoki first removes <var>2</var> stones from the <var>1</var>-st pile, Takahashi cannot win in any way.

If Takahashi moves <var>1</var> stone from the <var>1</var>-st pile to the <var>2</var>-nd before the game begins so that both piles have <var>4</var> stones, Takahashi can always win by properly choosing his actions.

Sample Input 2

2
3 5

Sample Output 2

-1

It is not allowed to move stones from the <var>2</var>-nd pile to the <var>1</var>-st.

Sample Input 3

3
1 1 2

Sample Output 3

-1

It is not allowed to move all stones from the <var>1</var>-st pile.

Sample Input 4

8
10 9 8 7 6 5 4 3

Sample Output 4

3

Sample Input 5

3
4294967297 8589934593 12884901890

Sample Output 5

1

Watch out for overflows.

int solution() {
  int i;
  int N;
  long long A[301];
  long long xor = 0;
  scanf("%d", &N);
  for (i = 1; i <= N; i++) {
    scanf("%lld", &(A[i]));
    xor ^= A[i];
  }
  if (xor== 0) {
    printf("0\n");
    fflush(stdout);
    return 0;
  }
  xor ^= A[1] ^ A[2];

  long long bit[41];
  long long x = A[1] + A[2];
  long long y = x - xor;
  for (i = 1, bit[0] = 1; i <= 40; i++) {
    bit[i] = bit[i - 1] << 1;
  }
  if (y < 0 || x < y || y % 2 == 1 || y / 2 > A[1]) {
    printf("-1\n");
    fflush(stdout);
    return 0;
  }
  y /= 2;

  int flag[41];
  long long a = y;
  long long b = y;
  long long c = y << 1;
  for (i = 0; i <= 40; i++) {
    flag[i] = ((y & bit[i]) > 0) ? 1 : 0;
  }
  for (i = 0; i <= 40; i++) {
    if ((x & bit[i]) == (c & bit[i])) {
      continue;
    }
    if (flag[i] == 1) {
      break;
    }
    flag[i] = -1;
    c += bit[i];
  }
  if (c != x) {
    printf("-1\n");
    fflush(stdout);
    return 0;
  }

  for (i = 40; i >= 0; i--) {
    if (flag[i] == -1 && a + bit[i] <= A[1]) {
      a += bit[i];
    }
  }
  if (a > 0) {
    printf("%lld\n", A[1] - a);
  } else {
    printf("-1\n");
  }
  fflush(stdout);
  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<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 p = a[0] + a[1];
    let q = (2..n).fold(0, |sum, i| sum ^ a[i]);
    if p < q || (p - q) % 2 == 1 {
        println!("-1");
        return;
    }
    let mut p = (p - q) >> 1;
    if (p & q) > 0 || p > a[0] {
        println!("-1");
        return;
    }

    for i in (0..40).rev() {
        let b = 1 << i;
        if q & b > 0 && p + b <= a[0] {
            p += b;
        }
    }

    let ans = a[0] - p;
    if ans == a[0] {
        println!("-1");
    } else {
        println!("{}", ans);
    }
}


int solution(const int arr[], int x, int n) {

  int fibMMm2 = 0;
  int fibMMm1 = 1;
  int fibM = fibMMm2 + fibMMm1;

  while (fibM < n) {
    fibMMm2 = fibMMm1;
    fibMMm1 = fibM;
    fibM = fibMMm2 + fibMMm1;
  }

  int offset = -1;

  while (fibM > 1) {

    int i = ((offset + fibMMm2) < (n - 1)) ? (offset + fibMMm2) : (n - 1);

    if (arr[i] < x) {
      fibM = fibMMm1;
      fibMMm1 = fibMMm2;
      fibMMm2 = fibM - fibMMm1;
      offset = i;
    }

    else if (arr[i] > x) {
      fibM = fibMMm2;
      fibMMm1 = fibMMm1 - fibMMm2;
      fibMMm2 = fibM - fibMMm1;
    }

    else {
      return i;
    }
  }

  if (fibMMm1 && arr[offset + 1] == x) {
    return offset + 1;
  }

  return -1;
}

fn solution<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
    let len = arr.len();
    if len == 0 {
        return None;
    }
    let mut start = -1;

    let mut f0 = 0;
    let mut f1 = 1;
    let mut f2 = 1;
    while f2 < len {
        f0 = f1;
        f1 = f2;
        f2 = f0 + f1;
    }
    while f2 > 1 {
        let index = min((f0 as isize + start) as usize, len - 1);
        match item.cmp(&arr[index]) {
            Ordering::Less => {
                f2 = f0;
                f1 -= f0;
                f0 = f2 - f1;
            }
            Ordering::Equal => return Some(index),
            Ordering::Greater => {
                f2 = f1;
                f1 = f0;
                f0 = f2 - f1;
                start = index as isize;
            }
        }
    }
    if (f1 != 0) && (&arr[len - 1] == item) {
        return Some(len - 1);
    }
    None
}


You are given two strings $$$s$$$ and $$$t$$$. The string $$$s$$$ consists of lowercase Latin letters and at most one wildcard character '*', the string $$$t$$$ consists only of lowercase Latin letters. The length of the string $$$s$$$ equals $$$n$$$, the length of the string $$$t$$$ equals $$$m$$$.The wildcard character '*' in the string $$$s$$$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $$$s$$$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $$$s$$$ to obtain a string $$$t$$$, then the string $$$t$$$ matches the pattern $$$s$$$.For example, if $$$s=$$$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".If the given string $$$t$$$ matches the given string $$$s$$$, print "YES", otherwise print "NO".

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 m = get!(usize);
    let s = get().as_bytes();
    let t = get().as_bytes();

    let mut ok = true;

    if s.contains(&b'*') && n <= m + 1 {
        for i in 0..n {
            if s[i] == b'*' {
                break;
            }
            if s[i] != t[i] {
                ok = false;
                break;
            }
        }
        for i in 0..n {
            let j = (m - 1) - i;
            let i = (n - 1) - i;
            if s[i] == b'*' {
                break;
            }
            if s[i] != t[j] {
                ok = false;
                break;
            }
        }
    } else {
        ok = s == t;
    }

    if ok {
        println!("YES");
    } else {
        println!("NO");
    }
}


You're given an array $$$b$$$ of length $$$n$$$. Let's define another array $$$a$$$, also of length $$$n$$$, for which $$$a_i = 2^{b_i}$$$ ($$$1 \leq i \leq n$$$). Valerii says that every two non-intersecting subarrays of $$$a$$$ have different sums of elements. You want to determine if he is wrong. More formally, you need to determine if there exist four integers $$$l_1,r_1,l_2,r_2$$$ that satisfy the following conditions:   $$$1 \leq l_1 \leq r_1 \lt l_2 \leq r_2 \leq n$$$;  $$$a_{l_1}+a_{l_1+1}+\ldots+a_{r_1-1}+a_{r_1} = a_{l_2}+a_{l_2+1}+\ldots+a_{r_2-1}+a_{r_2}$$$. If such four integers exist, you will prove Valerii wrong. Do they exist?An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    int arr[n];
    _Bool ok = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      for (int j = 0; j < i; j++) {
        if (arr[j] == arr[i] && ok == 0) {
          printf("YES\n");
          ok = 1;
        }
      }
    }
    if (ok == 0) {
      printf("NO\n");
    }
  }
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let t: i32 = s.trim().parse().unwrap();
    for _ in 0..t {
        std::io::stdin().read_line(&mut s).unwrap();
        s.clear();
        let mut map = std::collections::HashSet::new();
        std::io::stdin().read_line(&mut s).unwrap();

        let mut result = || {
            for i in s.split_whitespace() {
                if map.contains(i) {
                    return "YES";
                } else {
                    map.insert(i);
                }
            }
            "NO"
        };
        println!("{}", result());
    }
}


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You are given an integer $$$n$$$. Your goal is to construct and print exactly $$$n$$$ different regular bracket sequences of length $$$2n$$$.

fn solution() {
    let mut input = String::new();
    let stdin = io::stdin();
    stdin.read_line(&mut input).unwrap();
    let mut t: i32 = input.trim().parse().unwrap();
    while t > 0 {
        let mut input = String::new();
        stdin.read_line(&mut input).unwrap();
        let n: usize = input.trim().parse().unwrap();
        for i in 1..n + 1 {
            print!("{}", std::iter::repeat_n("(", i).collect::<String>());
            print!("{}", std::iter::repeat_n(")", i).collect::<String>());
            print!("{}", std::iter::repeat_n("(", n - i).collect::<String>());
            print!("{}", std::iter::repeat_n(")", n - i).collect::<String>());
            println!();
        }
        t -= 1;
    }
}


Score : <var>300</var> points

Problem Statement

Given is a string <var>S</var> of length <var>N-1</var>.
Each character in <var>S</var> is < or >.

A sequence of <var>N</var> non-negative integers, <var>a_1,a_2,\cdots,a_N</var>, is said to be good when the following condition is satisfied for all <var>i</var> (<var>1 \leq i \leq N-1</var>):

If <var>S_i=</var> <: <var>a_i<a_{i+1}</var>

If <var>S_i=</var> >: <var>a_i>a_{i+1}</var>

Find the minimum possible sum of the elements of a good sequence of <var>N</var> non-negative integers.

Constraints

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

<var>S</var> is a string of length <var>N-1</var> consisting of < and >.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Find the minimum possible sum of the elements of a good sequence of <var>N</var> non-negative integers.

Sample Input 1

<>>

Sample Output 1

3

<var>a=(0,2,1,0)</var> is a good sequence whose sum is <var>3</var>.
There is no good sequence whose sum is less than <var>3</var>.

Sample Input 2

<>>><<><<<<<>>><

Sample Output 2

28

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let s = buf.chars().collect::<Vec<char>>();
    let n = buf.len() + 1;
    let mut vs: Vec<i64> = vec![0; n];

    for i in 0..n - 1 {
        if s[i] == '<' {
            vs[i + 1] = vs[i] + 1;
        }
    }

    for i in 0..n - 1 {
        let j = n - 2 - i;
        if s[j] == '>' {
            vs[j] = max(vs[j + 1] + 1, vs[j]);
        }
    }
    println!("{}", vs.iter().fold(0, |sum, elem| sum + *elem));
}


Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty — a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty d on Decoforces is as hard as the problem with difficulty d on any other judge). Makes has chosen n problems to solve on Decoforces with difficulties a1, a2, ..., an. He can solve these problems in arbitrary order. Though he can solve problem i with difficulty ai only if he had already solved some problem with difficulty  (no matter on what online judge was it).Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty k.With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list. For every positive integer y there exist some problem with difficulty y on at least one judge besides Decoforces.Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.

int solution(int argc, char const *argv[]) {
  int n;
  int k;
  int i;
  int j;
  int ar[1001];
  int max = 0;
  int c = 0;
  int t;
  scanf("%d %d", &n, &k);
  for (int i = 0; i < n; ++i) {
    scanf("%d", &ar[i]);
  }
  c = 1;
  while (c != 0) {
    c = 0;
    for (i = 1; i < n; i++) {
      if (ar[i - 1] > ar[i]) {
        t = ar[i];
        ar[i] = ar[i - 1];
        ar[i - 1] = t;
        c++;
      }
    }
  }
  c = 0;
  for (int i = 0; i < n; ++i) {
    if (ar[i] <= k * 2) {

      if (ar[i] > k) {
        k = ar[i];
      }
      continue;
    }
    while (k * 2 < ar[i]) {
      k = k * 2;

      c++;
    }
    if (ar[i] > k) {
      k = ar[i];
    }
  }
  printf("%d\n", c);

  return 0;
}

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

    std::io::stdin().read_line(&mut input).unwrap();

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

    let (_n, mut k) = (it.next().unwrap(), it.next().unwrap());

    let mut input = String::new();

    std::io::stdin().read_line(&mut input).unwrap();

    let a: Vec<u32> = input
        .split_whitespace()
        .map(|s| s.parse().unwrap())
        .collect();

    let max = a.iter().max().unwrap();
    let mut ans = 0;

    while k * 2 < *max {
        let o_max = a.iter().filter(|&p| *p <= k * 2).max();
        match o_max {
            Some(p) if *p > k => k = *p,
            _ => {
                ans += 1;
                k *= 2;
            }
        }
    }

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


You are given an integer $$$x$$$. Can you make $$$x$$$ by summing up some number of $$$11, 111, 1111, 11111, \ldots$$$? (You can use any number among them any number of times).For instance,   $$$33=11+11+11$$$  $$$144=111+11+11+11$$$

int solution() {
  int numInputs = 0;
  scanf("%d", &numInputs);
  for (int i = 0; i < numInputs; i++) {
    int num = 0;
    scanf("%d", &num);
    int r = num % 11;
    if (r * 111 <= num) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

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

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

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

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

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

        let a = x / 111;
        let b = x % 11;

        let ans = if b <= a { "YES" } else { "NO" };

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


Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:  First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.  Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!

int solution() {
  int clocks;
  scanf("%d", &clocks);
  int A[clocks][2];
  int *Hashx = (int *)calloc(sizeof(int), 101);
  int *Hashy = (int *)calloc(sizeof(int), 101);
  for (int i = 0; i < clocks; i++) {
    for (int j = 0; j < 2; j++) {
      scanf("%d", &A[i][j]);
      if (j == 0) {
        Hashx[A[i][j]]++;
      } else {
        Hashy[A[i][j]]++;
      }
    }
  }
  int countx = 0;
  int county = 0;
  for (int i = 0; i < 101; i++) {
    if (Hashx[i] != 0) {
      countx++;
    }
  }
  for (int i = 0; i < 101; i++) {
    if (Hashy[i] != 0) {
      county++;
    }
  }
  if (countx < county) {
    printf("%d", countx);
  } else {
    printf("%d", county);
  }
  return 0;
}

fn solution() {
    let n = {
        let mut buf = String::new();
        stdin().read_line(&mut buf).expect("Failed to read line 1");
        buf.trim().parse::<i32>().unwrap()
    };
    let mut rows: HashSet<i32> = HashSet::new();
    let mut cols: HashSet<i32> = HashSet::new();
    for _ in 0..n {
        let mut buf = String::new();
        stdin().read_line(&mut buf).expect("Failed to read line 1");
        let point: Vec<i32> = buf
            .trim()
            .split_ascii_whitespace()
            .map(|c| c.parse().unwrap())
            .collect();
        rows.insert(point[0]);
        cols.insert(point[1]);
    }
    println!("{}", min(rows.len(), cols.len()));
}


Score : <var>300</var> points

Problem Statement

We have <var>N</var> switches with "on" and "off" state, and <var>M</var> bulbs. The switches are numbered <var>1</var> to <var>N</var>, and the bulbs are numbered <var>1</var> to <var>M</var>.

Bulb <var>i</var> is connected to <var>k_i</var> switches: Switch <var>s_{i1}</var>, <var>s_{i2}</var>, <var>...</var>, and <var>s_{ik_i}</var>. It is lighted when the number of switches that are "on" among these switches is congruent to <var>p_i</var> modulo <var>2</var>.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

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

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

<var>1 \leq s_{ij} \leq N</var>

<var>s_{ia} \neq s_{ib} (a \neq b)</var>

<var>p_i</var> is <var>0</var> or <var>1</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_1</var> <var>s_{11}</var> <var>s_{12}</var> <var>...</var> <var>s_{1k_1}</var>
<var>:</var>
<var>k_M</var> <var>s_{M1}</var> <var>s_{M2}</var> <var>...</var> <var>s_{Mk_M}</var>
<var>p_1</var> <var>p_2</var> <var>...</var> <var>p_M</var>

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb <var>1</var> is lighted when there is an even number of switches that are "on" among the following: Switch <var>1</var> and <var>2</var>.

Bulb <var>2</var> is lighted when there is an odd number of switches that are "on" among the following: Switch <var>2</var>.

There are four possible combinations of states of (Switch <var>1</var>, Switch <var>2</var>): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print <var>1</var>.

Sample Input 2

2 3
2 1 2
1 1
1 2
0 0 1

Sample Output 2

0

Bulb <var>1</var> is lighted when there is an even number of switches that are "on" among the following: Switch <var>1</var> and <var>2</var>.

Bulb <var>2</var> is lighted when there is an even number of switches that are "on" among the following: Switch <var>1</var>.

Bulb <var>3</var> is lighted when there is an odd number of switches that are "on" among the following: Switch <var>2</var>.

Switch <var>1</var> has to be "off" to light Bulb <var>2</var> and Switch <var>2</var> has to be "on" to light Bulb <var>3</var>, but then Bulb <var>1</var> will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print <var>0</var>.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8

int solution() {

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

  int k[m];
  int s[m][n];

  for (int i = 0; i < m; i++) {
    scanf("%d", &k[i]);
    for (int j = 0; j < k[i]; j++) {
      scanf("%d", &s[i][j]);
    }
  }

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

  int ret = 0;
  for (int bit = 0; bit < (1 << n); bit++) {
    int sum = 0;
    for (int i = 0; i < m; i++) {
      int temp = 0;
      for (int j = 0; j < k[i]; j++) {
        if ((bit >> (s[i][j] - 1)) & 1) {
          temp++;
        }
      }

      if (temp % 2 == p[i]) {
        sum++;
      }
    }
    if (sum == m) {
      ret++;
    }
  }

  printf("%d", ret);

  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let v: Vec<&str> = s.split_whitespace().collect();
    let (n, m) = (
        v[0].parse::<usize>().unwrap(),
        v[1].parse::<usize>().unwrap(),
    );

    let mut lamps = Vec::new();
    for _i in 0..m {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        let s = buf
            .split_whitespace()
            .skip(1)
            .map(|i| i.parse::<usize>().unwrap() - 1)
            .collect::<Vec<usize>>();
        lamps.push(s);
    }

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let p = buf
        .split_whitespace()
        .map(|i| i.parse::<usize>().unwrap())
        .collect::<Vec<usize>>();

    let mut ans = 0;
    'a: for bit in 0..(1 << n) {
        let mut swc = vec![false; n];
        for sft in 0..n {
            if (bit >> sft) & 1 == 1 {
                swc[sft] = true;
            }
        }

        for (i, ls) in lamps.iter().enumerate() {
            if !ls.iter().filter(|&l| swc[*l]).count() % 2 == p[i] {
                continue 'a;
            }
        }
        ans += 1;
    }

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


Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

  Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

  The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

  For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

int solution() {
  int q;
  scanf("%d", &q);
  for (int n = 0; n < q; n++) {
    char x[1010];
    char y[1010];
    int lenx;
    int leny;
    scanf("%s%n", x, &lenx);
    scanf("%s%n", y, &leny);
    lenx--;
    leny--;
    int dp[lenx + 1][leny + 1];

    for (int i = 0; i < lenx + 1; i++) {
      dp[i][0] = 0;
    }
    for (int j = 0; j < leny + 1; j++) {
      dp[0][j] = 0;
    }

    for (int i = 0; i < lenx; i++) {
      for (int j = 0; j < leny; j++) {
        if (x[i] == y[j]) {
          dp[i + 1][j + 1] = dp[i][j] + 1;
        } else {
          dp[i + 1][j + 1] =
              (dp[i + 1][j] > dp[i][j + 1]) ? dp[i + 1][j] : dp[i][j + 1];
        }
      }
    }
    printf("%d\n", dp[lenx][leny]);
  }
  return 0;
}

fn solution() {
    input! {
        q: usize,
        str: [(chars, chars); q]
    }

    for (l, r) in str {
        let llen = l.len();
        let rlen = r.len();

        let mut dp = vec![vec![0; llen + 1]; rlen + 1];

        for i in 0..rlen {
            for j in 0..llen {
                if r[i] == l[j] {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                } else {
                    dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
                }
            }
        }
        println!("{}", dp[rlen][llen]);
    }
}


Anton likes to play chess, and so does his friend Danik.Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.Now Anton wonders, who won more games, he or Danik? Help him determine this.

int solution() {
  long n = 0;

  int a = 0;
  int d = 0;

  scanf("%ld\n", &n);

  if ((n >= 1) && (n <= 100000)) {

    char s[n];
    int i = 0;
    for (i = 0; i < n; i++) {
      scanf("%c", s + i);
      if (s[i] == 'A') {
        a++;
      } else if (s[i] == 'D') {
        d++;
      }
    }
    s[i] = '\0';

    if (a > d) {
      printf("Anton");
    } else if (d > a) {
      printf("Danik");
    } else {
      printf("Friendship");
    }
  }

  return 0;
}

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

    let _ = io::stdin().read_line(&mut round);
    let _ = io::stdin().read_line(&mut winners);

    let mut anton = 0;
    let mut danik = 0;
    for winner in winners.trim().chars() {
        if winner == 'A' {
            anton += 1;
        } else {
            danik += 1;
        }
    }

    if anton > danik {
        println!("Anton");
    } else if anton < danik {
        println!("Danik");
    } else {
        println!("Friendship");
    }
}


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

int solution() {
  int zushu;
  scanf("%d", &zushu);
  for (int zu = 1; zu <= zushu; zu++) {
    int n;
    char c;
    scanf("%d %c", &n, &c);

    char s[2 * n];
    scanf("%s", s);
    for (int i = 0; i < n; i++) {
      s[i + n] = s[i];
    }

    int max = 0;
    for (int i = 0; i < n; i++) {
      if (s[i] == c) {
        for (int j = 0; j < n; j++) {
          if (s[i + j] == 'g') {
            i = i + j;
            if (j > max) {
              max = j;
            }
            break;
          }
        }
      }
    }
    printf("%d", max);
    if (zu != zushu) {
      printf("\n");
    }
  }
  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let stdin_lock = stdin.lock();
    let mut line_iter = stdin_lock.lines();
    let t = line_iter
        .next()
        .unwrap()
        .unwrap()
        .as_str()
        .parse::<usize>()
        .unwrap();
    for _ in 0..t {
        let n_c_str = line_iter.next().unwrap().unwrap();
        let (n_str, c_str) = n_c_str.split_once(' ').unwrap();
        let (_n, c) = (
            n_str.parse::<usize>().unwrap(),
            c_str.chars().next().unwrap(),
        );
        let s = line_iter.next().unwrap().unwrap();

        if c == 'g' {
            println!("0");
            continue;
        }

        let mut first_g_found = false;
        let mut dist_to_first_g: usize = 0;
        let mut dist_to_green: usize = 0;
        let mut searching_for_green = false;
        let mut max_dist_to_green: usize = 0;

        for symbol in s.chars() {
            if searching_for_green {
                dist_to_green += 1;
            }
            if !first_g_found {
                dist_to_first_g += 1;
            }
            if symbol == 'g' {
                first_g_found = true;
                if searching_for_green {
                    if dist_to_green > max_dist_to_green {
                        max_dist_to_green = dist_to_green;
                    }
                    searching_for_green = false;
                }
            } else {
                if !searching_for_green && symbol == c {
                    searching_for_green = true;
                    dist_to_green = 0;
                }
            }
        }

        if searching_for_green {
            dist_to_green += dist_to_first_g;
            if dist_to_green > max_dist_to_green {
                max_dist_to_green = dist_to_green;
            }
        }
        println!("{0}", max_dist_to_green);
    }
}


New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows $$$h$$$ hours and $$$m$$$ minutes, where $$$0 \le hh < 24$$$ and $$$0 \le mm < 60$$$. We use 24-hour time format!Your task is to find the number of minutes before the New Year. You know that New Year comes when the clock shows $$$0$$$ hours and $$$0$$$ minutes.You have to answer $$$t$$$ independent test cases.

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut queries: i16 = line.trim().parse().unwrap();
    while queries > 0 {
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut numbers = line.split_whitespace();
        let hours: i16 = numbers.next().unwrap().parse().unwrap();
        let minutes: i16 = numbers.next().unwrap().parse().unwrap();
        println!("{}", 1440 - hours * 60 - minutes);
        queries -= 1;
    }
}


Bit Flag

  A state with $n$ flags of ON or OFF can be represented by a sequence of bits where $0, 1, ..., n-1$ -th flag corresponds to 1 (ON) or 0 (OFF).
  The state can be managed by the corresponding decimal integer, because the sequence of bits is a binary representation where each bit is 0 or 1.

  Given a sequence of bits with 64 flags which represent a state, perform the following operations. Note that each flag of the bits is initialized by OFF.

test(i): 		Print 1 if $i$-th flag is ON, otherwise 0

set(i): 		Set $i$-th flag to ON

clear(i):		Set $i$-th flag to OFF

flip(i): 		Inverse $i$-th flag

all:		Print 1 if all flags are ON, otherwise 0

any:		Print 1 if at least one flag is ON, otherwise 0

none:		Print 1 if all flags are OFF, otherwise 0

count:		Print the number of ON flags

val:		Print the decimal value of the state

Input

 The input is given in the following format.

$q$
$query_1$
$query_2$
:
$query_q$

Each query $query_i$ is given in the following format:

0 $i$

or

1 $i$

or

2 $i$

or

3 $i$

or

4

or

5

or

6

or

7

or

8

  The first digit 0, 1,...,8 represents the operation test(i), set(i), clear(i), flip(i), all, any, none, count or val respectively.

Output

  Print the result in a line for each test, all, any, none, count and val operation.

Constraints

$1 \leq q \leq 200,000$

$0 \leq i < 64$

Sample Input 1

14
1 0
1 1
1 2
2 1
0 0
0 1
0 2
0 3
3 3
4
5
6
7
8

Sample Output 1

1
0
1
0
0
1
0
3
13

int solution(void) {
  unsigned long long int bit = 0;
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int command;
    scanf("%d", &command);
    if (0 <= command && command <= 3) {
      int t;
      scanf("%d", &t);
      if (command == 0) {
        if (bit >> t & 1UL) {
          printf("1\n");
        } else {
          printf("0\n");
        }
      } else if (command == 1) {
        bit |= 1UL << t;
      } else if (command == 2) {
        bit &= ~(1UL << t);
      } else {
        bit ^= (1UL << t);
      }
    } else {
      if (command == 4) {
        printf("%d\n", !(bit + 1));
      } else if (command == 5) {
        if (bit == 0) {
          printf("0\n");
        } else {
          printf("1\n");
        }
      } else if (command == 6) {
        printf("%d\n", bit == 0);
      } else if (command == 7) {
        printf("%d\n", __builtin_popcountll(bit));
      } else {
        printf("%llu\n", bit);
      }
    }
  }
  return 0;
}

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

    let mut state = 0u64;

    let q = lines.next().unwrap().unwrap().parse().unwrap();

    for (_, l) in (0..q).zip(lines) {
        let l = l.unwrap();
        let mut sw = l.split_whitespace();
        let com = sw.next().unwrap().parse().unwrap();
        let i = sw.next();
        match com {
            0 => {
                let i: u8 = i.unwrap().parse().unwrap();
                println!("{}", if state & (1 << i) != 0 { 1 } else { 0 });
            }
            1 => {
                let i: u8 = i.unwrap().parse().unwrap();
                state |= 1 << i;
            }
            2 => {
                let i: u8 = i.unwrap().parse().unwrap();
                state &= !(1 << i);
            }
            3 => {
                let i: u8 = i.unwrap().parse().unwrap();
                state ^= 1 << i;
            }
            4 => {
                println!("{}", if state == 0xffffffffffffffff { 1 } else { 0 });
            }
            5 => {
                println!("{}", if state != 0 { 1 } else { 0 });
            }
            6 => {
                println!("{}", if state == 0 { 1 } else { 0 });
            }
            7 => {
                println!("{}", state.count_ones());
            }
            _ => {
                println!("{}", state);
            }
        }
    }
}


Fillomino is a classic logic puzzle. (You do not need to know Fillomino in order to solve this problem.) In one classroom in Yunqi town, some volunteers are playing a board game variant of it:Consider an $$$n$$$ by $$$n$$$ chessboard. Its rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom. Its columns are numbered from $$$1$$$ to $$$n$$$ from the left to the right. A cell on an intersection of $$$x$$$-th row and $$$y$$$-th column is denoted $$$(x, y)$$$. The main diagonal of the chessboard is cells $$$(x, x)$$$ for all $$$1 \le x \le n$$$.A permutation of $$$\{1, 2, 3, \dots, n\}$$$ is written on the main diagonal of the chessboard. There is exactly one number written on each of the cells. The problem is to partition the cells under and on the main diagonal (there are exactly $$$1+2+ \ldots +n$$$ such cells) into $$$n$$$ connected regions satisfying the following constraints:  Every region should be connected. That means that we can move from any cell of a region to any other cell of the same region visiting only cells of the same region and moving from a cell to an adjacent cell.  The $$$x$$$-th region should contain cell on the main diagonal with number $$$x$$$ for all $$$1\le x\le n$$$.  The number of cells that belong to the $$$x$$$-th region should be equal to $$$x$$$ for all $$$1\le x\le n$$$.  Each cell under and on the main diagonal should belong to exactly one region.

int solution() {
  unsigned n;
  unsigned a[500];
  unsigned b[500][500];
  scanf("%u", &n);

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

  for (unsigned i = 0; i < n; i++) {
    unsigned j = 0;
    for (unsigned k = 0; k < n; k++) {
      if (a[k] >= i + 1) {
        b[i + j][j] = a[k];
        j++;
      }
    }
  }

  for (unsigned i = 0; i < n; i++) {
    for (unsigned j = 0; j <= i; j++) {
      printf("%u ", b[i][j]);
    }
    putchar('\n');
  }

  return 0;
}

fn solution() {
    use std::io::Read;
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut itr = buf.split_whitespace();

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

    let n = scan!(usize);
    let mut g = vec![vec![0; n + 1]; n + 1];
    for i in 1..=n {
        g[i][i] = scan!(usize);

        let mut dfs = Vec::<(usize, usize, usize)>::new();
        dfs.push((i, i, g[i][i]));
        while let Some((x, y, c)) = dfs.pop() {
            if c == 0 {
                continue;
            }

            if y > 1 && g[x][y - 1] == 0 {
                g[x][y] = g[i][i];
                dfs.push((x, y - 1, c - 1));
                continue;
            } else {
                assert!(x <= n);
                g[x][y] = g[i][i];
                dfs.push((x + 1, y, c - 1));
                continue;
            }
        }
    }

    for i in 1..=n {
        for j in 1..=i {
            print!("{} ", g[i][j]);
        }
        print!("\n");
    }
}


Are you going to Scarborough Fair?Parsley, sage, rosemary and thyme.Remember me to one who lives there.He once was the true love of mine.Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there.Willem asks his friend, Grick for directions, Grick helped them, and gave them a task.Although the girl wants to help, Willem insists on doing it by himself.Grick gave Willem a string of length n.Willem needs to do m operations, each operation has four parameters l, r, c1, c2, which means that all symbols c1 in range [l, r] (from l-th to r-th, including l and r) are changed into c2. String is 1-indexed.Grick wants to know the final string after all the m operations.

int solution() {
  short len;
  short n;
  scanf("%hi %hi", &len, &n);

  short start[n];
  short end[n];
  char from[n];
  char to[n];
  char str[len];

  scanf("%s", str);

  for (short i = 0; i < n; ++i) {
    scanf("%hi %hi %c %c", &start[i], &end[i], &from[i], &to[i]);
  }

  for (short i = 0; i < n; ++i) {
    for (short j = start[i]; j <= end[i]; ++j) {
      if (str[j - 1] == from[i]) {
        str[j - 1] = to[i];
      }
    }
  }

  for (short i = 0; i < len; ++i) {
    printf("%c", str[i]);
  }

  return 0;
}

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

    let vec = input
        .split_whitespace()
        .map(|item| item.parse::<usize>().unwrap())
        .collect::<Vec<usize>>();

    let (_length, amount) = (vec[0], vec[1]);

    input.clear();
    std::io::stdin()
        .read_line(&mut input)
        .expect("input: read line failed");
    let mut str = input.clone().into_bytes();
    for _i in 0..amount {
        input.clear();
        std::io::stdin()
            .read_line(&mut input)
            .expect("input: read line failed");
        let mut input_splite = input.split_whitespace();
        let (start, end, source, destination) = (
            input_splite.next().unwrap().parse::<usize>().unwrap(),
            input_splite.next().unwrap().parse::<usize>().unwrap(),
            input_splite.next().unwrap().parse::<String>().unwrap(),
            input_splite.next().unwrap().parse::<String>().unwrap(),
        );

        (0..str.len()).for_each(|i| {
            if i < end && i >= start - 1 && str[i] == source.as_bytes()[0] {
                str[i] = destination.as_bytes()[0];
            }
        })
    }

    println!("{}", String::from_utf8(str).unwrap());
}


Problem B: 友だちの誘い方

明日から、待ちに待った夏休みが始まります。なのでわたしは、友だちを誘って、海に遊びに行くこ
とに決めました。

けれども、わたしの友だちには、恥ずかしがりやさんが多いです。その人たちは、あまり多くの人が
いっしょに来ると知ったら、きっと嫌がるでしょう。

ほかにも、わたしの友だちには、目立ちたがりやさんも多いです。その人たちは、いっしょに来る人
があまり多くないと知れば、きっと嫌がるでしょう。

それと、わたしの友だちには、いつもは目立ちたがりやなのに実は恥ずかしがりやさんな人もいま
す。その人たちは、いっしょに来る人が多すぎても少なすぎても、きっと嫌がるでしょう。

こういうのは、大勢で行った方が楽しいはずです。だからわたしは、できるだけたくさんの友だちを
誘いたいと思っています。けれども、嫌がる友だちを無理やり連れていくのはよくありません。

いったい、わたしは最大で何人の友だちを誘うことができるのでしょうか。

わたしは、こういう頭を使いそうな問題が大の苦手です。なので、あなたにお願いがあります。もし
よろしければ、わたしの代わりにこの問題を解いていただけないでしょうか。いえ、決して無理にと
は言いません。けれど、もし解いていただるのでしたら、わたしはとても嬉しいです。

Input

N

a1 b1

a2 b2

.

.

.

aN bN

入力の１行目には、整数N（1 ≤ N ≤ 100,000）が書かれている。これは、友だちの数をあらわす。

続くN行には、整数 ai と整数 bi（2 ≤ ai ≤ bi ≤ 100,001）が、空白区切りで書かれている。１＋ i 行目に書かれた整数 ai とbi は、i 番目の友だちは海に行く人数が ai 人以上 bi 人以下でないと嫌がることをあらわす。海に行く人数には「わたし」も含まれることに注意せよ。

Output

嫌がる友だちが出ないように、海に誘うことのできる友だちの最大人数を出力せよ。

Sample Input 1

4
2 5
4 7
2 4
3 6

Sample output 1

3

Sample Input 2

5
8 100001
7 100001
12 100001
8 100001
3 100001

Sample output 2

0

Sample Input 3

6
2 9
4 8
6 7
6 6
5 7
2 100001

Sample output 3

5

int solution() {

  int a[100002] = {0};
  int b[100002] = {0};
  int N;
  int i;
  int k;
  int answer = 0;
  int p;

  scanf("%d", &N);
  for (i = 1; i <= N; i++) {
    scanf("%d %d", &a[i], &b[i]);
  }

  for (k = N + 1; k >= 1; k--) {
    p = 0;
    for (i = 1; i <= N; i++) {
      if (a[i] <= k && k <= b[i]) {
        p++;
      }

      if (p == k) {
        answer = p - 1;
        break;
      }
      if (p == k - 1) {
        answer = p;
        break;
      }
    }
    if (answer > 0) {
      break;
    }
  }

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

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

    let mut v: Vec<i32> = (0..100010).map(|_| 0).collect();
    let n: usize = iter.next().unwrap().parse().unwrap();
    for _i in 0..n {
        let a: usize = iter.next().unwrap().parse().unwrap();
        let b: usize = iter.next().unwrap().parse().unwrap();
        v[a] += 1;
        v[b + 1] -= 1;
    }
    let mut result = 0;
    let mut member = 1;
    for i in 2..n + 2 {
        member += v[i];
        let i = i as i32;
        if i <= member {
            result = i;
        }
    }
    if result > 0 {
        result -= 1;
    }
    println!("{}", result);
}


You are given a binary string $$$s$$$ consisting of $$$n$$$ zeros and ones.Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should not contain two adjacent zeros or ones).Recall that a subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, subsequences of "1011101" are "0", "1", "11111", "0111", "101", "1001", but not "000", "101010" and "11100".You have to answer $$$t$$$ independent test cases.

int solution() {
  int tc;
  scanf("%d", &tc);
  while (tc--) {
    int n;
    int i;
    int z = -1;
    int o = -1;
    int s = 0;
    int max = -1;
    scanf("%d", &n);
    char ss[n + 5];
    char at[2];

    scanf("%s", ss);
    int a[n];
    int b[n];
    int zero[n];
    int one[n];
    for (i = 0; i < n; i++) {
      at[0] = ss[i];
      at[1] = '\0';
      a[i] = atoi(at);
    }
    for (i = 0; i < n; i++) {
      if (!a[i]) {
        if (o >= 0) {
          zero[++z] = one[o--];
          b[i] = zero[z];
        } else {
          zero[++z] = ++s;
          b[i] = zero[z];
        }
      }
      if (a[i]) {
        if (z >= 0) {
          one[++o] = zero[z--];
          b[i] = one[o];
        } else {
          one[++o] = ++s;
          b[i] = one[o];
        }
      }
      if (max < b[i]) {
        max = b[i];
      }
    }
    printf("%d\n", max);
    for (i = 0; i < n; i++) {
      printf("%d ", b[i]);
    }
    printf("\n");
  }
}

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

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

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

        let mut a = Vec::with_capacity(n);
        let mut zeros: VecDeque<usize> = VecDeque::new();
        let mut ones: VecDeque<usize> = VecDeque::new();
        for i in 0..n {
            if s[i] == '0' {
                if let Some(x) = ones.pop_front() {
                    a.push(x.to_string());
                    zeros.push_back(x);
                } else {
                    let x = zeros.len() + 1;
                    a.push(x.to_string());
                    zeros.push_back(x);
                }
            } else {
                if let Some(x) = zeros.pop_front() {
                    a.push(x.to_string());
                    ones.push_back(x);
                } else {
                    let x = ones.len() + 1;
                    a.push(x.to_string());
                    ones.push_back(x);
                }
            }
        }

        println!("{}", zeros.len() + ones.len());
        println!("{}", a.join(" "));
    }
}


A pair of positive integers $$$(a,b)$$$ is called special if $$$\lfloor \frac{a}{b} \rfloor = a \bmod b$$$. Here, $$$\lfloor \frac{a}{b} \rfloor$$$ is the result of the integer division between $$$a$$$ and $$$b$$$, while $$$a \bmod b$$$ is its remainder.You are given two integers $$$x$$$ and $$$y$$$. Find the number of special pairs $$$(a,b)$$$ such that $$$1\leq a \leq x$$$ and $$$1 \leq b \leq y$$$.

int solution() {
  int t;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int x;
    int y;
    long long int Answer = 0;
    scanf("%d%d", &x, &y);
    for (int k = 1; k < pow(x, 0.5); k++) {
      int temp = (x / k) - 1;
      int min1;
      int max1;
      if (y < temp) {
        min1 = y;
      } else {
        min1 = temp;
      }

      min1 = min1 - k;
      if (min1 > 0) {
        Answer += min1;
      }
    }

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

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 (x, y): (i64, i64) = (sc.next(), sc.next());
        let mut i = 1;
        let mut ans = 0;
        while i * i <= x && i < y {
            ans += max(min((x - i) / i, y) - i, 0);
            i += 1;
        }
        writeln!(out, "{}", ans).unwrap();
    }
}


Score : <var>500</var> points

Problem Statement

We have a grid with <var>H</var> horizontal rows and <var>W</var> vertical columns. Let <var>(i,j)</var> denote the square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left.

The square <var>(i, j)</var> has two numbers <var>A_{ij}</var> and <var>B_{ij}</var> written on it.

First, for each square, Takahashi paints one of the written numbers red and the other blue.

Then, he travels from the square <var>(1, 1)</var> to the square <var>(H, W)</var>. In one move, he can move from a square <var>(i, j)</var> to the square <var>(i+1, j)</var> or the square <var>(i, j+1)</var>. He must not leave the grid.

Let the unbalancedness be the absolute difference of the sum of red numbers and the sum of blue numbers written on the squares along Takahashi's path, including the squares <var>(1, 1)</var> and <var>(H, W)</var>.

Takahashi wants to make the unbalancedness as small as possible by appropriately painting the grid and traveling on it.

Find the minimum unbalancedness possible.

Constraints

<var>2 \leq H \leq 80</var>

<var>2 \leq W \leq 80</var>

<var>0 \leq A_{ij} \leq 80</var>

<var>0 \leq B_{ij} \leq 80</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>A_{11}</var> <var>A_{12}</var> <var>\ldots</var> <var>A_{1W}</var>
<var>:</var>
<var>A_{H1}</var> <var>A_{H2}</var> <var>\ldots</var> <var>A_{HW}</var>
<var>B_{11}</var> <var>B_{12}</var> <var>\ldots</var> <var>B_{1W}</var>
<var>:</var>
<var>B_{H1}</var> <var>B_{H2}</var> <var>\ldots</var> <var>B_{HW}</var>

Output

Print the minimum unbalancedness possible.

Sample Input 1

2 2
1 2
3 4
3 4
2 1

Sample Output 1

0

By painting the grid and traveling on it as shown in the figure below, the sum of red numbers and the sum of blue numbers are <var>3+3+1=7</var> and <var>1+2+4=7</var>, respectively, for the unbalancedness of <var>0</var>.

Sample Input 2

2 3
1 10 80
80 10 1
1 2 3
4 5 6

Sample Output 2

2

int solution(void) {

  int h;
  int w;
  scanf("%d %d", &h, &w);
  long a[h][w];
  long b[h][w];
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      scanf("%ld", &a[i][j]);
    }
  }
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      scanf("%ld", &b[i][j]);
    }
  }
  long ab[h][w];
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      ab[i][j] = labs(a[i][j] - b[i][j]);
    }
  }
  long limit = (h + w) * 80;
  long ***dp;
  dp = (long ***)malloc(sizeof(long **) * 80);
  for (long i = 0; i < 80; i++) {
    dp[i] = (long **)malloc(sizeof(long *) * 80);
    for (long j = 0; j < 80; j++) {
      dp[i][j] = (long *)malloc(sizeof(long) * (limit + 1));
      for (long k = 0; k <= limit; k++) {
        dp[i][j][k] = 0;
      }
    }
  }
  long value = ab[0][0];
  dp[0][0][value] = 1;
  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      if (i != 0) {
        for (long k = 0; k <= limit; k++) {
          if (dp[i - 1][j][k] == 1) {
            value = labs(k + ab[i][j]);
            dp[i][j][value] = 1;
            value = labs(k - ab[i][j]);
            dp[i][j][value] = 1;
          }
        }
      }
      if (j != 0) {
        for (long k = 0; k <= limit; k++) {
          if (dp[i][j - 1][k] == 1) {
            value = labs(k + ab[i][j]);
            dp[i][j][value] = 1;
            value = labs(k - ab[i][j]);
            dp[i][j][value] = 1;
          }
        }
      }
    }
  }
  for (long i = 0; i <= limit; i++) {
    if (dp[h - 1][w - 1][i] == 1) {
      printf("%ld\n", i);
      break;
    }
  }

  return 0;
}

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

    let input_parts = input_str.split_whitespace().collect::<Vec<_>>();
    let mut input_parts_it = input_parts.iter().cloned();
    let mut next = || input_parts_it.next().unwrap();

    let h: usize = next().parse().unwrap();
    let w: usize = next().parse().unwrap();
    let a_map: Vec<i32> = (0..(w * h)).map(|_| next().parse().unwrap()).collect();
    let b_map: Vec<i32> = (0..(w * h)).map(|_| next().parse().unwrap()).collect();

    let idx = |x: usize, y: usize| x + y * w;

    let mut costs: Vec<Vec<i32>> = vec![Vec::new(); a_map.len()];

    let mut buf = Vec::new();

    for y in 0..h {
        for x in 0..w {
            buf.clear();

            if x == 0 && y == 0 {
                buf.push(0);
            }
            if x > 0 {
                buf.extend(costs[idx(x - 1, y)].iter().cloned());
            }
            if y > 0 {
                buf.extend(costs[idx(x, y - 1)].iter().cloned());
            }

            let (a, b) = (a_map[idx(x, y)], b_map[idx(x, y)]);

            let out_cost = &mut costs[idx(x, y)];
            out_cost.reserve(buf.len() * 2);
            out_cost.extend(buf.iter().map(|&x| x + (a - b)));
            out_cost.extend(buf.iter().map(|&x| x + (b - a)));
            out_cost.sort();
            out_cost.dedup();
        }
    }

    let goal = costs.last().unwrap();

    let best = goal.iter().map(|&cost| cost.abs()).min().unwrap();

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


Score : <var>400</var> points

Problem Statement

You are given <var>N</var> non-negative integers <var>A_1, A_2, ..., A_N</var> and another non-negative integer <var>K</var>.

For a integer <var>X</var> between <var>0</var> and <var>K</var> (inclusive), let <var>f(X) = (X</var> XOR <var>A_1)</var> <var>+</var> <var>(X</var> XOR <var>A_2)</var> <var>+</var> <var>...</var> <var>+</var> <var>(X</var> XOR <var>A_N)</var>.

Here, for non-negative integers <var>a</var> and <var>b</var>, <var>a</var> XOR <var>b</var> denotes the bitwise exclusive OR of <var>a</var> and <var>b</var>.

Find the maximum value of <var>f</var>.

What is XOR?

The bitwise exclusive OR of <var>a</var> and <var>b</var>, <var>X</var>, is defined as follows:

When <var>X</var> is written in base two, the digit in the <var>2^k</var>'s place (<var>k \geq 0</var>) is <var>1</var> if, when written in base two, exactly one of <var>A</var> and <var>B</var> has <var>1</var> in the <var>2^k</var>'s place, and <var>0</var> otherwise.

For example, <var>3</var> XOR <var>5 = 6</var>. (When written in base two: <var>011</var> XOR <var>101 = 110</var>.)

int solution(void) {
  int N = 0;
  long K = 0;
  int bin[50] = {0};
  long long sum = 0;
  long X = 0;

  scanf("%d %ld", &N, &K);

  long A[N];

  for (int i = 0; i < N; i++) {
    A[i] = 0;
    scanf("%ld", &A[i]);
    sum += A[i];
    for (int j = 0; j < 50; j++) {
      if (A[i] % 2) {
        bin[j]++;
      }
      A[i] /= (long)2;
    }
  }

  for (int i = 49; i >= 0; i--) {
    if (bin[i] < (N + 1) / 2) {
      if (X + (long)(pow(2, i)) <= K) {
        X += (long)pow(2, i);
        sum += (long long)pow(2, i) * (long long)(N - (bin[i] * 2));
      }
    }
  }

  printf("%lld", sum);

  return 0;
}

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

    for i in (0..61).rev() {
        let bit = 1u64 << i;
        let mut bit0 = 0;
        let mut bit1 = 0;
        for y in a.iter() {
            if (y & bit) != 0 {
                bit1 += 1;
            } else {
                bit0 += 1;
            }
        }
        if x + bit <= k && bit1 < bit0 {
            x += bit;
            ans += bit * bit0;
        } else {
            ans += bit * bit1;
        }
    }

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


Score : <var>500</var> points

Problem Statement

There is a directed graph with <var>N</var> vertices numbered <var>1</var> to <var>N</var> and <var>M</var> edges.
The <var>i</var>-th edge is directed from Vertex <var>A_i</var> to Vertex <var>B_i</var>, and there are <var>C_i</var> coins placed along that edge.
Additionally, there is a button on Vertex <var>N</var>.

We will play a game on this graph.
You start the game on Vertex <var>1</var> with zero coins, and head for Vertex <var>N</var> by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex <var>N</var>, you can end the game by pressing the button. (You can also choose to leave Vertex <var>N</var> without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay <var>T \times P</var> coins, where <var>T</var> is the number of minutes elapsed since the start of the game. If you have less than <var>T \times P</var> coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

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

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

<var>1 \leq A_i, B_i \leq N</var>

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

<var>0 \leq P \leq 10^5</var>

All values in input are integers.

Vertex <var>N</var> can be reached from Vertex <var>1</var>.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>P</var>
<var>A_1</var> <var>B_1</var> <var>C_1</var>
<var>:</var>
<var>A_M</var> <var>B_M</var> <var>C_M</var>

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex <var>1</var> to Vertex <var>3</var>:

Vertex <var>1 \rightarrow 2 \rightarrow 3</var>: You collect <var>20 + 30 = 50</var> coins on the way. After two minutes from the start of the game, you press the button, pay <var>2 \times 10 = 20</var> coins, and you have <var>50 - 20 = 30</var> coins left.

Vertex <var>1 \rightarrow 2</var>: You collect <var>45</var> coins on the way. After one minute from the start of the game, you press the button, pay <var>1 \times 10 = 10</var> coins, and you have <var>45 - 10 = 35</var> coins left.

Thus, the maximum score that can be obtained is <var>35</var>.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex <var>1</var> takes you to Vertex <var>2</var>. If you then traverse the edge extending from Vertex <var>2</var> to itself <var>t</var> times and press the button, your score will be <var>90 + 90t</var>. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex <var>1</var> to Vertex <var>4</var> other than traversing the edge leading from Vertex <var>1</var> to Vertex <var>4</var> directly. You will pick up one coin along this edge, but after being asked to paying <var>10</var> coins, your score will be <var>0</var>.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex <var>1</var> to Vertex <var>2</var>, but this is pointless since you can no longer reach Vertex <var>4</var> and end the game.

fn solution() {
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());

    input! {
      n: usize,
      m: usize,
      p: i64,
      es: [(usize1, usize1, i64); m],
    }
    let es: Vec<_> = es.into_iter().map(|(a, b, c)| (a, b, c - p)).collect();
    let mut score = vec![-(1i64 << 60); n];
    score[0] = 0;
    let mut reach_start = vec![false; n];
    reach_start[0] = true;
    let mut reach_end = vec![false; n];
    reach_end[n - 1] = true;
    for _ in 0..n - 1 {
        for &(a, b, c) in &es {
            score[b] = cmp::max(score[b], score[a] + c);
            reach_start[b] = reach_start[b] || reach_start[a];
            reach_end[a] = reach_end[a] || reach_end[b];
        }
    }
    let mut update = false;
    for &(a, b, c) in &es {
        if reach_start[b] && reach_end[b] && score[a] + c > score[b] {
            update = true;
            break;
        }
    }
    if update {
        puts!("-1\n");
    } else {
        puts!("{}\n", cmp::max(score[n - 1], 0));
    }
}


Score : <var>100</var> points

Problem Statement

You will be given an integer <var>a</var> and a string <var>s</var> consisting of lowercase English letters as input.

Write a program that prints <var>s</var> if <var>a</var> is not less than <var>3200</var> and prints red if <var>a</var> is less than <var>3200</var>.

Constraints

<var>2800 \leq a < 5000</var>

<var>s</var> is a string of length between <var>1</var> and <var>10</var> (inclusive).

Each character of <var>s</var> is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

<var>a</var>
<var>s</var>

Output

If <var>a</var> is not less than <var>3200</var>, print <var>s</var>; if <var>a</var> is less than <var>3200</var>, print red.

Sample Input 1

3200
pink

Sample Output 1

pink

<var>a = 3200</var> is not less than <var>3200</var>, so we print <var>s =</var> pink.

Sample Input 2

3199
pink

Sample Output 2

red

<var>a = 3199</var> is less than <var>3200</var>, so we print red.

Sample Input 3

4049
red

Sample Output 3

red

<var>a = 4049</var> is not less than <var>3200</var>, so we print <var>s =</var> red.

int solution(void) {
  int a = 0;
  char s[20];
  char *ss = "red";
  scanf("%d", &a);
  scanf("%s", s);
  if (a >= 3200) {
    printf("%s\n", s);
  } else {
    printf("%s\n", ss);
  }
  return 0;
}

fn solution() {
    let mut a = String::new();
    let mut s = String::new();
    std::io::stdin().read_line(&mut a).unwrap();
    std::io::stdin().read_line(&mut s).unwrap();
    let a: i32 = a.trim().parse().unwrap();
    println!("{}", if a >= 3200 { s.trim() } else { "red" });
}