Ashish has a string $$$s$$$ of length $$$n$$$ containing only characters 'a', 'b' and 'c'.He wants to find the length of the smallest substring, which satisfies the following conditions:   Length of the substring is at least $$$2$$$  'a' occurs strictly more times in this substring than 'b'  'a' occurs strictly more times in this substring than 'c'  Ashish is busy planning his next Codeforces round. Help him solve the problem.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

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

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

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

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

        for k in 2..=7 {
            for w in s.windows(k) {
                let mut na = 0;
                let mut nb = 0;
                let mut nc = 0;
                for &c in w {
                    match c {
                        b'a' => na += 1,
                        b'b' => nb += 1,
                        _ => nc += 1,
                    }
                }
                if na > nb && na > nc {
                    writeln!(&mut output, "{}", k).unwrap();
                    continue 'cases;
                }
            }
        }

        writeln!(&mut output, "-1").unwrap();
    }
}


Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    int x = 0;
    scanf("%d", &n);
    scanf("%d", &x);
    int w[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &w[i]);
    }
    int sum = 0;
    int flag = 0;
    for (int i = 0; i < n; i++) {
      sum += w[i];
      if (sum > x) {
        flag = 1;
        break;
      }
      if (sum == x) {
        for (int j = i + 1; j < n; j++) {
          if (w[i] != w[j]) {
            sum -= w[i];
            int temp = 0;
            temp = w[i];
            w[i] = w[j];
            w[j] = temp;
            sum += w[j];

            if (sum > x) {
              flag = 1;
            }
            break;
          }
        }
      }
      if (i == n - 1 && sum < x) {
        flag = 1;
      }
    }
    if (flag == 0) {
      printf("No\n");
    }
    if (flag == 1) {
      printf("Yes\n");
    }
    if (flag == 1) {
      for (int i = 0; i < n; i++) {
        printf("%d ", w[i]);
      }
      printf("\n");
    }
  }
  return 0;
}

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

    std::io::stdin().read_line(&mut buf).expect("Failed read");
    let t: i32 = buf.trim().parse().expect("Failed parse");
    buf = String::new();

    for _ in 0..t {
        std::io::stdin().read_line(&mut buf).expect("Failed read");
        let x: i32 = buf.split_whitespace().last().unwrap().parse().unwrap();
        buf = String::new();

        std::io::stdin().read_line(&mut buf).expect("Failed read");
        let mut w: Vec<i32> = buf
            .split_whitespace()
            .map(|elem| elem.parse().expect("Failed parse"))
            .collect();
        buf = String::new();

        if w.iter().sum::<i32>() == x {
            println!("NO");
        } else {
            println!("YES");
            let mut cur_sum = 0;
            for i in 0..w.len() {
                if cur_sum + w[i] == x {
                    w.swap(i, i + 1);
                }
                print!("{} ", w[i]);
                cur_sum += w[i];
            }
            println!();
        }
    }
}


Score: <var>200</var> points

Problem Statement

The number <var>105</var> is quite special - it is odd but still it has eight divisors.
Now, your task is this: how many odd numbers with exactly eight positive divisors are there between <var>1</var> and <var>N</var> (inclusive)?

Constraints

<var>N</var> is an integer between <var>1</var> and <var>200</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the count.

Sample Input 1

105

Sample Output 1

1

Among the numbers between <var>1</var> and <var>105</var>, the only number that is odd and has exactly eight divisors is <var>105</var>.

Sample Input 2

7

Sample Output 2

0

<var>1</var> has one divisor. <var>3</var>, <var>5</var> and <var>7</var> are all prime and have two divisors. Thus, there is no number that satisfies the condition.

int solution() {
  int n = 0;
  int qntdiv = 0;
  int divi = 0;

  scanf("%d", &n);

  for (int i = 1; i <= n; ++i) {
    if (i & 1) {
      for (int j = 1; j <= i; ++j) {
        if (i % j == 0) {
          ++qntdiv;
          if (qntdiv == 8) {
            ++divi;
          }
        }
      }
      qntdiv = 0;
    }
  }
  printf("%d\n", divi);
  return 0;
}

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

    let mut s = String::new();

    let _ = reader.read_line(&mut s);
    let n: u32 = s.trim().parse().unwrap();
    let mut result = 0;

    for i in 1..n + 1 {
        if i % 2 == 0 {
            continue;
        }
        let mut count = 0;
        for j in 1..i + 1 {
            if i % j == 0 {
                count += 1;
            }
        }
        if count == 8 {
            result += 1;
        }
    }
    println!("{}", result);
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> people, conveniently numbered <var>1</var> through <var>N</var>.
They were standing in a row yesterday, but now they are unsure of the order in which they were standing.
However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the number of the people who were standing to the right of that person.
According to their reports, the difference above for person <var>i</var> is <var>A_i</var>.

Based on these reports, find the number of the possible orders in which they were standing.
Since it can be extremely large, print the answer modulo <var>10^9+7</var>.
Note that the reports may be incorrect and thus there may be no consistent order.
In such a case, print <var>0</var>.

Constraints

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

<var>0≦A_i≦N-1</var>

Input

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

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

Output

Print the number of the possible orders in which they were standing, modulo <var>10^9+7</var>.

Sample Input 1

5
2 4 4 0 2

Sample Output 1

4

There are four possible orders, as follows:

<var>2,1,4,5,3</var>

<var>2,5,4,1,3</var>

<var>3,1,4,5,2</var>

<var>3,5,4,1,2</var>

Sample Input 2

7
6 4 0 2 4 0 2

Sample Output 2

0

Any order would be inconsistent with the reports, thus the answer is <var>0</var>.

Sample Input 3

8
7 5 1 1 7 3 5 3

Sample Output 3

16


Score : <var>500</var> points

Problem Statement

Takahashi is not good at problems about trees in programming contests, and Aoki is helping him practice.

First, Takahashi created a tree with <var>N</var> vertices numbered <var>1</var> through <var>N</var>, and wrote <var>0</var> at each edge.

Then, Aoki gave him <var>M</var> queries. The <var>i</var>-th of them is as follows:

Increment the number written at each edge along the path connecting vertices <var>a_i</var> and <var>b_i</var>, by one.

After Takahashi executed all of the queries, he told Aoki that, for every edge, the written number became an even number.
However, Aoki forgot to confirm that the graph Takahashi created was actually a tree, and it is possible that Takahashi made a mistake in creating a tree or executing queries.

Determine whether there exists a tree that has the property mentioned by Takahashi.

Constraints

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

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

<var>1 ≤ a_i,b_i ≤ N</var>

<var>a_i ≠ b_i</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>a_1</var> <var>b_1</var>
:
<var>a_M</var> <var>b_M</var>

Output

Print YES if there exists a tree that has the property mentioned by Takahashi; print NO otherwise.

Sample Input 1

4 4
1 2
2 4
1 3
3 4

Sample Output 1

YES

For example, Takahashi's graph has the property mentioned by him if it has the following edges: <var>1-2</var>, <var>1-3</var> and <var>1-4</var>.
In this case, the number written at every edge will become <var>2</var>.

Sample Input 2

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

Sample Output 2

NO

int solution(void) {
  int N;
  int M;
  scanf("%d %d", &N, &M);
  int a[M];
  int b[M];
  for (int i = 0; i < M; i++) {
    scanf("%d %d", &a[i], &b[i]);
  }

  int C[N + 1];
  for (int i = 1; i <= N; i++) {
    C[i] = 0;
  }
  for (int i = 0; i < M; i++) {
    C[a[i]]++;
    C[b[i]]++;
  }
  for (int i = 1; i <= N; i++) {
    if (C[i] % 2 == 1) {
      printf("NO\n");
      return 0;
    }
  }
  printf("YES\n");
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let m = it.next().unwrap().parse::<usize>().unwrap();
    let mut cnt = vec![0; n];
    for _ in 0..2 * m {
        cnt[it.next().unwrap().parse::<usize>().unwrap() - 1] += 1;
    }
    println!(
        "{}",
        if cnt.iter().all(|x| x % 2 == 0) {
            "YES"
        } else {
            "NO"
        }
    );
}


Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.

int solution() {
  int n;
  int q;
  scanf("%d %d", &n, &q);
  char *song = malloc(sizeof(char) * (n + 1));
  scanf("%s", song);
  int count[n + 2];
  char alphabet[27] = "abcdefghijklmnopqrstuvwxyz";
  count[0] = 0;
  for (int i = 0; i < n; i++) {
    const char *find = strchr(alphabet, song[i]);
    count[i + 1] = count[i] + (find - alphabet) + 1;
  }

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

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

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

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

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

    let n = it.next().unwrap();
    let q = it.next().unwrap();

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

    let mut t = vec![0; n + 1];

    for i in 1..=n {
        let x = (a[i - 1] - (b'a' - 1)) as u64;
        t[i] = t[i - 1] + x;
    }

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

        let l = it.next().unwrap();
        let r = it.next().unwrap();

        let ans = t[r] - t[l - 1];

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


One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?

int solution() {
  char s1[5001];
  scanf("%s", s1);
  int ca[5001];
  int cb[5001];
  memset(ca, 0, sizeof(ca));
  memset(cb, 0, sizeof(cb));
  int i;
  for (i = 0; s1[i]; i++) {
    ca[i + 1] = ca[i];
    cb[i + 1] = cb[i];
    if (s1[i] == 'a') {
      ca[i + 1]++;
    } else {
      cb[i + 1]++;
    }
  }
  int len = i;
  int alla = ca[len];
  int allb = cb[len];
  int max = 0;
  int j;
  for (i = 1; i <= len; i++) {
    for (j = i; j <= len; j++) {
      int nowans = len - (cb[i - 1] + allb - cb[j] + ca[j] - ca[i - 1]);
      if (nowans > max) {
        max = nowans;
      }
    }
  }
  if (alla > max) {
    max = alla;
  }
  if (allb > max) {
    max = allb;
  }
  printf("%d\n", max);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    stdin().read_line(&mut buf);
    let bs: Vec<i32> = once(0)
        .chain(buf.chars().scan(0, |acc, c| match c {
            'a' => Some(*acc),
            'b' => {
                *acc += 1;
                Some(*acc)
            }
            _ => None,
        }))
        .collect();
    let n = bs.len() - 1;
    let na = n as i32 - bs[n];
    let _ac = |i: usize| i as i32 - bs[i];
    let res: i32 = (0..n + 1)
        .map(|i| {
            (i..n + 1)
                .map(|j| na - (j - i) as i32 + 2 * (bs[j] - bs[i]))
                .max()
                .unwrap()
        })
        .max()
        .unwrap();
    println!("{:?}", res);
}


Score: <var>400</var> points

Problem Statement

There is a cave.

The cave has <var>N</var> rooms and <var>M</var> passages. The rooms are numbered <var>1</var> to <var>N</var>, and the passages are numbered <var>1</var> to <var>M</var>. Passage <var>i</var> connects Room <var>A_i</var> and Room <var>B_i</var> bidirectionally. One can travel between any two rooms by traversing passages. Room <var>1</var> is a special room with an entrance from the outside.

It is dark in the cave, so we have decided to place a signpost in each room except Room <var>1</var>. The signpost in each room will point to one of the rooms directly connected to that room with a passage.

Since it is dangerous in the cave, our objective is to satisfy the condition below for each room except Room <var>1</var>.

If you start in that room and repeatedly move to the room indicated by the signpost in the room you are in, you will reach Room <var>1</var> after traversing the minimum number of passages possible.

Determine whether there is a way to place signposts satisfying our objective, and print one such way if it exists.

Constraints

All values in input are integers.

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

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

<var>1 \leq A_i, B_i \leq N\ (1 \leq i \leq M)</var>

<var>A_i \neq B_i\ (1 \leq i \leq M)</var>

One can travel between any two rooms by traversing passages.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>A_1</var> <var>B_1</var>
<var>:</var>
<var>A_M</var> <var>B_M</var>

Output

If there is no way to place signposts satisfying the objective, print No.

Otherwise, print <var>N</var> lines. The first line should contain Yes, and the <var>i</var>-th line <var>(2 \leq i \leq N)</var> should contain the integer representing the room indicated by the signpost in Room <var>i</var>.

Sample Input 1

4 4
1 2
2 3
3 4
4 2

Sample Output 1

Yes
1
2
2

If we place the signposts as described in the sample output, the following happens:

Starting in Room <var>2</var>, you will reach Room <var>1</var> after traversing one passage: <var>(2) \to 1</var>. This is the minimum number of passages possible.

Starting in Room <var>3</var>, you will reach Room <var>1</var> after traversing two passages: <var>(3) \to 2 \to 1</var>. This is the minimum number of passages possible.

Starting in Room <var>4</var>, you will reach Room <var>1</var> after traversing two passages: <var>(4) \to 2 \to 1</var>. This is the minimum number of passages possible.

Thus, the objective is satisfied.

Sample Input 2

6 9
3 4
6 1
2 4
5 3
4 6
1 5
6 2
4 5
5 6

Sample Output 2

Yes
6
5
5
1
1

If there are multiple solutions, any of them will be accepted.

int solution() {
  int N;
  int M;
  scanf("%d %d", &N, &M);
  int *node[N + 1];
  int n_edge[N + 1];
  for (int i = 0; i <= N; i++) {
    node[i] = NULL;
    n_edge[i] = 0;
  }
  for (int m = 1; m <= M; m++) {
    int i;
    int j;
    scanf("%d %d", &i, &j);
    n_edge[i]++;
    n_edge[j]++;
    node[i] = (int *)realloc(node[i], sizeof(int) * n_edge[i]);
    node[i][n_edge[i] - 1] = j;
    node[j] = (int *)realloc(node[j], sizeof(int) * n_edge[j]);
    node[j][n_edge[j] - 1] = i;
  }

  int start = 1;
  int end = start;
  int vacant = 2;
  int queue[N + 1];
  int state[N + 1];
  for (int i = 1; i <= N; i++) {
    state[i] = -1;
  }
  queue[1] = 1;
  state[1] = 1;
  while (start <= end) {
    for (int current = start; current <= end; current++) {
      int base = queue[current];
      for (int i = 0; i < n_edge[base]; i++) {
        int neighbor = node[base][i];
        if (state[neighbor] < 0) {
          queue[vacant] = neighbor;
          state[neighbor] = base;
          vacant++;
        }
      }
    }
    start = end + 1;
    end = vacant - 1;
  }
  printf("Yes\n");
  for (int n = 2; n <= N; n++) {
    printf("%d\n", state[n]);
  }
  for (int i = 0; i <= N; i++) {
    free(node[i]);
  }
  return 0;
}

fn solution() {
    input! {
        n: usize,
        m: usize,
        v: [(usize1, usize1); m]
    }
    let mut g = vec![vec![]; n];
    for &(a, b) in &v {
        g[a].push(b);
        g[b].push(a);
    }
    let mut q = VecDeque::new();
    let mut ans = vec![n; n];
    ans[0] = 0;
    q.push_back(0);
    while let Some(i) = q.pop_front() {
        for &j in &g[i] {
            if ans[j] == n {
                ans[j] = i;
                q.push_back(j);
            }
        }
    }
    println!("Yes");
    for &a in ans.iter().skip(1) {
        println!("{}", a + 1);
    }
}


In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.

int solution() {
  int n;
  scanf("%d", &n);
  int A[n];
  int vis[n];
  for (int i = 1; i <= n; i++) {
    scanf("%d", &A[i]);
    vis[i] = 0;
  }
  for (int i = 1; i <= n; i++) {
    int j = i;
    while (1) {
      if (vis[j] == 0) {
        vis[j] = 1;
        j = A[j];
      } else {
        printf("%d\t", j);
        break;
      }
    }
    for (int k = 1; k <= n; k++) {
      vis[k] = 0;
    }
  }
  return 0;
}

fn solution() {
    let mut buffer = String::new();
    let stdin = io::stdin();
    let mut handle = stdin.lock();
    handle.read_to_string(&mut buffer).unwrap();
    let arr: Vec<i32> = buffer
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .collect();
    let n = *arr.get(0).unwrap();
    for i in 0..n as usize {
        let mut hs = HashSet::new();
        let mut a = i as i32 + 1;
        let mut pa = arr[i + 1];
        hs.insert(a);
        while !hs.contains(&pa) {
            a = pa;
            pa = arr[a as usize];
            hs.insert(a);
        }
        println!("{}", pa);
    }
}


You are given two sequences $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$. Each element of both sequences is either $$$0$$$, $$$1$$$ or $$$2$$$. The number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$a$$$ is $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ respectively, and the number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$b$$$ is $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ respectively.You can rearrange the elements in both sequences $$$a$$$ and $$$b$$$ however you like. After that, let's define a sequence $$$c$$$ as follows:$$$c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$$$You'd like to make $$$\sum_{i=1}^n c_i$$$ (the sum of all elements of the sequence $$$c$$$) as large as possible. What is the maximum possible sum?

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 (_x1, y1, z1): (i64, i64, i64) = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        let (x2, y2, _z2): (i64, i64, i64) = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            (
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            )
        };

        let ans = min(z1, y2) - max(0, y1 - (x2 + max(0, y2 - z1)));
        println!("{}", ans * 2);
    }
}


Score : <var>400</var> points

Problem Statement

Mountaineers Mr. Takahashi and Mr. Aoki recently trekked across a certain famous mountain range.
The mountain range consists of <var>N</var> mountains, extending from west to east in a straight line as Mt. <var>1</var>, Mt. <var>2</var>, ..., Mt. <var>N</var>.
Mr. Takahashi traversed the range from the west and Mr. Aoki from the east.

The height of Mt. <var>i</var> is <var>h_i</var>, but they have forgotten the value of each <var>h_i</var>.
Instead, for each <var>i</var> (<var>1 ≤ i ≤ N</var>), they recorded the maximum height of the mountains climbed up to the time they reached the peak of Mt. <var>i</var> (including Mt. <var>i</var>).
Mr. Takahashi's record is <var>T_i</var> and Mr. Aoki's record is <var>A_i</var>.

We know that the height of each mountain <var>h_i</var> is a positive integer.
Compute the number of the possible sequences of the mountains' heights, modulo <var>10^9 + 7</var>.

Note that the records may be incorrect and thus there may be no possible sequence of the mountains' heights.
In such a case, output <var>0</var>.

Constraints

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

<var>1 ≤ T_i ≤ 10^9</var>

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

<var>T_i ≤ T_{i+1}</var> (<var>1 ≤ i ≤ N - 1</var>)

<var>A_i ≥ A_{i+1}</var> (<var>1 ≤ i ≤ N - 1</var>)

Input

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

<var>N</var>
<var>T_1</var> <var>T_2</var> <var>...</var> <var>T_N</var>
<var>A_1</var> <var>A_2</var> <var>...</var> <var>A_N</var>

Output

Print the number of possible sequences of the mountains' heights, modulo <var>10^9 + 7</var>.

Sample Input 1

5
1 3 3 3 3
3 3 2 2 2

Sample Output 1

4

The possible sequences of the mountains' heights are:

<var>1, 3, 2, 2, 2</var>

<var>1, 3, 2, 1, 2</var>

<var>1, 3, 1, 2, 2</var>

<var>1, 3, 1, 1, 2</var>

for a total of four sequences.

Sample Input 2

5
1 1 1 2 2
3 2 1 1 1

Sample Output 2

0

The records are contradictory, since Mr. Takahashi recorded <var>2</var> as the highest peak after climbing all the mountains but Mr. Aoki recorded <var>3</var>.

Sample Input 3

10
1 3776 3776 8848 8848 8848 8848 8848 8848 8848
8848 8848 8848 8848 8848 8848 8848 8848 3776 5

Sample Output 3

884111967

Don't forget to compute the number modulo <var>10^9 + 7</var>.

Sample Input 4

1
17
17

Sample Output 4

1

Some mountain ranges consist of only one mountain.

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

    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    let xs: Vec<u64> = s.trim().split(' ').map(|x| x.parse().unwrap()).collect();

    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    let ys: Vec<u64> = s.trim().split(' ').map(|x| x.parse().unwrap()).collect();

    let mut tbs = vec![false; n];

    let mut p = 0;
    for i in 0..n {
        if p < xs[i] {
            tbs[i] = true;
            p = xs[i];
        }
    }

    let mut abs = vec![false; n];

    p = 0;
    for j in 1..(n + 1) {
        let i = n - j;

        if p < ys[i] {
            abs[i] = true;
            p = ys[i];
        }
    }

    let m = 1000000007;

    let mut r = 1;
    for i in 0..n {
        if tbs[i] && abs[i] && xs[i] != ys[i] {
            r = 0;
            break;
        } else if !tbs[i] && !abs[i] {
            r *= cmp::min(xs[i], ys[i]);
            r %= m;
        } else if tbs[i] != abs[i] && ((tbs[i] && xs[i] > ys[i]) || (abs[i] && ys[i] > xs[i])) {
            r = 0;
            break;
        }
    }

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


路線バスの時刻表

バスマニアの健次郎君は、Ａ市内のバスをよく利用しています。ある日ふと、健次郎君の家の前のバス停から出発するすべてのバスを写真に収めることを思い立ちました。このバス停には飯盛山行きと鶴ケ城行きの２つのバス路線が通ります。各路線の時刻表は手に入れましたが、１つの時刻表としてまとめた方がバス停で写真が撮りやすくなります。

健次郎君を助けるために、２つの路線の時刻表を、０時０分を基準として出発時刻が早い順に１つの時刻表としてまとめるプログラムを作成してください。

入力

入力は以下の形式で与えられる。

<var>N</var> <var>h</var>1 <var>m</var>1 <var>h</var>2 <var>m</var>2 ... <var>hN</var> <var>mN</var>
<var>M</var> <var>k</var>1 <var>g</var>1 <var>k</var>2 <var>g</var>2 ... <var>kM</var> <var>gM</var>

１行目に、飯盛山行きのバスの数を表す整数 <var>N</var> (1 ≤ <var>N</var> ≤ 100) と、それに続いて飯盛山行きのバス出発時刻が早い順に与えられる。出発時刻は整数 <var>hi</var> (0 ≤ <var>hi</var> ≤ 23) と <var>mi</var> (0 ≤ <var>mi</var> ≤ 59) からなり、<var>hi</var> 時 <var>mi</var> 分に <var>i</var> 番目のバスが出発することを表す。２行目に、鶴ケ城行きのバスの数を表す整数 <var>M</var> (1 ≤ <var>M</var> ≤ 100) と、それに続いて鶴ケ城行きのバス出発時刻が早い順に与えられる。出発時刻は整数 <var>ki</var> (0 ≤ <var>ki</var> ≤ 23) と <var>gi</var> (0 ≤ <var>gi</var> ≤ 59) からなり、<var>ki</var> 時 <var>gi</var> 分に <var>i</var> 番目のバスが出発することを表す。同じ路線には、同じ時刻に出発するバスはないものとする。

出力

２つの路線の時刻表を、０時０分を基準として出発時刻が早い順に１つにまとめた時刻表を１行に出力する。ただし、同じ時刻に複数のバスが出発するときは１つだけを出力する。出発時刻の時と分を : で区切る。分が１桁のときは左に０をひとつ加えて２桁で出力する。時刻と時刻の間は空白1 つで区切る。

入出力例

入力例１

2 9 8 15 59
1 8 27

出力例１

8:27 9:08 15:59

入力例２

2 0 0 21 0
3 7 30 21 0 23 7

出力例２

0:00 7:30 21:00 23:07

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

    let mut table = vec![];

    for line in lines.take(2) {
        let mut iter = line.split(' ').map(|s| s.parse::<u32>().unwrap());
        let n = iter.next().unwrap() as usize;

        table.reserve(n);

        for _ in 0..n {
            let (h, m) = (iter.next().unwrap(), iter.next().unwrap());
            table.push(h * 60 + m);
        }
    }

    table.sort();
    table.dedup();

    let mut res = String::with_capacity(5 * table.len());
    for v in table {
        write!(res, "{}:{:02} ", v / 60, v % 60);
    }
    println!("{}", res.trim_end());
}


The flag of Berland is such rectangular field n × m that satisfies following conditions:  Flag consists of three colors which correspond to letters 'R', 'G' and 'B'.  Flag consists of three equal in width and height stripes, parralel to each other and to sides of the flag. Each stripe has exactly one color.  Each color should be used in exactly one stripe. You are given a field n × m, consisting of characters 'R', 'G' and 'B'. Output "YES" (without quotes) if this field corresponds to correct flag of Berland. Otherwise, print "NO" (without quotes).

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut nums: Vec<u32> = buf
        .split_whitespace()
        .map(|c| c.parse::<u32>().unwrap())
        .collect();
    let width = nums.pop().unwrap();
    let height = nums.pop().unwrap();

    let mut buf = String::new();
    let mut flag: Vec<Vec<char>> = Vec::new();
    for _ in 0..height {
        io::stdin().read_line(&mut buf).unwrap();
        flag.push(buf.trim().chars().collect::<Vec<char>>());
        buf = String::new();
    }

    let mut colors: HashSet<char> = ['R', 'G', 'B'].iter().cloned().collect();
    let mut sizes: HashMap<char, u32> = [('R', 0), ('G', 0), ('B', 0)].iter().cloned().collect();
    let mut line_is_same = true;
    let mut color_is_onece = true;
    let mut curr_color = '_';
    for i in 0..height {
        let i = i as usize;
        let color = flag[i][0];
        if let Some(c) = sizes.get_mut(&color) {
            *c += 1;
        };

        for j in 1..width {
            let j = j as usize;
            if color != flag[i][j] {
                line_is_same = false;
                break;
            }
        }

        if curr_color != color {
            if !colors.remove(&color) {
                color_is_onece = false;
                break;
            }
            curr_color = color;
        }

        if !line_is_same || !color_is_onece {
            break;
        }
    }

    let sizes: HashSet<u32> = sizes.values().cloned().collect();

    if line_is_same && color_is_onece && sizes.len() == 1 {
        println!("YES");
        return;
    }

    let mut colors: HashSet<char> = ['R', 'G', 'B'].iter().cloned().collect();
    let mut sizes: HashMap<char, u32> = [('R', 0), ('G', 0), ('B', 0)].iter().cloned().collect();
    let mut line_is_same = true;
    let mut color_is_onece = true;
    let mut curr_color = '_';
    for i in 0..width {
        let i = i as usize;
        let color = flag[0][i];
        if let Some(c) = sizes.get_mut(&color) {
            *c += 1;
        };

        for j in 1..height {
            let j = j as usize;
            if color != flag[j][i] {
                line_is_same = false;
                break;
            }
        }

        if curr_color != color {
            if !colors.remove(&color) {
                color_is_onece = false;
                break;
            }
            curr_color = color;
        }

        if !line_is_same || !color_is_onece {
            break;
        }
    }

    let sizes: HashSet<u32> = sizes.values().cloned().collect();

    if line_is_same && color_is_onece && sizes.len() == 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}


Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

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

    let n_s_array: Vec<u32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|s| s.parse().unwrap())
        .collect();

    let a_array: Vec<i32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|s| s.parse().unwrap())
        .collect();

    let b_array: Vec<i32> = reader
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .split(' ')
        .map(|s| s.trim())
        .filter(|s| !s.is_empty())
        .map(|s| s.parse().unwrap())
        .collect();

    let n = (n_s_array[0] as usize) - 1;
    let s = (n_s_array[1] as usize) - 1;

    if a_array[0] == 0 {
        println!("NO");
        return;
    }

    if s == n {
        if a_array[n] == 0 {
            println!("NO");
            return;
        } else {
            println!("YES");
            return;
        }
    }

    if a_array[s] == 0 && b_array[s] == 0 {
        println!("NO");
        return;
    }

    if a_array[s] != 0 && b_array[s] != 0 {
        println!("YES");
        return;
    }

    if a_array[s] == 0 {
        for i in s..(n + 1) {
            if a_array[i] == 1 && b_array[i] == 1 {
                println!("YES");
                return;
            }
        }

        println!("NO");
        return;
    }

    println!("YES");
}


Problem Statement

We have <var>N</var> boxes, numbered <var>1</var> through <var>N</var>. At first, box <var>1</var> contains one red ball, and each of the other boxes contains one white ball.

Snuke will perform the following <var>M</var> operations, one by one. In the <var>i</var>-th operation, he randomly picks one ball from box <var>x_i</var>, then he puts it into box <var>y_i</var>.

Find the number of boxes that may contain the red ball after all operations are performed.

Constraints

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

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

<var>1≤x_i,y_i≤N</var>

<var>x_i≠y_i</var>

Just before the <var>i</var>-th operation is performed, box <var>x_i</var> contains at least <var>1</var> ball.

Input

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

<var>N</var> <var>M</var>
<var>x_1</var> <var>y_1</var>
<var>:</var>
<var>x_M</var> <var>y_M</var>

Output

Print the number of boxes that may contain the red ball after all operations are performed.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

2

Just after the first operation, box <var>1</var> is empty, box <var>2</var> contains one red ball and one white ball, and box <var>3</var> contains one white ball.

Now, consider the second operation. If Snuke picks the red ball from box <var>2</var>, the red ball will go into box <var>3</var>. If he picks the white ball instead, the red ball will stay in box <var>2</var>.
Thus, the number of boxes that may contain the red ball after all operations, is <var>2</var>.

Sample Input 2

3 3
1 2
2 3
2 3

Sample Output 2

1

All balls will go into box <var>3</var>.

Sample Input 3

4 4
1 2
2 3
4 1
3 4

Sample Output 3

3

int solution(void) {

  int n;
  int m;
  scanf("%d %d", &n, &m);
  int x[m];
  int y[m];
  for (int i = 0; i < m; i++) {
    scanf("%d %d", &x[i], &y[i]);
  }
  int box[n];
  for (int i = 0; i < n; i++) {
    box[i] = 1;
  }
  int red[n];
  red[0] = 1;
  for (int i = 1; i < n; i++) {
    red[i] = 0;
  }
  for (int i = 0; i < m; i++) {
    if (red[x[i] - 1] == 1) {
      if (box[x[i] - 1] == 1) {
        red[x[i] - 1] = 0;
      }
      red[y[i] - 1] = 1;
    }
    box[x[i] - 1]--;
    box[y[i] - 1]++;
  }
  int answer = 0;
  for (int i = 0; i < n; i++) {
    if (red[i] == 1) {
      answer++;
    }
  }
  printf("%d\n", answer);

  return 0;
}

fn solution() {
    let mut stdin = io::stdin();
    let mut lines = String::new();
    let _ = stdin.read_to_string(&mut lines);
    let vec = lines.lines().collect::<Vec<&str>>();
    let vec2 = vec[0].split(' ').collect::<Vec<&str>>();
    let n: usize = vec2[0].trim().parse().unwrap();
    let m: usize = vec2[1].trim().parse().unwrap();
    let mut xy: Vec<(usize, usize)> = Vec::new();
    for i in 0..m {
        let vec3 = vec[i + 1].split(' ').collect::<Vec<&str>>();
        xy.push((
            vec3[0].trim().parse::<usize>().unwrap() - 1,
            vec3[1].trim().parse::<usize>().unwrap() - 1,
        ));
    }
    let xy = xy;

    let mut is_red = vec![false; n];
    is_red[0] = true;
    let mut ball_num = vec![1; n];
    for (x, y) in xy {
        if is_red[x] {
            is_red[y] = true;
        }
        ball_num[x] -= 1;
        ball_num[y] += 1;
        if ball_num[x] == 0 {
            is_red[x] = false;
        }
    }
    let mut red_ball_num = 0;
    for i in 0..n {
        if is_red[i] {
            red_ball_num += 1;
        }
    }
    println!("{}", red_ball_num);
}


Score: <var>100</var> points

Problem Statement

In <var>2020</var>, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.

One day, there was an exam where a one-year-old child must write a program that prints Hello World, and a two-year-old child must write a program that receives integers <var>A, B</var> and prints <var>A+B</var>.

Takahashi, who is taking this exam, suddenly forgets his age.

He decides to write a program that first receives his age <var>N</var> (<var>1</var> or <var>2</var>) as input, then prints Hello World if <var>N=1</var>, and additionally receives integers <var>A, B</var> and prints <var>A+B</var> if <var>N=2</var>.

Write this program for him.

Constraints

<var>N</var> is <var>1</var> or <var>2</var>.

<var>A</var> is an integer between <var>1</var> and <var>9</var> (inclusive).

<var>B</var> is an integer between <var>1</var> and <var>9</var> (inclusive).

Input

Input is given from Standard Input in one of the following formats:

1

2
<var>A</var>
<var>B</var>

Output

If <var>N=1</var>, print Hello World; if <var>N=2</var>, print <var>A+B</var>.

Sample Input 1

1

Sample Output 1

Hello World

As <var>N=1</var>, Takahashi is one year old. Thus, we should print Hello World.

Sample Input 2

2
3
5

Sample Output 2

8

As <var>N=2</var>, Takahashi is two years old. Thus, we should print <var>A+B</var>, which is <var>8</var> since <var>A=3</var> and <var>B=5</var>.

int solution() {
  int number = 0;
  int A = 0;
  int B = 0;
  scanf("%d", &number);

  if (number == 1) {
    printf("Hello World");
  } else {
    scanf("%d%d", &A, &B);
    printf("%d", A + B);
  }

  return 0;
}

fn solution() {
    let scan = std::io::stdin();
    let mut line = String::new();
    let _ = scan.read_line(&mut line);
    line = line.trim_end().to_owned();

    if line == "1" {
        println!("Hello World");
    } else if line == "2" {
        let mut a_s = String::new();
        let _ = scan.read_line(&mut a_s);
        let mut b_s = String::new();
        let _ = scan.read_line(&mut b_s);
        let a = &a_s.trim_end().to_owned().parse::<i32>().unwrap();
        let b = &b_s.trim_end().to_owned().parse::<i32>().unwrap();
        println!("{}", a + b);
    }
}


Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play $$$t$$$ matches of a digit game...In each of $$$t$$$ matches of the digit game, a positive integer is generated. It consists of $$$n$$$ digits. The digits of this integer are numerated from $$$1$$$ to $$$n$$$ from the highest-order digit to the lowest-order digit. After this integer is announced, the match starts.Agents play in turns. Raze starts. In one turn an agent can choose any unmarked digit and mark it. Raze can choose digits on odd positions, but can not choose digits on even positions. Breach can choose digits on even positions, but can not choose digits on odd positions. The match ends, when there is only one unmarked digit left. If the single last digit is odd, then Raze wins, else Breach wins.It can be proved, that before the end of the match (for every initial integer with $$$n$$$ digits) each agent has an ability to make a turn, i.e. there is at least one unmarked digit, that stands on a position of required parity.For each of $$$t$$$ matches find out, which agent wins, if both of them want to win and play optimally.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int n;
    scanf("%d", &n);
    char s[n];
    scanf("%s", s);
    if (n & 1) {
      int ans = 0;
      for (int i = 0; i < n; i += 2) {
        int x = s[i] - '0';
        if (x & 1) {
          ans = 1;
          break;
        }
      }
      ans ? printf("1\n") : printf("2\n");
    } else {
      int ans = 0;
      for (int i = 1; i < n; i += 2) {
        int x = s[i] - '0';
        if (!(x & 1)) {
          ans = 1;
          break;
        }
      }
      ans ? printf("2\n") : printf("1\n");
    }
  }
}

fn solution() {
    let stdin = stdin();
    let mut lines = { stdin.lock().lines().map(|l| l.unwrap()) };

    let t: usize = lines.next().unwrap().parse().unwrap();
    let mut ds: Vec<usize> = Vec::new();
    let mut ns: Vec<Vec<u8>> = Vec::new();
    for i in 0..t {
        ds.push(lines.next().unwrap().parse().unwrap());

        let n = lines.next().unwrap();
        ns.push(Vec::new());
        for c in n.chars() {
            ns[i].push(c.to_digit(10).unwrap() as u8);
        }
    }

    for i in 0..t {
        let mut b_wins;
        if ds[i].is_multiple_of(2) {
            b_wins = false;
            for digit in ns[i].iter().skip(1).step_by(2) {
                if digit % 2 == 0 {
                    b_wins = true;
                    break;
                }
            }
        } else {
            b_wins = true;
            for digit in ns[i].iter().step_by(2) {
                if digit % 2 == 1 {
                    b_wins = false;
                    break;
                }
            }
        }
        if b_wins {
            println!("2");
        } else {
            println!("1");
        }
    }
}


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

int solution() {
  int re[3];
  int N = 0;
  re[1] = re[2] = 0;
  scanf("%d", &N);
  while (N--) {
    int tmp = 0;
    scanf("%d", &tmp);
    ++re[tmp];
  }
  int result = re[1];

  result = result > re[2] ? re[2] : result;

  result = result + (re[1] - result) / 3;
  printf("%d\n", result);
  return 0;
}

fn solution() {
    let mut input = String::new();
    use std::io::prelude::*;
    std::io::stdin().read_to_string(&mut input).unwrap();
    let mut it = input
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap());

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

    let mut d = [0; 2];

    for i in it.take(n) {
        match i {
            1 => d[0] += 1,
            2 => d[1] += 1,
            _ => panic!("Fail."),
        }
    }

    let ans = if d[0] >= d[1] {
        d[1] + (d[0] - d[1]) / 3
    } else {
        d[0]
    };

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


Score: <var>300</var> points

Problem Statement

AtCoder Mart sells <var>1000000</var> of each of the six items below:

Riceballs, priced at <var>100</var> yen (the currency of Japan) each

Sandwiches, priced at <var>101</var> yen each

Cookies, priced at <var>102</var> yen each

Cakes, priced at <var>103</var> yen each

Candies, priced at <var>104</var> yen each

Computers, priced at <var>105</var> yen each

Takahashi wants to buy some of them that cost exactly <var>X</var> yen in total.
Determine whether this is possible.

(Ignore consumption tax.)

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>X</var>

Output

If it is possible to buy some set of items that cost exactly <var>X</var> yen in total, print 1; otherwise, print 0.

Sample Input 1

615

Sample Output 1

1

For example, we can buy one of each kind of item, which will cost <var>100+101+102+103+104+105=615</var> yen in total.

Sample Input 2

217

Sample Output 2

0

No set of items costs <var>217</var> yen in total.

int solution() {
  int X = 0;
  int i = 0;
  int j = 0;
  int ans = 0;
  ;
  scanf("%d", &X);
  i = X / 100;
  j = X % 100;

  if (i * 5 >= j) {
    ans = 1;
  } else {
    ans = 0;
  }
  printf("%d\n", ans);
  return 0;
}

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

    let y: u32 = x / 100;
    let z: u32 = (x % 100).div_ceil(5);
    println!("{}", if y >= z { 1 } else { 0 });
}


Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

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

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

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

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

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

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

        let x = it.next().unwrap();
        let mut il = 0;
        let mut xl = x;
        let mut ih = 0;
        let mut xh = x;

        for (i, x) in it.enumerate() {
            let i = i + 1;
            if x < xl {
                xl = x;
                il = i;
            }
            if x > xh {
                xh = x;
                ih = i;
            }
        }

        let l = std::cmp::min(il, ih);
        let r = std::cmp::max(il, ih);

        let ans = [r + 1, n - 1 - l + 1, l + n - 1 - r + 2]
            .iter()
            .min()
            .cloned()
            .unwrap();

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


Score: <var>300</var> points

Problem Statement

In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc.

The pyramid had center coordinates <var>(C_X, C_Y)</var> and height <var>H</var>. The altitude of coordinates <var>(X, Y)</var> is <var>max(H - |X - C_X| - |Y - C_Y|, 0)</var>.

Aoki, an explorer, conducted a survey to identify the center coordinates and height of this pyramid. As a result, he obtained the following information:

<var>C_X, C_Y</var> was integers between <var>0</var> and <var>100</var> (inclusive), and <var>H</var> was an integer not less than <var>1</var>.

Additionally, he obtained <var>N</var> pieces of information. The <var>i</var>-th of them is: "the altitude of point <var>(x_i, y_i)</var> is <var>h_i</var>."

This was enough to identify the center coordinates and the height of the pyramid. Find these values with the clues above.

Constraints

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

<var>x_i</var> and <var>y_i</var> are integers between <var>0</var> and <var>100</var> (inclusive).

<var>h_i</var> is an integer between <var>0</var> and <var>10^9</var> (inclusive).

The <var>N</var> coordinates <var>(x_1, y_1), (x_2, y_2), (x_3, y_3), ..., (x_N, y_N)</var> are all different.

The center coordinates and the height of the pyramid can be uniquely identified.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>x_1</var> <var>y_1</var> <var>h_1</var>
<var>x_2</var> <var>y_2</var> <var>h_2</var>
<var>x_3</var> <var>y_3</var> <var>h_3</var>
<var>:</var>
<var>x_N</var> <var>y_N</var> <var>h_N</var>

Output

Print values <var>C_X, C_Y</var> and <var>H</var> representing the center coordinates and the height of the pyramid in one line, with spaces in between.

Sample Input 1

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

Sample Output 1

2 2 6

In this case, the center coordinates and the height can be identified as <var>(2, 2)</var> and <var>6</var>.

Sample Input 2

2
0 0 100
1 1 98

Sample Output 2

0 0 100

In this case, the center coordinates and the height can be identified as <var>(0, 0)</var> and <var>100</var>.

Note that <var>C_X</var> and <var>C_Y</var> are known to be integers between <var>0</var> and <var>100</var>.

Sample Input 3

3
99 1 191
100 1 192
99 0 192

Sample Output 3

100 0 193

In this case, the center coordinates and the height can be identified as <var>(100, 0)</var> and <var>193</var>.

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

  int p[n][3];
  for (int i = 0; i < n; i++) {
    int x;
    int y;
    int h;
    scanf("%d %d %d", &x, &y, &h);
    p[i][0] = x;
    p[i][1] = y;
    p[i][2] = h;
  }

  for (int i = 0; i <= 100; i++) {
    for (int j = 0; j <= 100; j++) {
      int ans_h = -1;
      int cnt = 0;
      int ok = 1;
      int q[n][3];
      for (int l = 0; l < n; l++) {
        int x = p[l][0];
        int y = p[l][1];
        int h = p[l][2];
        if (h == 0) {
          q[cnt][0] = x;
          q[cnt][1] = y;
          q[cnt][2] = h;
          cnt++;
          continue;
        }

        int tmp = abs(x - i) + abs(y - j) + h;

        if (tmp < 1) {
          ok = 0;
          break;
        }

        if (ans_h == -1) {
          ans_h = tmp;
          continue;
        }

        if (ans_h != tmp) {
          ok = 0;
          break;
        }
      }

      for (int k = 0; k < cnt; k++) {
        int x = q[k][0];
        int y = q[k][1];
        if ((ans_h - abs(x - i) - abs(y - j)) > 0) {
          ok = 0;
          break;
        }
      }
      if (ok) {
        printf("%d %d %d\n", i, j, ans_h);
        return 0;
      }
    }
  }

  return 0;
}

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

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

    let mut iter = buf.split_whitespace();
    let n: usize = iter.next().unwrap().parse().unwrap();
    let mut x = vec![0; n];
    let mut y = vec![0; n];
    let mut h = vec![0; n];
    for i in 0..n {
        x[i] = iter.next().unwrap().parse().unwrap();
        y[i] = iter.next().unwrap().parse().unwrap();
        h[i] = iter.next().unwrap().parse().unwrap();
    }

    let mut t = 0;
    for i in 0..n {
        if h[i] > 0 {
            t = i;
            break;
        }
    }

    for cx in 0..101 {
        for cy in 0..101 {
            let ch = h[t] + i32::abs(cx - x[t]) + i32::abs(cy - y[t]);
            let mut ok = true;
            for i in 0..n {
                let h2 = std::cmp::max(0, ch - (i32::abs(cx - x[i]) + i32::abs(cy - y[i])));
                if h2 != h[i] {
                    ok = false;
                    break;
                }
            }
            if ok {
                println!("{} {} {}", cx, cy, ch);
                return;
            }
        }
    }
}


Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly greater he throws it away and continues with the next one.The juicer has a special section to collect waste. It overflows if Kolya squeezes oranges of the total size strictly greater than d. When it happens Kolya empties the waste section (even if there are no more oranges) and continues to squeeze the juice. How many times will he have to empty the waste section?

int solution(void) {
  int n = 0;
  int p = 0;
  int d = 0;
  int o = 0;

  int counter1 = 0;

  int sum = 0;
  scanf("%d", &n);
  scanf("%d", &p);
  scanf("%d", &d);
  for (int i = 0; i < n; i++) {
    scanf("%d", &o);

    if (o <= p) {
      sum += o;
    }
    if ((sum > d)) {
      counter1++;
      sum = 0;
    }
  }

  printf("%d", counter1);

  return 0;
}

fn solution() {
    use std::io;
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let b;
    let d;
    {
        let mut ns = buf.split(" ").map(|str| str.trim().parse::<u32>().unwrap());
        ns.next();
        b = ns.next().unwrap();
        d = ns.next().unwrap();
    }
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let oranges = buf.split(" ").map(|str| str.trim().parse::<u32>().unwrap());
    let mut limit = d;
    let mut overflows = 0;
    for orange in oranges {
        if orange > b {
            continue;
        }
        let (n, overflowed) = limit.overflowing_sub(orange);
        if overflowed {
            limit = d;
            overflows += 1;
        } else {
            limit = n;
        }
    }
    println!("{}", overflows);
}


And where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi < qi and for all j < i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.

int solution() {
  int a;
  int b;
  scanf("%d %d\n", &a, &b);

  char c[a];
  char v[27];
  char min = 'z';
  char max = 'a';

  for (int i = 0; i < 27; i++) {
    v[i] = 0;
  }

  for (int i = 0; i < a; i++) {
    scanf("%c", &c[i]);
    if (c[i] < min) {
      min = c[i];
    }
    if (c[i] > max) {
      max = c[i];
    }
    v[(int)c[i] - 'a'] = 1;
  }

  if (b > a) {
    for (int i = 0; i < a; i++) {
      printf("%c", c[i]);
    }
    for (int i = 0; i < (b - a); i++) {
      printf("%c", min);
    }
  } else {
    for (int i = b - 1; i >= 0; i--) {
      if (c[i] != max) {
        int j = 1;
        while (!v[((int)c[i] - 'a' + j)]) {
          j++;
        }
        c[i] = (char)((int)c[i] + j);
        break;
      }
      c[i] = min;
    }
    for (int i = 0; i < b; i++) {
      printf("%c", c[i]);
    }
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    use std::io;
    use std::io::prelude::*;
    io::stdin().read_to_string(&mut input).unwrap();

    let mut it = input.split_whitespace();

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

    let s = it.next().unwrap().as_bytes();

    let mut set = [false; 26];

    for &b in s.iter() {
        set[(b - b'a') as usize] = true;
    }

    let first = set.iter().position(|&x| x).unwrap() as u8;
    let last = set.iter().rposition(|&x| x).unwrap() as u8;

    use std::cmp::Ordering;

    match n.cmp(&k) {
        Ordering::Less => {
            let mut ans = s.to_vec();
            for _ in n..k {
                ans.push(first + b'a');
            }
            let ans = std::str::from_utf8(&ans).unwrap();

            println!("{}", ans);
        }
        Ordering::Equal | Ordering::Greater => {
            let pos = s[..k].iter().rposition(|&b| b != last + b'a').unwrap();
            let mut ans = s[..k].to_vec();
            let b = ans[pos] - b'a';
            let next = set[b as usize..].iter().skip(1).position(|&x| x).unwrap() as u8 + b + 1;
            ans[pos] = next + b'a';
            for b in ans[pos..].iter_mut().skip(1) {
                *b = first + b'a';
            }
            let ans = std::str::from_utf8(&ans).unwrap();
            println!("{}", ans);
        }
    }
}


A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \le n \le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.

fn solution() {
    let stdin = stdin();
    let lockin = stdin.lock();
    let mut r = BufReader::new(lockin);

    let stdout = stdout();
    let lockout = stdout.lock();
    let mut w = BufWriter::new(lockout);

    let mut i = String::new();
    r.read_line(&mut i).expect("");

    for _ in 0..i.trim().parse::<u16>().unwrap() {
        let mut x = String::new();
        r.read_line(&mut x).expect("");
        x = x.trim().to_string();

        let mut n: Vec<String> = Vec::with_capacity(x.len());

        for (ii, xi) in x.chars().rev().enumerate() {
            if xi != '0' {
                n.push(format!("{}{}", xi, &"00000"[0..ii]));
            }
        }
        write!(w, "{}\n{}\n", n.len(), n.join(" ")).expect("");
    }
}


Score : <var>300</var> points

Problem Statement

Takahashi made <var>N</var> problems for competitive programming.
The problems are numbered <var>1</var> to <var>N</var>, and the difficulty of Problem <var>i</var> is represented as an integer <var>d_i</var> (the higher, the harder).

He is dividing the problems into two categories by choosing an integer <var>K</var>, as follows:

A problem with difficulty <var>K</var> or higher will be for ARCs.

A problem with difficulty lower than <var>K</var> will be for ABCs.

How many choices of the integer <var>K</var> make the number of problems for ARCs and the number of problems for ABCs the same?

Problem Statement

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

<var>N</var> is an even number.

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of choices of the integer <var>K</var> that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 1

6
9 1 4 4 6 7

Sample Output 1

2

If we choose <var>K=5</var> or <var>6</var>, Problem <var>1</var>, <var>5</var>, and <var>6</var> will be for ARCs, Problem <var>2</var>, <var>3</var>, and <var>4</var> will be for ABCs, and the objective is achieved.
Thus, the answer is <var>2</var>.

Sample Input 2

8
9 1 14 5 5 4 4 14

Sample Output 2

0

There may be no choice of the integer <var>K</var> that make the number of problems for ARCs and the number of problems for ABCs the same.

Sample Input 3

14
99592 10342 29105 78532 83018 11639 92015 77204 30914 21912 34519 80835 100000 1

Sample Output 3

42685

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

    let mut input = String::new();
    io::stdin().read_line(&mut input).ok();

    let mut v: Vec<usize> = Vec::new();
    for z in input.split_whitespace() {
        v.push(z.parse().unwrap());
    }

    let mut v2: Vec<usize> = Vec::new();
    v.sort();

    for z in 0..n {
        let buf;
        if z == 0 {
            buf = v[z];
        } else {
            buf = v[z] - v[z - 1];
        }

        v2.push(buf);
    }

    println!("{}", v2[n / 2]);
}


Score : <var>100</var> points

Problem Statement

Given a lowercase English letter <var>c</var>, determine whether it is a vowel. Here, there are five vowels in the English alphabet: a, e, i, o and u.

Constraints

<var>c</var> is a lowercase English letter.

Input

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

<var>c</var>

Output

If <var>c</var> is a vowel, print vowel. Otherwise, print consonant.

Sample Input 1

a

Sample Output 1

vowel

Since a is a vowel, print vowel.

Sample Input 2

z

Sample Output 2

consonant

Sample Input 3

s

Sample Output 3

consonant

int solution(void) {
  char str = 0;
  scanf("%c", &str);
  if (str == 'a' || str == 'i' || str == 'u' || str == 'e' || str == 'o') {
    printf("vowel");
  } else {
    printf("consonant");
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let s = s.trim();
    let set: HashSet<&str> = ["a", "e", "i", "o", "u"].iter().cloned().collect();

    println!(
        "{}",
        if set.contains(s) {
            "vowel"
        } else {
            "consonant"
        }
    );
}


B: 双子 (Twins)

とある双子は、自分たちのどちらが兄でどちらが弟かがあまり知られていないことに腹を立てた。

"ani" と入力されたら "square1001"、"otouto" と入力されたら "e869120" と出力するプログラムを作りなさい。

入力

入力として "ani" または "otouto" という文字列のどちらかが与えられます。

出力

"e869120" または "square1001" を、問題文の通りに出力してください。最後の改行を忘れないようにしましょう。

入力例1

ani

出力例1

square1001

入力例2

otouto

出力例2

e869120

int solution(void) {
  char nyuuryoku[128];
  if (scanf("%127s", nyuuryoku) != 1) {
    return 1;
  }
  if (strcmp(nyuuryoku, "ani") == 0) {
    puts("square1001");
  } else if (strcmp(nyuuryoku, "otouto") == 0) {
    puts("e869120");
  } else {
    puts("YOU ARE AN IDIOT!!!!!");
  }
  return 0;
}

fn solution() {
    input! {
      s : String,
    }
    if s == "ani" {
        println!("square1001")
    } else {
        println!("e869120")
    }
}


Score : <var>200</var> points

Problem Statement

There is a string <var>S</var> consisting of digits 1, 2, <var>...</var>, 9.
Lunlun, the Dachshund, will take out three consecutive digits from <var>S</var>, treat them as a single integer <var>X</var> and bring it to her master. (She cannot rearrange the digits.)

The master's favorite number is <var>753</var>. The closer to this number, the better.
What is the minimum possible (absolute) difference between <var>X</var> and <var>753</var>?

Constraints

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

Each character in <var>S</var> is 1, 2, <var>...</var>, or 9.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the minimum possible difference between <var>X</var> and <var>753</var>.

Sample Input 1

1234567876

Sample Output 1

34

Taking out the seventh to ninth characters results in <var>X = 787</var>, and the difference between this and <var>753</var> is <var>787 - 753 = 34</var>. The difference cannot be made smaller, no matter where <var>X</var> is taken from.

Note that the digits cannot be rearranged. For example, taking out 567 and rearranging it to 765 is not allowed.

We cannot take out three digits that are not consecutive from <var>S</var>, either. For example, taking out the seventh digit 7, the ninth digit 7 and the tenth digit 6 to obtain 776 is not allowed.

Sample Input 2

35753

Sample Output 2

0

If 753 itself can be taken out, the answer is <var>0</var>.

Sample Input 3

1111111111

Sample Output 3

642

No matter where <var>X</var> is taken from, <var>X = 111</var>, with the difference <var>753 - 111 = 642</var>.

fn solution() {
    let mut s = String::new();
    let t = 753;
    stdin().read_line(&mut s).unwrap();
    let s: Vec<_> = s.trim().chars().flat_map(|v| v.to_digit(10)).collect();
    let mut result = 753;
    for ((&a, &b), &c) in s.iter().zip(s.iter().skip(1)).zip(s.iter().skip(2)) {
        let mut v = a * 100 + b * 10 + c;
        if v > t {
            v -= t;
        } else {
            v = t - v;
        }
        if v < result {
            result = v;
        }
    }
    println!("{}", result);
}


Phoenix has $$$n$$$ coins with weights $$$2^1, 2^2, \dots, 2^n$$$. He knows that $$$n$$$ is even.He wants to split the coins into two piles such that each pile has exactly $$$\frac{n}{2}$$$ coins and the difference of weights between the two piles is minimized. Formally, let $$$a$$$ denote the sum of weights in the first pile, and $$$b$$$ denote the sum of weights in the second pile. Help Phoenix minimize $$$|a-b|$$$, the absolute value of $$$a-b$$$.

int solution() {
  int t;
  int n;
  int p = 0;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    p = pow(2, (n / 2) + 1) - 2;
    printf("%d\n", p);
  }
  return 0;
}

fn solution() {
    let mut input_str = String::new();
    io::stdin().read_line(&mut input_str).expect("err");
    let t = input_str.trim().parse::<u32>().unwrap();
    for _ in 0..t {
        input_str.clear();
        io::stdin().read_line(&mut input_str).expect("err");
        let n = input_str.trim().parse::<u32>().unwrap();
        let mut s1: i64 = 0;
        let mut s2: i64 = 0;
        for i in 0..n / 2 - 1 {
            s1 += 2 << i;
        }
        for i in n / 2 - 1..n - 1 {
            s2 += 2 << i;
        }
        s1 += 2 << (n - 1);
        println!("{}", (s2 - s1).abs())
    }
}


Score : <var>200</var> points

Problem Statement

You are given a image with a height of <var>H</var> pixels and a width of <var>W</var> pixels.
Each pixel is represented by a lowercase English letter.
The pixel at the <var>i</var>-th row from the top and <var>j</var>-th column from the left is <var>a_{ij}</var>.

Put a box around this image and output the result. The box should consist of # and have a thickness of <var>1</var>.

Constraints

<var>1 ≤ H, W ≤ 100</var>

<var>a_{ij}</var> is a lowercase English letter.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>a_{11}</var> <var>...</var> <var>a_{1W}</var>
<var>:</var>
<var>a_{H1}</var> <var>...</var> <var>a_{HW}</var>

Output

Print the image surrounded by a box that consists of # and has a thickness of <var>1</var>.

Sample Input 1

2 3
abc
arc

Sample Output 1

#####
#abc#
#arc#
#####

Sample Input 2

1 1
z

Sample Output 2

###
#z#
###

fn solution() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let split: Vec<&str> = input.as_str().split_whitespace().collect();

    let h: i64 = split[0].parse().unwrap();
    let w: i64 = split[1].parse().unwrap();

    for _n in 0..w + 2 {
        print!("#");
    }

    println!();

    for _n in 0..h {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let pict = input.as_str();
        println!("#{}#", pict.replace("\n", ""));
    }

    for _n in 0..w + 2 {
        print!("#");
    }
}


問題 2: 　投票 (Vote)

問題

20XX年に東京で世界的なスポーツ大会が開かれることになった．プログラミングコンテストはスポーツとして世界で楽しまれており，競技として採用される可能性がある．採用される競技を決める審査委員会について調べたところ，次のようなことが分かった．

審査委員会のために，候補となる N 個の競技を面白い方から順番に並べたリストが作成された．リストの上から i 番目には i 番目に面白い競技が書かれている．それを競技 i とする．さらに競技 i の開催に必要な費用 Ai が書かれている．

また，審査委員会は委員 1 から委員 M までの M 人の委員で構成されている．委員 j は自分の審査基準 Bj をもっており，開催に必要な費用が Bj 以下の競技のうち最も面白いものに 1 票を投票した．

どの委員の審査基準に対しても，少なくとも 1 つの競技は開催に必要な費用が審査基準以下であった．したがって，委員は全員 1 票を投票した．

最も多く票を獲得した競技は 1 つだけであった．

競技のリストと委員の情報が与えられたとき，最も多く票を獲得した競技の番号を求めるプログラムを作成せよ．

 入力

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

1 行目には整数 N, M  (1 ≤ N ≤ 1000，1 ≤ M ≤ 1000) が書かれており，それぞれ競技の数，委員の数を表す．

続く N 行のうちの i 行目 (1 ≤ i ≤ N) には整数 Ai (1 ≤ Ai ≤ 1000) が書かれており， 競技 i の開催に必要な費用 Ai を表す．

続く M 行のうちの j 行目 (1 ≤ j ≤ M) には整数 Bj (1 ≤ Bj ≤ 1000) が書かれており，委員 j の審査基準 Bj を表す．

与えられる入力データにおいては，どの委員も必ず 1 票を投票し，最も多く票を獲得した競技は 1 つであることが保証されている．

出力

最も多く票を獲得した競技の番号を 1 行で出力せよ．

入出力例

入力例 1

4 3
5
3
1
4
4
3
2

出力例 1

2

入出力例 1 では，競技は 4 つあり，委員は 3 人いる．リストの 4 つの競技にかかる費用はそれぞれ 5, 3, 1, 4 である．

委員 1 の審査基準は 4 である．費用が 4 以下の競技のうち最も面白いものは競技 2 である．

委員 2 の審査基準は 3 である．費用が 3 以下の競技のうち最も面白いものは競技 2 である．

委員 3 の審査基準は 2 である．費用が 2 以下の競技のうち最も面白いものは競技 3 である．

よって，競技 2 が 2 票，競技 3 が 1 票を獲得する．最も多く票を獲得した競技は競技 2 であるので，2 を出力する．

入力例 2

6 6
3
1
4
1
5
9
2
6
5
3
5
9

出力例 2

1

入出力例 2 では，競技 1 が 5 票，競技 2 が 1 票を獲得する．最も多く票を獲得した競技は競技 1 なので，1 を出力する．

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

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

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

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

    let mut list: Vec<(u32, u32)> = lines
        .by_ref()
        .take(n)
        .map(|l| (l.parse().unwrap(), 0))
        .collect();

    for line in lines.take(m) {
        let b = line.parse().unwrap();
        let &mut (_, ref mut n) = list.iter_mut().find(|&&mut (i, _)| i <= b).unwrap();
        *n += 1;
    }

    let (i, _) = list
        .into_iter()
        .enumerate()
        .max_by_key(|&(_, (_, n))| n)
        .unwrap();

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


Distance

  Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

  Four real numbers x1, y1, x2 and y2 are given in a line.

Output

  Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356

int solution() {
  double x1 = 0;
  double x2 = 0;
  double y1 = 0;
  double y2 = 0;
  double x = 0;
  double y = 0;

  scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2);
  x = (x2 - x1) * (x2 - x1);
  y = (y2 - y1) * (y2 - y1);

  printf("%lf\n", sqrt(x + y));

  return (0);
}

fn solution() {
    let handle = std::io::stdin();
    let mut s = String::new();
    handle.lock().read_line(&mut s).unwrap();
    let points: Vec<f64> = s.split_whitespace().map(|a| a.parse().unwrap()).collect();
    let (ax, ay, bx, by) = (points[0], points[1], points[2], points[3]);
    println!("{}", ((ax - bx).powi(2) + (ay - by).powi(2)).powf(0.5));
}


Little Dormi received a histogram with $$$n$$$ bars of height $$$a_1, a_2, \ldots, a_n$$$ for Christmas. However, the more he played with his new histogram, the more he realized its imperfections, so today he wanted to modify it to his liking.To modify the histogram, Little Dormi is able to perform the following operation an arbitrary number of times: Select an index $$$i$$$ ($$$1 \le i \le n$$$) where $$$a_i>0$$$, and assign $$$a_i := a_i-1$$$.Little Dormi defines the ugliness score of his histogram (after performing some number of operations) as the sum of the vertical length of its outline and the number of operations he performed on it. And to make the histogram as perfect as possible, he would like to minimize the ugliness score after modifying it with some number of operations.However, as his histogram is very large, Little Dormi is having trouble minimizing the ugliness score, so as Little Dormi's older brother, help him find the minimal ugliness.Consider the following example where the histogram has $$$4$$$ columns of heights $$$4,8,9,6$$$:  The blue region represents the histogram, and the red lines represent the vertical portion of the outline. Currently, the vertical length of the outline is $$$4+4+1+3+6 = 18$$$, so if Little Dormi does not modify the histogram at all, the ugliness would be $$$18$$$.However, Little Dormi can apply the operation once on column $$$2$$$ and twice on column $$$3$$$, resulting in a histogram with heights $$$4,7,7,6$$$:  Now, as the total vertical length of the outline (red lines) is $$$4+3+1+6=14$$$, the ugliness is $$$14+3=17$$$ dollars. It can be proven that this is optimal.

int solution() {
  long long int testcases;
  scanf("%lld", &testcases);
  while (testcases--) {
    long long int n;
    scanf("%lld", &n);
    long long int arrrr[n + 2];
    arrrr[0] = 0;
    arrrr[n + 1] = 0;
    for (int i = 1; i <= n; i++) {
      scanf("%lld", &arrrr[i]);
    }
    long long int count = 0;
    for (long long int i = 1; i <= n; i++) {
      if (arrrr[i] > arrrr[i - 1] && arrrr[i] > arrrr[i + 1]) {
        if (arrrr[i - 1] > arrrr[i + 1]) {
          count = count + arrrr[i] - arrrr[i - 1];
          arrrr[i] = arrrr[i - 1];
        } else {
          count = count + arrrr[i] - arrrr[i + 1];
          arrrr[i] = arrrr[i + 1];
        }
      }
    }
    for (long long int i = 1; i <= n + 1; i++) {
      if (arrrr[i] - arrrr[i - 1] >= 0) {
        count += (arrrr[i] - arrrr[i - 1]);
      } else {
        count += (arrrr[i - 1] - arrrr[i]);
      }
    }
    printf("%lld\n", count);
  }
  return 0;
}

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

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

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

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

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

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

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

        let mut ans = 0u64;
        let mut x = 0;
        let mut y = 0;

        for z in it.chain(std::iter::once(0)) {
            let o = z.abs_diff(y);

            ans += o;
            if x < y && z < y {
                let m = std::cmp::max(x, z);
                ans -= y - m;
            }
            x = y;
            y = z;
        }

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


Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins.Vasiliy plans to buy his favorite drink for q consecutive days. He knows, that on the i-th day he will be able to spent mi coins. Now, for each of the days he want to know in how many different shops he can buy a bottle of "Beecola".

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

    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();

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

    x.sort();

    let mut q = String::new();
    stdin().read_line(&mut q).unwrap();
    let q: i32 = q.trim().parse().unwrap();

    for _ in 0..q {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let line: i32 = line.trim().parse().unwrap();

        let mut min: i32 = -1;
        let mut max = n;

        while max - min > 1 {
            let current = (min + max) / 2;
            if x[current as usize] > line {
                max = current;
            } else {
                min = current;
            }
        }

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


Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.

int solution() {
  char a[101][101];
  int n;
  int m;
  scanf("%d %d", &n, &m);
  int minx = m;
  int miny = n;
  int maxx = 0;
  int maxy = 0;
  int count = 0;
  for (int i = 0; i < n; i++) {
    scanf("%s", a[i]);
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (a[i][j] == 'B') {

        if (i >= maxy) {
          maxy = i;
        }
        if (j >= maxx) {
          maxx = j;
        }
        if (i <= miny) {
          miny = i;
        }
        if (j <= minx) {
          minx = j;
        }
        count++;
      }
    }
  }
  if (count == 0) {
    printf("1\n");
    return 0;
  }

  int length = maxx - minx + 1;
  int breadth = maxy - miny + 1;
  int side = (length > breadth) ? length : breadth;
  if (side > n || side > m) {
    printf("-1\n");
  } else {
    printf("%d\n", (side * side) - count);
  }
}

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

    let br = BufReader::new(stdin());

    let arr = br
        .lines()
        .map(|l| {
            l.unwrap()
                .chars()
                .map(|c| match c {
                    'W' => false,
                    'B' => true,
                    _ => panic!("HEEEEELP!!!"),
                })
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();

    let cnt: usize = arr.iter().map(|v| v.iter().filter(|&b| *b).count()).sum();

    if cnt == 0 {
        println!("{}", 1);
    } else {
        let max_x = arr
            .iter()
            .filter_map(|row| {
                row.iter()
                    .enumerate()
                    .filter_map(|(i, &b)| if b { Some(i) } else { None })
                    .max()
            })
            .max()
            .unwrap();
        let min_x = arr
            .iter()
            .filter_map(|row| {
                row.iter()
                    .enumerate()
                    .filter_map(|(i, &b)| if b { Some(i) } else { None })
                    .min()
            })
            .min()
            .unwrap();
        let max_y = arr
            .iter()
            .enumerate()
            .filter_map(|(i, row)| {
                row.iter()
                    .filter_map(|&b| if b { Some(i) } else { None })
                    .max()
            })
            .max()
            .unwrap();
        let min_y = arr
            .iter()
            .enumerate()
            .filter_map(|(i, row)| {
                row.iter()
                    .filter_map(|&b| if b { Some(i) } else { None })
                    .min()
            })
            .min()
            .unwrap();

        let max = max(max_x - min_x, max_y - min_y) + 1;

        if max > min(n, m) {
            println!("-1");
        } else {
            println!("{}", max.pow(2) - cnt);
        }
    }
}


Score : <var>400</var> points

Problem Statement

Takahashi has <var>N</var> sticks that are distinguishable from each other. The length of the <var>i</var>-th stick is <var>L_i</var>.

He is going to form a triangle using three of these sticks. Let <var>a</var>, <var>b</var>, and <var>c</var> be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

<var>a < b + c</var>

<var>b < c + a</var>

<var>c < a + b</var>

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

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

<var>1 \leq L_i \leq 10^3</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>L_1</var> <var>L_2</var> <var>...</var> <var>L_N</var>

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23

int solution(void) {
  int N;
  int L[2000];
  scanf("%d", &N);
  for (int i = 0; i < N; i++) {
    scanf("%d", &L[i]);
  }
  int count = 0;
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < i; j++) {
      for (int k = 0; k < j; k++) {
        if (L[i] < L[j] + L[k] && L[j] < L[k] + L[i] && L[k] < L[i] + L[j]) {
          ++count;
        }
      }
    }
  }
  printf("%d\n", count);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let _n: usize = iter.next().unwrap().parse().unwrap();

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

    l_s.sort();

    let mut ans = 0usize;

    for a in 0..l_s.len() {
        for b in (a + 1)..l_s.len() {
            let c_over = l_s[a] + l_s[b];

            let mut l = b;
            let mut r = l_s.len();
            let mut mid = (l + r) / 2;

            while r - l > 1 {
                if l_s[mid] < c_over {
                    l = mid;
                } else {
                    r = mid;
                }
                mid = (l + r) / 2;
            }

            ans += mid - b;
        }
    }

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


Let's denote as  the number of bits set ('1' bits) in the binary representation of the non-negative integer x.You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and  is maximum possible. If there are multiple such numbers find the smallest of them.

int solution(void) {
  int n = 0;
  long long l = 0;
  long long r = 0;

  scanf("%d", &n);

  while (n--) {
    scanf("%lli %lli", &l, &r);

    while ((l | (l + 1)) <= r) {
      l = l | (l + 1);
    }
    printf("%lli\n", l);
  }

  return 0;
}

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

    for _ in 0..n {
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read input");
        let mut input = input
            .split_whitespace()
            .map(|n| n.parse::<u64>().expect("invalid input"));
        let l = input.next().unwrap();
        let r = input.next().unwrap();

        let mut inc = 1;
        let mut result = l;
        while result | inc <= r {
            result |= inc;
            inc <<= 1;
        }
        println!("{}", result);
    }
}


PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $$$6$$$ slices, medium ones consist of $$$8$$$ slices, and large pizzas consist of $$$10$$$ slices each. Baking them takes $$$15$$$, $$$20$$$ and $$$25$$$ minutes, respectively.Petya's birthday is today, and $$$n$$$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least $$$n$$$ slices in total. For example:   if $$$12$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$12$$$ slices in total. He can order two small pizzas, containing exactly $$$12$$$ slices, and the time to bake them is $$$30$$$ minutes;  if $$$15$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$15$$$ slices in total. He can order a small pizza and a large pizza, containing $$$16$$$ slices, and the time to bake them is $$$40$$$ minutes;  if $$$300$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$300$$$ slices in total. He can order $$$15$$$ small pizzas, $$$10$$$ medium pizzas and $$$13$$$ large pizzas, in total they contain $$$15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300$$$ slices, and the total time to bake them is $$$15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750$$$ minutes;  if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $$$15$$$ minutes.

int solution() {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    long long int n = 0;
    scanf("%lld", &n);
    if (n <= 6) {
      printf("15\n");
      continue;
    }
    if (n % 2 == 0) {
      printf("%lld\n", (n / 2) * 5);
    } else {
      printf("%lld\n", ((n / 2) + 1) * 5);
    }
  }
  return 0;
}

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

    io::stdin()
        .read_line(&mut inPut)
        .expect("Failed to read line");
    let mut inPutInt: i32 = inPut.trim().parse().unwrap();
    inPut.clear();
    let mut out: i128 = 0;
    while inPutInt != 0 {
        io::stdin()
            .read_line(&mut inPut)
            .expect("Failed to read line");

        let mut frens: i128 = inPut.trim().parse().unwrap();
        inPut.clear();
        inPutInt -= 1;

        if frens < 6 {
            out = 15
        } else {
            frens = (frens + frens % 2) / 2;
            out = frens * 5;
        }
        println!("{}", out);
    }
}


void solution(int *arr, int size) {
  int i, j;

  for (i = 0; i < size - 1; i++) {
    bool swapped = false;

    for (j = 0; j < size - 1 - i; j++) {

      if (arr[j] > arr[j + 1]) {
        int temp;

        temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;

        swapped = true;
      }
    }

    if (!swapped) {
      break;
    }
  }
}

fn solution<T: Ord>(arr: &mut [T]) {
    if arr.is_empty() {
        return;
    }
    let mut sorted = false;
    let mut n = arr.len();
    while !sorted {
        sorted = true;
        for i in 0..n - 1 {
            if arr[i] > arr[i + 1] {
                arr.swap(i, i + 1);
                sorted = false;
            }
        }
        n -= 1;
    }
}


void solution(char *str, char *pattern) {
  int n = strlen(str);
  int m = strlen(pattern);

  if (m == 0 || n == 0 || m > n)
    return;

  int shift = 0;

  int bad_char[256];

  for (int i = 0; i < 256; i++)
    bad_char[i] = -1;

  for (int i = 0; i < m; i++)
    bad_char[(unsigned char)pattern[i]] = i;

  while (shift <= (n - m)) {
    int j = m - 1;

    while (j >= 0 && pattern[j] == str[shift + j])
      j--;

    if (j < 0) {
      printf("--Pattern is found at: %d\n", shift);

      if (shift + m < n)
        shift += m - bad_char[(unsigned char)str[shift + m]];
      else
        shift += 1;
    } else {
      int bad_shift = j - bad_char[(unsigned char)str[shift + j]];

      shift += (bad_shift > 1) ? bad_shift : 1;
    }
  }
}

fn solution(text: &str, pat: &str) -> Vec<usize> {
    let mut positions = Vec::new();

    let text_len = text.len() as isize;
    let pat_len = pat.len() as isize;

    if text_len == 0 || pat_len == 0 || pat_len > text_len {
        return positions;
    }

    let text: Vec<char> = text.chars().collect();
    let pat: Vec<char> = pat.chars().collect();

    let mut bad_char_table = HashMap::new();
    for (i, &ch) in pat.iter().enumerate() {
        bad_char_table.insert(ch, i as isize);
    }

    let mut shift = 0;

    while shift <= text_len - pat_len {
        let mut j = pat_len - 1;

        while j >= 0 && pat[j as usize] == text[(shift + j) as usize] {
            j -= 1;
        }

        if j < 0 {
            positions.push(shift as usize);

            if shift + pat_len >= text_len {
                shift += 1;
            } else {
                let next_ch = text[(shift + pat_len) as usize];
                shift += pat_len - bad_char_table.get(&next_ch).unwrap_or(&-1);
            }
        } else {
            let mis_ch = text[(shift + j) as usize];
            let bad_char_shift = bad_char_table.get(&mis_ch).unwrap_or(&-1);

            shift += std::cmp::max(1, j - bad_char_shift);
        }
    }

    positions
}


Score : <var>200</var> points

Problem Statement

A string is called a KEYENCE string when it can be changed to keyence by removing its contiguous substring (possibly empty) only once.

Given a string <var>S</var> consisting of lowercase English letters, determine if <var>S</var> is a KEYENCE string.

Constraints

The length of <var>S</var> is between <var>7</var> and <var>100</var> (inclusive).

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

If <var>S</var> is a KEYENCE string, print YES; otherwise, print NO.

Sample Input 1

keyofscience

Sample Output 1

YES

keyence is an abbreviation of key of science.

Sample Input 2

mpyszsbznf

Sample Output 2

NO

Sample Input 3

ashlfyha

Sample Output 3

NO

Sample Input 4

keyence

Sample Output 4

YES

fn solution() {
    let mut buf = String::new();
    let handle = std::io::stdin();
    handle.read_line(&mut buf).unwrap();
    let s: String = buf.trim().to_string();
    let k: String = "keyence".to_string();
    let _k_index: Vec<usize> = vec![];

    let mut left = 0;
    let mut right = s.len() - k.len();
    let mut find = false;
    loop {
        let mut target = s[0..left].to_string();
        target.push_str(&s[right..]);
        if target == k {
            find = true;
            break;
        }
        if right == s.len() {
            break;
        }
        left += 1;
        right += 1;
    }
    if find {
        println!("YES");
    } else {
        println!("NO");
    }
}


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. Recall that sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Find three indices $$$i$$$, $$$j$$$ and $$$k$$$ such that:   $$$1 \le i < j < k \le n$$$;  $$$p_i < p_j$$$ and $$$p_j > p_k$$$.  Or say that there are no such indices.

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

  for (int i = 0; i < n; i++) {
    int flag = 0;
    int size = 0;
    scanf("%d", &size);
    int ind[size];
    for (int j = 0; j < size; j++) {
      scanf("%d", &ind[j]);
    }
    for (int j = 1; j < size - 1; j++) {
      if (ind[j] > ind[j + 1] && ind[j] > ind[j - 1]) {
        printf("Yes\n%d %d %d\n", j, j + 1, j + 2);
        flag = 1;
        break;
      }
    }
    if (flag == 0) {
      printf("NO\n");
    }
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut count: i16 = line.trim().parse().unwrap();
    while count > 0 {
        input.read_line(&mut line).unwrap();
        line.clear();
        input.read_line(&mut line).unwrap();
        let mut value = i16::MAX;
        let mut first: i16 = 0;
        let mut index: i16 = 0;
        for number in line.split_whitespace() {
            index += 1;
            let number: i16 = number.parse().unwrap();
            if first == 0 {
                if number > value {
                    first = index - 1;
                }
                value = number;
            } else {
                if number < value {
                    println!("YES\n{} {} {}", first, index - 1, index);
                    first = -1;
                    break;
                }
                value = number;
            }
        }
        if first != -1 {
            println!("NO");
        }
        count -= 1;
    }
}


You are given a string $$$s$$$. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?

fn solution() -> io::Result<()> {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;
    let input = input.trim();

    for line in input.lines().skip(1) {
        let mut erased_0 = 0;
        let mut flag = false;
        let mut prev_digit = '0';
        let line = line.trim_matches('0');
        for digit in line.chars() {
            if flag {
                if digit == '0' {
                    erased_0 += 1;
                } else {
                    flag = false;
                }
            } else if prev_digit == '1' && digit == '0' {
                erased_0 += 1;
                flag = true;
            }
            prev_digit = digit;
        }
        println!("{}", erased_0);
    }

    Ok(())
}


A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large).Killjoy's account is already infected and has a rating equal to $$$x$$$. Its rating is constant. There are $$$n$$$ accounts except hers, numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th account's initial rating is $$$a_i$$$. Any infected account (initially the only infected account is Killjoy's) instantly infects any uninfected account if their ratings are equal. This can happen at the beginning (before any rating changes) and after each contest. If an account is infected, it can not be healed.Contests are regularly held on Codeforces. In each contest, any of these $$$n$$$ accounts (including infected ones) can participate. Killjoy can't participate. After each contest ratings are changed this way: each participant's rating is changed by an integer, but the sum of all changes must be equal to zero. New ratings can be any integer.Find out the minimal number of contests needed to infect all accounts. You can choose which accounts will participate in each contest and how the ratings will change.It can be proven that all accounts can be infected in some finite number of contests.

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

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

    handle.read_line(&mut buf).unwrap();
    let tests: i64 = buf.trim().parse().unwrap();

    for _test in 0..tests {
        buf.clear();
        handle.read_line(&mut buf).unwrap();
        let mut input = buf.split_whitespace();
        input.next();
        let joy: i64 = input.next().unwrap().parse().unwrap();

        buf.clear();
        handle.read_line(&mut buf).unwrap();
        let maj: Vec<i64> = buf.split_whitespace().map(|x| x.parse().unwrap()).collect();

        let mut An = 0;
        let mut Bn = 0;
        let mut Btotal = 0i64;
        for one in maj {
            if one == joy {
                An += 1;
            } else {
                Bn += 1;
                Btotal += one;
            }
        }

        println!(
            "{}",
            if Bn == 0 {
                0
            } else if An != 0 || Btotal % Bn == 0 && Btotal / Bn == joy {
                1
            } else {
                2
            }
        );
    }
}