You are given a rooted tree consisting of $$$n$$$ vertices. Vertices are numbered from $$$1$$$ to $$$n$$$. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of ancestors $$$b$$$ containing $$$n$$$ numbers: $$$b_i$$$ is an ancestor of the vertex with the number $$$i$$$. The ancestor of a vertex $$$u$$$ is a vertex that is the next vertex on a simple path from $$$u$$$ to the root. For example, on the simple path from $$$5$$$ to $$$3$$$ (the root), the next vertex would be $$$1$$$, so the ancestor of $$$5$$$ is $$$1$$$.The root has no ancestor, so for it, the value of $$$b_i$$$ is $$$i$$$ (the root is the only vertex for which $$$b_i=i$$$).For example, if $$$n=5$$$ and $$$b=[3, 1, 3, 3, 1]$$$, then the tree looks like this.    An example of a rooted tree for $$$n=5$$$, the root of the tree is a vertex number $$$3$$$. You are given an array $$$p$$$ — a permutation of the vertices of the tree. If it is possible, assign any positive integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation $$$p$$$.In other words, for a given permutation of vertices $$$p$$$, it is necessary to choose such edge weights so that the condition $$$dist[p_i]<dist[p_{i+1}]$$$ is true for each $$$i$$$ from $$$1$$$ to $$$n-1$$$. $$$dist[u]$$$ is a sum of the weights of the edges on the path from the root to $$$u$$$. In particular, $$$dist[u]=0$$$ if the vertex $$$u$$$ is the root of the tree.For example, assume that $$$p=[3, 1, 2, 5, 4]$$$. In this case, the following edge weights satisfy this permutation:  the edge ($$$3, 4$$$) has a weight of $$$102$$$;  the edge ($$$3, 1$$$) has weight of $$$1$$$;  the edge ($$$1, 2$$$) has a weight of $$$10$$$;  the edge ($$$1, 5$$$) has a weight of $$$100$$$. The array of distances from the root looks like: $$$dist=[1,11,0,102,101]$$$. The vertices sorted by increasing the distance from the root form the given permutation $$$p$$$.Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them.

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

    int parent[n + 1];
    int order[n + 1];
    int weight[n + 1];
    int tot_weight[n + 1];
    order[0] = -100;
    parent[0] = -100;
    weight[0] = -100;
    for (j = 1; j <= n; j++) {
      scanf("%d", &parent[j]);
    }
    for (j = 1; j <= n; j++) {
      scanf("%d", &order[j]);
    }
    for (j = 1; j <= n; j++) {
      weight[j] = -1;
      tot_weight[j] = -1;
    }
    int root = order[1];

    weight[root] = 0;
    tot_weight[root] = 0;
    int curr_weight = 0;
    int prev_weight = 0;
    int k;
    int ans = 0;
    for (j = 2; j <= n; j++) {
      prev_weight = curr_weight;
      curr_weight = 0;
      k = parent[order[j]];

      if (weight[k] == -1) {
        ans = -1;
        break;
      }
      curr_weight = tot_weight[k];

      if (curr_weight >= prev_weight) {
        weight[order[j]] = 1;
        curr_weight++;
        tot_weight[order[j]] = curr_weight;
      } else {
        weight[order[j]] = prev_weight - curr_weight + 1;
        curr_weight = prev_weight + 1;
        tot_weight[order[j]] = curr_weight;
      }
    }
    if (ans == 0) {
      for (j = 1; j <= n; j++) {
        printf("%d ", weight[j]);
      }
    } else {
      printf("-1");
    }
    printf("\n");
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let b: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse::<usize>().unwrap() - 1)
            .collect();
        let p: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse::<usize>().unwrap() - 1)
            .collect();
        let root = b.iter().enumerate().find(|&(i, &x)| i == x).unwrap().0;
        let mut d: Vec<Option<usize>> = vec![None; n];
        if root != p[0] {
            println!("-1");
            continue;
        }
        d[root] = Some(0);
        let mut is_valid = true;
        for i in 1..n {
            let u = p[i];
            let par = b[u];
            if d[par].is_some() {
                d[u] = Some(i);
            } else {
                is_valid = false;
                break;
            }
        }
        if is_valid {
            for i in 0..n {
                let w = d[i].unwrap() - d[b[i]].unwrap();
                print!("{} ", w);
            }
            println!();
        } else {
            println!("-1");
        }
    }
}


Score : <var>200</var> points

Problem Statement

Niwango created a playlist of <var>N</var> songs.
The title and the duration of the <var>i</var>-th song are <var>s_i</var> and <var>t_i</var> seconds, respectively.
It is guaranteed that <var>s_1,\ldots,s_N</var> are all distinct.

Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, without any pause in between.)
However, he fell asleep during his work, and he woke up after all the songs were played.
According to his record, it turned out that he fell asleep at the very end of the song titled <var>X</var>.

Find the duration of time when some song was played while Niwango was asleep.

Constraints

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

<var>s_i</var> and <var>X</var> are strings of length between <var>1</var> and <var>100</var> (inclusive) consisting of lowercase English letters.

<var>s_1,\ldots,s_N</var> are distinct.

There exists an integer <var>i</var> such that <var>s_i = X</var>.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>s_1</var> <var>t_1</var>
<var>\vdots</var>
<var>s_{N}</var> <var>t_N</var>
<var>X</var>

Output

Print the answer.

Sample Input 1

3
dwango 2
sixth 5
prelims 25
dwango

Sample Output 1

30

While Niwango was asleep, two songs were played: sixth and prelims.

The answer is the total duration of these songs, <var>30</var>.

Sample Input 2

1
abcde 1000
abcde

Sample Output 2

0

No songs were played while Niwango was asleep.

In such a case, the total duration of songs is <var>0</var>.

Sample Input 3

15
ypnxn 279
kgjgwx 464
qquhuwq 327
rxing 549
pmuduhznoaqu 832
dagktgdarveusju 595
wunfagppcoi 200
dhavrncwfw 720
jpcmigg 658
wrczqxycivdqn 639
mcmkkbnjfeod 992
htqvkgkbhtytsz 130
twflegsjz 467
dswxxrxuzzfhkp 989
szfwtzfpnscgue 958
pmuduhznoaqu

Sample Output 3

6348

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

  char s[n][100];
  int t[n];
  for (int i = 0; i < n; i++) {
    scanf("%s %d\n", s[i], &t[i]);
  }

  char x[100];
  scanf("%s\n", x);

  int flag = 0;
  int sum = 0;
  for (int i = 0; i < n; i++) {
    if (flag == 1) {
      sum += t[i];
    }
    if (strcmp(x, s[i]) == 0) {
      flag = 1;
    }
  }

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

  return (0);
}

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let st: Vec<_> = (0..n)
        .map(|_| (s.next().unwrap(), s.next().unwrap().parse::<i32>().unwrap()))
        .collect();
    let x = s.next().unwrap();
    let ans = st
        .iter()
        .fold((0, false), |r, &(s, t)| {
            if r.1 {
                (r.0 + t, true)
            } else {
                (r.0, s == x)
            }
        })
        .0;
    println!("{}", ans);
}


A: 丸付け

問題

AORイカちゃんはテストに合格するため勉強しています。

AORイカちゃんは、 $N$ 問、問題を解きました。
その後、解いた問題の丸付けを以下の手順で行います。

解答の正誤を確認する。

解答が正しい場合はマル印、誤っていた場合はバツ印を解答用紙に書き込む。

解答が $2$ 問連続で誤りであるとわかった瞬間、テストに不合格になってしまう恐怖から、AORイカちゃんは失神してしまいます。そして、それ以降丸付けを行うことはできません。

失神は手順 $1$ と $2$ の間で起こります。

AORイカちゃんが解いた問題の数を表す整数 $N$ と、解答の正誤を表した長さ $N$ の文字列 $S$ が与えられます。
文字列は 'o' と 'x' からなり、 'o' は解答が正しく、 'x' は解答が誤りであることを表しています。
 $i$ 文字目が $i$ 問目の正誤を表しており、AORイカちゃんは $1$ 問目から順番に丸付けを行います。

AORイカちゃんが正誤を書き込めた問題数を出力してください。

制約

$1 \leq N \leq 10^5$

入力形式

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

$N$

$S$

出力

AORイカちゃんが正誤を書き込めた問題数を $1$ 行で出力せよ。また、末尾に改行も出力せよ。

サンプル

サンプル入力 1

3
oxx

サンプル出力 1

2

 $3$ 問目の手順 $1$ を行うと失神するため、手順 $2$ は行えません。

サンプル入力 2

8
oxoxoxox

サンプル出力 2

8

サンプル入力 3

4
xxxx

サンプル出力 3

1

int solution() {
  char mozi[100000];
  int i;
  int n;
  int count = 0;

  scanf("%d", &n);
  scanf("%s", mozi);

  for (i = 0; i < n; i++) {
    count++;
    if (mozi[i] == 'x' && mozi[i + 1] == 'x') {
      printf("%d\n", count);
      return 0;
    }
  }
  printf("%d\n", count);
  return 0;
}

fn solution() {
    input!(N:usize,S:chars);
    let mut S: Vec<char> = S;
    S.push('x');
    S.push('x');
    let mut ans = 0;
    let mut flag = false;
    for i in 0..N {
        if S[i] == 'x' {
            if flag {
                break;
            }
            flag = true;
        } else {
            flag = false;
        }
        ans += 1;
    }
    println!("{}", ans);
}


Score : <var>400</var> points

Problem Statement

Takahashi has a string <var>S</var> consisting of lowercase English letters.

Starting with this string, he will produce a new one in the procedure given as follows.

The procedure consists of <var>Q</var> operations. In Operation <var>i</var> <var>(1 \leq i \leq Q)</var>, an integer <var>T_i</var> is provided, which means the following:

If <var>T_i = 1</var>: reverse the string <var>S</var>.

If <var>T_i = 2</var>: An integer <var>F_i</var> and a lowercase English letter <var>C_i</var> are additionally provided.

If <var>F_i = 1</var> : Add <var>C_i</var> to the beginning of the string <var>S</var>.

If <var>F_i = 2</var> : Add <var>C_i</var> to the end of the string <var>S</var>.

Help Takahashi by finding the final string that results from the procedure.

Constraints

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

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

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

<var>T_i = 1</var> or <var>2</var>.

<var>F_i = 1</var> or <var>2</var>, if provided.

<var>C_i</var> is a lowercase English letter, if provided.

Input

Input is given from Standard Input in the following format:

<var>S</var>
<var>Q</var>
<var>Query_1</var>
<var>:</var>
<var>Query_Q</var>

In the <var>3</var>-rd through the <var>(Q+2)</var>-th lines, <var>Query_i</var> is one of the following:

<var>1</var>

which means <var>T_i = 1</var>, and:

<var>2</var> <var>F_i</var> <var>C_i</var>

which means <var>T_i = 2</var>.

Output

Print the resulting string.

Sample Input 1

a
4
2 1 p
1
2 2 c
1

Sample Output 1

cpa

There will be <var>Q = 4</var> operations. Initially, <var>S</var> is a.

Operation <var>1</var>: Add p at the beginning of <var>S</var>. <var>S</var> becomes pa.

Operation <var>2</var>: Reverse <var>S</var>. <var>S</var> becomes ap.

Operation <var>3</var>: Add c at the end of <var>S</var>. <var>S</var> becomes apc.

Operation <var>4</var>: Reverse <var>S</var>. <var>S</var> becomes cpa.

Thus, the resulting string is cpa.

Sample Input 2

a
6
2 2 a
2 1 b
1
2 2 c
1
1

Sample Output 2

aabc

There will be <var>Q = 6</var> operations. Initially, <var>S</var> is a.

Operation <var>1</var>: <var>S</var> becomes aa.

Operation <var>2</var>: <var>S</var> becomes baa.

Operation <var>3</var>: <var>S</var> becomes aab.

Operation <var>4</var>: <var>S</var> becomes aabc.

Operation <var>5</var>: <var>S</var> becomes cbaa.

Operation <var>6</var>: <var>S</var> becomes aabc.

Thus, the resulting string is aabc.

Sample Input 3

y
1
2 1 x

Sample Output 3

xy

int solution(void) {
  char s[500001];
  char *p1 = &s[200000];
  scanf("%s", p1);
  char *p2 = p1 + strlen(p1);
  int q;
  scanf("%d", &q);
  int flag = 1;
  for (int i = 0; i < q; i++) {
    int n;
    int f;
    char c;
    scanf("%d", &n);
    if (n == 1) {
      flag = 1 - flag;
      continue;
    }
    scanf("%d %c", &f, &c);
    if (flag ^ --f) {
      *--p1 = c;
    } else {
      *p2++ = c;
    }
  }
  *p2 = '\0';
  if (flag) {
    puts(p1);
  } else {
    while (--p2 >= p1) {
      putchar(*p2);
    }
    putchar('\n');
  }
}

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

    let mut q = String::new();
    std::io::stdin().read_line(&mut q).unwrap();
    let q: u64 = q.trim_end().parse().unwrap();

    let mut reversed = false;

    for _ in 0..q {
        let mut query = String::new();
        std::io::stdin().read_line(&mut query).unwrap();
        let query: Vec<&str> = query.split_whitespace().collect();

        if query[0] == "1" {
            reversed = !reversed;
        }
        if query[0] == "2" {
            let push_front = query[1] == "1";
            if reversed ^ push_front {
                s.push_front(query[2].chars().next().unwrap());
            } else {
                s.push_back(query[2].chars().next().unwrap());
            }
        }
    }

    let mut res = String::new();
    if reversed {
        res.extend(s.iter().rev());
    } else {
        res.extend(s.iter());
    };

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


Suppose there is a $$$h \times w$$$ grid consisting of empty or full cells. Let's make some definitions:  $$$r_{i}$$$ is the number of consecutive full cells connected to the left side in the $$$i$$$-th row ($$$1 \le i \le h$$$). In particular, $$$r_i=0$$$ if the leftmost cell of the $$$i$$$-th row is empty.  $$$c_{j}$$$ is the number of consecutive full cells connected to the top end in the $$$j$$$-th column ($$$1 \le j \le w$$$). In particular, $$$c_j=0$$$ if the topmost cell of the $$$j$$$-th column is empty. In other words, the $$$i$$$-th row starts exactly with $$$r_i$$$ full cells. Similarly, the $$$j$$$-th column starts exactly with $$$c_j$$$ full cells.    These are the $$$r$$$ and $$$c$$$ values of some $$$3 \times 4$$$ grid. Black cells are full and white cells are empty. You have values of $$$r$$$ and $$$c$$$. Initially, all cells are empty. Find the number of ways to fill grid cells to satisfy values of $$$r$$$ and $$$c$$$. Since the answer can be very large, find the answer modulo $$$1000000007\,(10^{9} + 7)$$$. In other words, find the remainder after division of the answer by $$$1000000007\,(10^{9} + 7)$$$.

int solution() {
  int h;
  int w;
  scanf("%d %d", &h, &w);
  int matrix[h][w];

  memset(matrix, 0, sizeof(matrix));

  for (int i = 0; i < h; ++i) {
    int r = 0;
    scanf("%d", &r);

    for (int j = 0; j < r; ++j) {
      matrix[i][j] += 1;
    }
    if (r < w) {
      matrix[i][r] += 4;
    }
  }

  for (int i = 0; i < w; ++i) {
    int c = 0;
    scanf("%d", &c);

    for (int j = 0; j < c; ++j) {
      matrix[j][i] += 1;
    }
    if (c < h) {
      matrix[c][i] += 4;
    }
  }
  int n = 0;
  int ans = 1;
  int l = 1000000007;
  int flag = 0;

  for (int k = 0; k < h; ++k) {
    for (int i = 0; i < w; ++i) {
      if (!matrix[k][i]) {
        n++;
        ans = ans * 2 % l;
      }
      if (matrix[k][i] == 5) {

        flag = -1;
        break;
      }
    }
  }

  if (flag != -1) {
    printf("%d", ans);
  } else {
    printf("%d", 0);
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    stdin().read_to_string(&mut buf).unwrap();
    let mut tok = buf.split_whitespace();
    let mut get = || tok.next().unwrap();

    let h = get!(usize);
    let w = get!(usize);
    let mut grid = vec![vec![0; w]; h];
    for r in 0..h {
        let c = get!(usize);
        for i in 0..c {
            grid[r][i] |= 1;
        }
        if c < w {
            grid[r][c] |= 2;
        }
    }
    for c in 0..w {
        let r = get!(usize);
        for i in 0..r {
            grid[i][c] |= 1;
        }
        if r < h {
            grid[r][c] |= 2;
        }
    }
    let mut ans = 1_i64;
    for r in 0..h {
        for c in 0..w {
            match grid[r][c] {
                0 => ans = ans * 2 % 1_000_000_007,
                3 => ans = 0,
                _ => {}
            }
        }
    }
    println!("{}", ans);
}


Score : <var>100</var> points

Problem Statement

Given is a three-digit integer <var>N</var>. Does <var>N</var> contain the digit <var>7</var>?

If so, print Yes; otherwise, print No.

Constraints

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

If <var>N</var> contains the digit <var>7</var>, print Yes; otherwise, print No.

Sample Input 1

117

Sample Output 1

Yes

<var>117</var> contains <var>7</var> as its last digit.

Sample Input 2

123

Sample Output 2

No

<var>123</var> does not contain the digit <var>7</var>.

Sample Input 3

777

Sample Output 3

Yes

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    let mut itr = s.trim().chars();
    println!("{}", if itr.any(|e| e == '7') { "Yes" } else { "No" });
}


You are given two positive integers $$$n$$$ and $$$k$$$. Print the $$$k$$$-th positive integer that is not divisible by $$$n$$$.For example, if $$$n=3$$$, and $$$k=7$$$, then all numbers that are not divisible by $$$3$$$ are: $$$1, 2, 4, 5, 7, 8, 10, 11, 13 \dots$$$. The $$$7$$$-th number among them is $$$10$$$.

int solution() {
  int t;
  scanf("%d\n", &t);
  long long int n[t];
  long long int k[t];
  for (int i = 0; i < t; i++) {
    scanf("%lld %lld\n", &n[i], &k[i]);
  }
  for (int i = 0; i < t; i++) {
    long long int q;
    long long int r;
    q = k[i] / (n[i] - 1);
    r = k[i] % (n[i] - 1);
    if (r == 0) {
      printf("%lld\n", (q * n[i]) - 1);
    } else {
      printf("%lld\n", (q * n[i]) + r);
    }
  }
  return 0;
}

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


Score : <var>900</var> points

Problem Statement

You are given an undirected graph consisting of <var>N</var> vertices and <var>M</var> edges.
The vertices are numbered <var>1</var> to <var>N</var>, and the edges are numbered <var>1</var> to <var>M</var>.
In addition, each vertex has a label, A or B. The label of Vertex <var>i</var> is <var>s_i</var>.
Edge <var>i</var> bidirectionally connects vertex <var>a_i</var> and <var>b_i</var>.

The phantom thief Nusook likes to choose some vertex as the startpoint and traverse an edge zero or more times.
Today, he will make a string after traveling as above, by placing the labels of the visited vertices in the order visited, beginning from the startpoint.

For example, in a graph where Vertex <var>1</var> has the label A and Vertex <var>2</var> has the label B, if Nusook travels along the path <var>1 \rightarrow 2 \rightarrow 1 \rightarrow 2 \rightarrow 2</var>, the resulting string is ABABB.

Determine if Nusook can make all strings consisting of A and B.

Constraints

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

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

<var>|s| = N</var>

<var>s_i</var> is A or B.

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

The given graph may NOT be simple or connected.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>s</var>
<var>a_1</var> <var>b_1</var>
<var>:</var>
<var>a_{M}</var> <var>b_{M}</var>

Output

If Nusook can make all strings consisting of A and B, print Yes; otherwise, print No.

Sample Input 1

2 3
AB
1 1
1 2
2 2

Sample Output 1

Yes

Since Nusook can visit Vertex <var>1</var> and Vertex <var>2</var> in any way he likes, he can make all strings consisting of A and B.

Sample Input 2

4 3
ABAB
1 2
2 3
3 1

Sample Output 2

No

For example, Nusook cannot make BB.

The given graph may not be connected.

Sample Input 3

13 23
ABAAAABBBBAAB
7 1
10 6
1 11
2 10
2 8
2 11
11 12
8 3
7 12
11 2
13 13
11 9
4 1
9 7
9 6
8 13
8 6
4 10
8 7
4 3
2 1
8 12
6 9

Sample Output 3

Yes

Sample Input 4

13 17
BBABBBAABABBA
7 1
7 9
11 12
3 9
11 9
2 1
11 5
12 11
10 8
1 11
1 8
7 7
9 10
8 8
8 12
6 2
13 11

Sample Output 4

No

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 s = it.next().unwrap().as_bytes();
    let mut to = vec![vec![0; n]; 2];
    let mut g = vec![Vec::new(); n];
    for _ in 0..m {
        let a = it.next().unwrap().parse::<usize>().unwrap() - 1;
        let b = it.next().unwrap().parse::<usize>().unwrap() - 1;
        to[(s[b] - b'A') as usize][a] += 1;
        to[(s[a] - b'A') as usize][b] += 1;
        g[a].push(b);
        g[b].push(a);
    }
    let mut visit = vec![0; n];
    let mut qu = VecDeque::new();
    for i in 0..n {
        if to[0][i] == 0 || to[1][i] == 0 {
            qu.push_back(i);
            visit[i] = 1;
        }
    }
    while !qu.is_empty() {
        let p = qu.pop_front().unwrap();
        let idx = (s[p] - b'A') as usize;
        for &t in &g[p] {
            to[idx][t] -= 1;
            if to[idx][t] == 0 && visit[t] == 0 {
                qu.push_back(t);
                visit[t] = 1;
            }
        }
    }
    println!("{}", if visit.contains(&0) { "Yes" } else { "No" });
}


It has finally been decided to build a roof over the football field in School 179. Its construction will require placing $$$n$$$ consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation $$$p$$$ of integers from $$$0$$$ to $$$n - 1$$$, where $$$p_i$$$ is the height of the $$$i$$$-th pillar from the left $$$(1 \le i \le n)$$$.As the chief, you know that the cost of construction of consecutive pillars is equal to the maximum value of the bitwise XOR of heights of all pairs of adjacent pillars. In other words, the cost of construction is equal to $$$\max\limits_{1 \le i \le n - 1}{p_i \oplus p_{i + 1}}$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.Find any sequence of pillar heights $$$p$$$ of length $$$n$$$ with the smallest construction cost.In this problem, a permutation is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n - 1$$$ in arbitrary order. For example, $$$[2,3,1,0,4]$$$ is a permutation, but $$$[1,0,1]$$$ is not a permutation ($$$1$$$ appears twice in the array) and $$$[1,0,3]$$$ is also not a permutation ($$$n=3$$$, but $$$3$$$ is in the array).

int solution() {
  int tt;
  scanf("%d", &tt);
  while (tt--) {
    int n;
    scanf("%d", &n);
    int k = 1;
    while (k < n) {
      k *= 2;
    }
    k /= 2;
    for (int i = 1; i < n; i++) {
      if (i == k) {
        printf("0 %d ", k);
      } else {
        printf("%d ", i);
      }
    }
    printf("\n");
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let mut m = 1 << 18;
        while (n - 1) & m == 0 {
            m >>= 1;
        }
        let mut ans = vec![];
        for i in 0..m {
            ans.push(m - i - 1);
        }
        for i in m..n {
            ans.push(i);
        }
        print!("{}", ans[0]);
        for i in 1..n {
            print!(" {}", ans[i]);
        }
        println!();
    }
}


A sequence of $$$n$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$n$$$ exactly once.Given two integers $$$n$$$ and $$$k$$$, construct a permutation $$$a$$$ of numbers from $$$1$$$ to $$$n$$$ which has exactly $$$k$$$ peaks. An index $$$i$$$ of an array $$$a$$$ of size $$$n$$$ is said to be a peak if $$$1 < i < n$$$ and $$$a_i \gt a_{i-1}$$$ and $$$a_i \gt a_{i+1}$$$. If such permutation is not possible, then print $$$-1$$$.

fn solution() {
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let t: i64 = s.trim().parse().unwrap();
    for _i in 0..t {
        s.clear();
        stdin().read_line(&mut s).unwrap();
        let mut iter = s.split_whitespace();
        let n: usize = iter.next().unwrap().parse().unwrap();
        let k: usize = iter.next().unwrap().parse().unwrap();

        if n <= 2 * k || (n < 3 && k != 0) {
            println!("-1");
            continue;
        }
        let mut l = 1;
        let mut r = n;
        let mut ans = vec![0; n];
        for i in 0..k {
            ans[2 * i] = l;
            ans[2 * i + 1] = r;

            l += 1;
            r -= 1;
        }
        for i in 2 * k..n {
            ans[i] = l;
            l += 1;
        }
        for i in 0..ans.len() {
            if i != 0 {
                print!(" {}", ans[i]);
            } else {
                print!("{}", ans[i]);
            }
        }
        println!();
    }
}


Alice gave Bob two integers $$$a$$$ and $$$b$$$ ($$$a > 0$$$ and $$$b \ge 0$$$). Being a curious boy, Bob wrote down an array of non-negative integers with $$$\operatorname{MEX}$$$ value of all elements equal to $$$a$$$ and $$$\operatorname{XOR}$$$ value of all elements equal to $$$b$$$.What is the shortest possible length of the array Bob wrote?Recall that the $$$\operatorname{MEX}$$$ (Minimum EXcluded) of an array is the minimum non-negative integer that does not belong to the array and the $$$\operatorname{XOR}$$$ of an array is the bitwise XOR of all the elements of the array.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int a;
    int b;
    scanf("%d%d", &a, &b);
    int temp = 0;
    if ((a - 1) % 4 == 0) {
      temp = a - 1;
    } else if ((a - 1) % 4 == 1) {
      temp = 1;
    } else if ((a - 1) % 4 == 2) {
      temp = a;
    } else {
      temp = 0;
    }
    if (temp == b) {
      printf("%d\n", a);
    } else if (temp != b && (temp ^ b) != a) {
      printf("%d\n", a + 1);
    } else {
      printf("%d\n", a + 2);
    }
  }
}

fn solution() {
    let mut s = String::new();
    const MAX_VALUE: usize = 3 * 100000;
    let mut dp: [usize; MAX_VALUE] = [0; MAX_VALUE];

    for i in 1..MAX_VALUE {
        dp[i] = dp[i - 1] ^ i;
    }

    let solve = |a, b| -> usize {
        let prev = a - 1;
        let xor_up_to = dp[prev];
        let remain = xor_up_to ^ b;
        if remain == 0 {
            a
        } else if remain == a {
            a + 2
        } else {
            a + 1
        }
    };

    let stdin = io::stdin();
    stdin.read_line(&mut s).expect("string");
    let t: i32 = s.trim().parse().expect("int");
    s.clear();

    for _ in 0..t {
        stdin.read_line(&mut s).expect("string");
        let v: Vec<usize> = s
            .split_whitespace()
            .map(|x| x.parse::<usize>().unwrap())
            .collect();
        s.clear();
        println!("{}", solve(v[0], v[1]));
    }
}


Score : <var>300</var> points

Problem Statement

You are given a string <var>S</var> of length <var>N</var> consisting of A, C, G and T. Answer the following <var>Q</var> queries:

Query <var>i</var> (<var>1 \leq i \leq Q</var>): You will be given integers <var>l_i</var> and <var>r_i</var> (<var>1 \leq l_i < r_i \leq N</var>). Consider the substring of <var>S</var> starting at index <var>l_i</var> and ending at index <var>r_i</var> (both inclusive). In this string, how many times does AC occurs as a substring?

Notes

A substring of a string <var>T</var> is a string obtained by removing zero or more characters from the beginning and the end of <var>T</var>.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

Constraints

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

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

<var>S</var> is a string of length <var>N</var>.

Each character in <var>S</var> is A, C, G or T.

<var>1 \leq l_i < r_i \leq N</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>Q</var>
<var>S</var>
<var>l_1</var> <var>r_1</var>
<var>:</var>
<var>l_Q</var> <var>r_Q</var>

Output

Print <var>Q</var> lines. The <var>i</var>-th line should contain the answer to the <var>i</var>-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

Query <var>1</var>: the substring of <var>S</var> starting at index <var>3</var> and ending at index <var>7</var> is ACTAC. In this string, AC occurs twice as a substring.

Query <var>2</var>: the substring of <var>S</var> starting at index <var>2</var> and ending at index <var>3</var> is CA. In this string, AC occurs zero times as a substring.

Query <var>3</var>: the substring of <var>S</var> starting at index <var>1</var> and ending at index <var>8</var> is ACACTACG. In this string, AC occurs three times as a substring.

int solution(void) {
  int n;
  int q;
  scanf("%d %d\n", &n, &q);
  char s[n];
  int count[n];
  int l[q];
  int r[q];
  count[0] = 0;
  for (int i = 0; i < n; i++) {
    scanf("%c\n", &s[i]);
  }
  for (int j = 0; j < n; j++) {
    if (s[j] == 'A' && s[j + 1] == 'C') {
      count[j + 1] = count[j] + 1;
    } else {
      count[j + 1] = count[j];
    }
  }
  for (int i = 0; i < q; i++) {
    scanf("%d %d\n", &l[i], &r[i]);
    printf("%d\n", count[r[i] - 1] - count[l[i] - 1]);
  }
  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 q: usize = iter.next().unwrap().parse().unwrap();
    let s: Vec<char> = iter.next().unwrap().chars().collect();
    let mut a = vec![0; n + 1];
    for i in 0..n - 1 {
        if s[i] == 'A' && s[i + 1] == 'C' {
            a[i + 1] = 1;
        }
    }
    for i in 1..n + 1 {
        a[i] += a[i - 1];
    }
    for _ in 0..q {
        let l: usize = iter.next().unwrap().parse().unwrap();
        let r: usize = iter.next().unwrap().parse().unwrap();
        println!("{}", a[r - 1] - a[l - 1]);
    }
}


There's a chessboard of size $$$n \times n$$$. $$$m$$$ rooks are placed on it in such a way that:   no two rooks occupy the same cell;  no two rooks attack each other. A rook attacks all cells that are in its row or column.Is it possible to move exactly one rook (you can choose which one to move) into a different cell so that no two rooks still attack each other? A rook can move into any cell in its row or column if no other rook stands on its path.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    int m;
    int n;
    scanf("%d%d", &m, &n);
    int arr[2 * n];
    for (int i = 0; i < 2 * n; i++) {
      scanf("%d", &arr[n]);
    }
    if (m == n) {
      printf("No\n");
    } else {
      printf("Yes\n");
    }
  }
  return 0;
}

fn solution() {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let t = buffer.trim().parse::<u16>().unwrap();
    for _ in 0..t {
        buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
        let mut parts = buffer.split_whitespace().map(|s| s.parse::<u16>().unwrap());
        let n = parts.next().unwrap();
        let m = parts.next().unwrap();
        for _ in 0..m {
            io::stdin().read_line(&mut buffer).unwrap();
        }
        if m < n {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi wants to gain muscle, and decides to work out at AtCoder Gym.

The exercise machine at the gym has <var>N</var> buttons, and exactly one of the buttons is lighten up.
These buttons are numbered <var>1</var> through <var>N</var>.
When Button <var>i</var> is lighten up and you press it, the light is turned off, and then Button <var>a_i</var> will be lighten up. It is possible that <var>i=a_i</var>.
When Button <var>i</var> is not lighten up, nothing will happen by pressing it.

Initially, Button <var>1</var> is lighten up. Takahashi wants to quit pressing buttons when Button <var>2</var> is lighten up.

Determine whether this is possible. If the answer is positive, find the minimum number of times he needs to press buttons.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print <var>-1</var> if it is impossible to lighten up Button <var>2</var>.
Otherwise, print the minimum number of times we need to press buttons in order to lighten up Button <var>2</var>.

Sample Input 1

3
3
1
2

Sample Output 1

2

Press Button <var>1</var>, then Button <var>3</var>.

Sample Input 2

4
3
4
1
2

Sample Output 2

-1

Pressing Button <var>1</var> lightens up Button <var>3</var>, and vice versa, so Button <var>2</var> will never be lighten up.

Sample Input 3

5
3
3
4
2
4

Sample Output 3

3

int solution() {
  int N = 0;
  scanf("%d", &N);
  int a[N - 1];
  for (int n = 0; n < N; n++) {
    scanf("%d", &a[n]);
  }
  int check = 1;
  int num = 0;
  int count = 0;
  while (check) {
    num = a[num];
    count++;
    if (num == 2) {
      check = 0;
    }
    num--;
    if (count > N) {
      break;
    }
  }

  if (check) {
    printf("-1\n");
  } else {
    printf("%d\n", count);
  }

  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 buttons: Vec<usize> = (0..n)
        .map(|_| iter.next().unwrap().parse().unwrap())
        .collect();

    let mut cnt = 0;
    let mut target_button_index = 1;
    while target_button_index != 2 && cnt < 100000 {
        target_button_index = buttons[target_button_index - 1];
        cnt += 1;
    }
    if cnt == 100000 {
        println!("-1");
    } else {
        println!("{}", cnt);
    }
}


An array is beautiful if both of the following two conditions meet:  there are at least $$$l_1$$$ and at most $$$r_1$$$ elements in the array equal to its minimum;  there are at least $$$l_2$$$ and at most $$$r_2$$$ elements in the array equal to its maximum. For example, the array $$$[2, 3, 2, 4, 4, 3, 2]$$$ has $$$3$$$ elements equal to its minimum ($$$1$$$-st, $$$3$$$-rd and $$$7$$$-th) and $$$2$$$ elements equal to its maximum ($$$4$$$-th and $$$5$$$-th).Another example: the array $$$[42, 42, 42]$$$ has $$$3$$$ elements equal to its minimum and $$$3$$$ elements equal to its maximum.Your task is to calculate the minimum possible number of elements in a beautiful array.

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

  while (test_cases--) {
    int l1 = 0;
    int r1 = 0;
    int l2 = 0;
    int r2 = 0;

    scanf("%d", &l1);
    scanf("%d", &r1);
    scanf("%d", &l2);
    scanf("%d", &r2);

    int min = 100000;
    if (r2 < l1 || r1 < l2) {
      printf("%d\n", l1 + l2);
    } else {
      if (l2 > l1) {
        printf("%d\n", l2);
      } else {
        printf("%d\n", l1);
      }
    }
  }
}

fn solution() {
    let mut str_t = String::new();
    io::stdin().read_line(&mut str_t);
    let mut total_case = 0;
    match str::parse::<i32>(str_t.trim()) {
        Ok(val) => total_case = val,
        Err(_) => print!("error"),
    };

    for _i in 0..total_case {
        let mut str_l = String::new();
        io::stdin().read_line(&mut str_l);
        let numbers = str_l
            .trim()
            .split(' ')
            .flat_map(str::parse::<i32>)
            .collect::<Vec<_>>();
        let (l1, r1, l2, r2) = (numbers[0], numbers[1], numbers[2], numbers[3]);

        if r1 < l2 || r2 < l1 {
            println!("{}", l1 + l2);
        } else if l1 <= l2 && l2 <= r1 {
            println!("{}", l2);
        } else {
            println!("{}", l1);
        }
    }
}


Given an integer $$$n$$$, find any array $$$a$$$ of $$$n$$$ distinct nonnegative integers less than $$$2^{31}$$$ such that the bitwise XOR of the elements on odd indices equals the bitwise XOR of the elements on even indices.

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

  for (int currentSet = 0; currentSet < numSets; ++currentSet) {
    int numElements = 0;
    scanf("%d", &numElements);

    if (numElements == 3) {
      printf("2 1 3\n");
      continue;
    }

    if ((numElements % 2) == 1) {
      printf("0 ");
      numElements -= 1;
    }
    if ((numElements % 4) == 2) {
      printf("4 1 2 12 3 8");
      numElements -= 6;
      if (numElements > 0) {
        printf(" ");
      } else {
        printf("\n");
        continue;
      }
    }
    int currentPrint = 14;
    for (int i = 1; i < numElements; ++i) {
      printf("%d ", currentPrint++);
    }
    printf("%d\n", currentPrint);
  }

  return 0;
}

fn solution() {
    let mut lines = io::stdin().lines();
    lines.next();
    for line in lines {
        let n = line.unwrap().parse::<i32>().unwrap();
        let v = (0..(n - 3)).collect::<Vec<i32>>();
        let xor = v.iter().fold(0, |a, b| a ^ b);
        let x1 = 1 << 29;
        let x2 = 1 << 30;
        let x3 = xor ^ x1 ^ x2;
        let res = v
            .iter()
            .map(|x| x.to_string())
            .collect::<Vec<String>>()
            .join(" ");

        println!("{res} {x1} {x2} {x3}");
    }
}


An array $$$a_1, a_2, \ldots, a_n$$$ is good if and only if for every subsegment $$$1 \leq l \leq r \leq n$$$, the following holds: $$$a_l + a_{l + 1} + \ldots + a_r = \frac{1}{2}(a_l + a_r) \cdot (r - l + 1)$$$. You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$. In one operation, you can replace any one element of this array with any real number. Find the minimum number of operations you need to make this array good.

int solution() {
  int t;
  int i;
  scanf("%d", &t);
  for (i = 0; i < t; i++) {
    int n;
    int j;
    int k;
    int l;
    scanf("%d", &n);
    int arr[n];
    int max = 1;
    for (j = 0; j < n; j++) {
      scanf("%d", &arr[j]);
    }
    for (j = 0; j < n - 1; j++) {
      for (k = j + 1; k < n; k++) {
        int min = 2;
        for (l = k + 1; l < n; l++) {
          if ((arr[k] - arr[j]) * (l - k) == (arr[l] - arr[k]) * (k - j)) {
            min++;
          }
        }
        if (min > max) {
          max = min;
        }
      }
    }
    printf("%d\n", n - max);
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let x: Vec<i64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        if n == 1 {
            println!("0");
            continue;
        }
        let mut ans: usize = n;
        for i in 0..(n - 1) {
            for j in (i + 1)..n {
                let nu: i64 = x[j] - x[i];
                let d: i64 = (j - i) as i64;
                let b: i64 = x[i] * d - (nu * i as i64);
                let cnt = (0..n).filter(|&i| x[i] * d != nu * i as i64 + b).count();
                ans = min(ans, cnt);
            }
        }
        println!("{}", ans);
    }
}


Polycarp must pay exactly $$$n$$$ burles at the checkout. He has coins of two nominal values: $$$1$$$ burle and $$$2$$$ burles. Polycarp likes both kinds of coins equally. So he doesn't want to pay with more coins of one type than with the other.Thus, Polycarp wants to minimize the difference between the count of coins of $$$1$$$ burle and $$$2$$$ burles being used. Help him by determining two non-negative integer values $$$c_1$$$ and $$$c_2$$$ which are the number of coins of $$$1$$$ burle and $$$2$$$ burles, respectively, so that the total value of that number of coins is exactly $$$n$$$ (i. e. $$$c_1 + 2 \cdot c_2 = n$$$), and the absolute value of the difference between $$$c_1$$$ and $$$c_2$$$ is as little as possible (i. e. you must minimize $$$|c_1-c_2|$$$).

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

    io::stdin().read_line(&mut t).unwrap();

    for _ in 0..t.trim().parse::<i32>().unwrap() {
        let mut n = String::new();
        io::stdin().read_line(&mut n).unwrap();

        let sum = n.trim().parse::<i64>().unwrap();

        if sum % 3 == 0 {
            println!("{} {}", sum / 3, sum / 3)
        } else {
            if sum % 3 == 1 {
                println!("{} {}", sum / 3 + 1, sum / 3)
            } else {
                println!("{} {}", sum / 3, sum / 3 + 1);
            }
        }
    }
}


There are $$$n$$$ people in a horizontal line, each looking either to the left or the right. Each person counts the number of people in the direction they are looking. The value of the line is the sum of each person's count.For example, in the arrangement LRRLL, where L stands for a person looking left and R stands for a person looking right, the counts for each person are $$$[0, 3, 2, 3, 4]$$$, and the value is $$$0+3+2+3+4=12$$$.You are given the initial arrangement of people in the line. For each $$$k$$$ from $$$1$$$ to $$$n$$$, determine the maximum value of the line if you can change the direction of at most $$$k$$$ people.

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

  while (t--) {
    long long int n;
    long long int val = 0;
    long long int k = 0;
    scanf("%lld\n", &n);
    char c[n];
    long long int a[n];

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

      if (c[i] == 'L') {
        val += i;
      } else {
        val += n - 1 - i;
      }
    }
    for (long long int i = 0; i < n / 2; i++) {
      if (c[i] == 'L') {
        printf("%lld ", val += n - (2 * i + 1));
        k++;
      }
      if (c[n - i - 1] == 'R') {
        printf("%lld ", val += n - (2 * i + 1));
        k++;
      }
    }
    for (int i = k; i < n; i++) {
      printf("%lld ", val);
    }
    printf("\n");
  }
  return 0;
}

fn solution() {
    let t: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    for _i in 0..t {
        let n: usize = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().parse().unwrap()
        };
        let s: Vec<char> = {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            line.trim().chars().collect()
        };
        let mut ans = Vec::new();
        let mut sum = 0;

        for i in 0..n {
            let ss = s[i];
            if ss == 'L' {
                ans.push((n - i - 1 - i) as i64);
                sum += i as i64;
            } else {
                ans.push((i - (n - i - 1)) as i64);
                sum += n as i64 - i as i64 - 1;
            }
        }
        ans.sort_by_key(|&x| Reverse(x));

        let mut ans2 = Vec::new();
        for d in ans {
            if d > 0 {
                sum += d;
            }
            ans2.push(sum);
        }
        println!(
            "{}",
            ans2.iter()
                .map(std::string::ToString::to_string)
                .collect::<Vec<_>>()
                .join(" ")
        );
    }
}


Score : <var>100</var> points

Problem Statement

In "Takahashi-ya", a ramen restaurant, a bowl of ramen costs <var>700</var> yen (the currency of Japan), plus <var>100</var> yen for each kind of topping (boiled egg, sliced pork, green onions).

A customer ordered a bowl of ramen and told which toppings to put on his ramen to a clerk. The clerk took a memo of the order as a string <var>S</var>. <var>S</var> is three characters long, and if the first character in <var>S</var> is o, it means the ramen should be topped with boiled egg; if that character is x, it means the ramen should not be topped with boiled egg. Similarly, the second and third characters in <var>S</var> mean the presence or absence of sliced pork and green onions on top of the ramen.

Write a program that, when <var>S</var> is given, prints the price of the corresponding bowl of ramen.

Constraints

<var>S</var> is a string of length <var>3</var>.

Each character in <var>S</var> is o or x.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the price of the bowl of ramen corresponding to <var>S</var>.

Sample Input 1

oxo

Sample Output 1

900

The price of a ramen topped with two kinds of toppings, boiled egg and green onions, is <var>700 + 100 \times 2 = 900</var> yen.

Sample Input 2

ooo

Sample Output 2

1000

The price of a ramen topped with all three kinds of toppings is <var>700 + 100 \times 3 = 1000</var> yen.

Sample Input 3

xxx

Sample Output 3

700

The price of a ramen without any toppings is <var>700</var> yen.

int solution() {
  char top = 0;
  char in[4];
  scanf("%s", in);

  for (int i = 0; i < 4; i++) {
    if (*(in + (i * sizeof(char))) == 'o') {
      top++;
    }
  }
  printf("%d\n", 700 + (top * 100));
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).ok();
    let cnt = buf.trim().chars().filter(|&x| x == 'o').count();
    println!("{}", 700 + cnt * 100);
}


Pasha is participating in a contest on one well-known website. This time he wants to win the contest and will do anything to get to the first place!This contest consists of n problems, and Pasha solves ith problem in ai time units (his solutions are always correct). At any moment of time he can be thinking about a solution to only one of the problems (that is, he cannot be solving two problems at the same time). The time Pasha spends to send his solutions is negligible. Pasha can send any number of solutions at the same moment.Unfortunately, there are too many participants, and the website is not always working. Pasha received the information that the website will be working only during m time periods, jth period is represented by its starting moment lj and ending moment rj. Of course, Pasha can send his solution only when the website is working. In other words, Pasha can send his solution at some moment T iff there exists a period x such that lx ≤ T ≤ rx.Pasha wants to know his best possible result. We need to tell him the minimal moment of time by which he is able to have solutions to all problems submitted, if he acts optimally, or say that it's impossible no matter how Pasha solves the problems.

int solution() {
  int n;
  int m;
  scanf("%d", &n);
  long int a[n];
  int i;
  long int sum = 0;
  long int max = 100001;
  for (i = 0; i < n; i++) {
    scanf("%ld", &a[i]);
    sum += a[i];
  }

  int flag = 0;

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

    if (l[i] <= sum && (r[i] >= sum)) {
      printf("%ld", sum);
      flag = 1;
      break;
    }
    if (r[i] < max && (r[i] > sum)) {
      max = r[i];
    }
    if (l[i] < max && (l[i] > sum)) {
      max = l[i];
    }
  }
  if (!flag) {
    if (max == 100001) {
      printf("-1");
    } else {
      printf("%ld", max);
    }
  }
}

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

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

    buffer.clear();
    io::stdin().read_line(&mut buffer).unwrap();
    let m = buffer.trim().parse::<i32>().unwrap();
    let mut i = vec![-1];
    let mut e = vec![-1];

    for _ in 0..m {
        buffer.clear();
        io::stdin().read_line(&mut buffer).unwrap();
        let aux = buffer
            .split_whitespace()
            .map(|x| x.trim().parse::<i32>().unwrap())
            .collect::<Vec<i32>>();
        i.push(aux[0]);
        e.push(aux[1]);
    }

    let mut last = 0;
    let mut ok = m > 0;
    if ok {
        for j in 0..n {
            if last + v[j] > e[e.len() - 1] {
                ok = false;
                break;
            }
            last += v[j];
        }
    }
    if ok {
        let index = match i.binary_search(&last) {
            Ok(x) => x,
            Err(x) => x,
        };
        if e[index - 1] >= last {
            println!("{}", last);
        } else {
            println!("{}", i[index]);
        }
    } else {
        println!("-1");
    }
}


Vector

  For a dynamic array $A = \{a_0, a_1, ...\}$ of integers, perform a sequence of the following operations:

pushBack($x$): add element $x$ at the end of $A$

randomAccess($p$):print element $a_p$

popBack(): delete the last element of $A$

$A$ is a 0-origin array and it is empty in the initial state.

Input

  The input is given in the following format.

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

  Each query $query_i$ is given by

0 $x$

or

1 $p$

or

2

  where the first digits 0, 1 and 2 represent pushBack, randomAccess and popBack operations respectively.

  randomAccess and popBack operations will not be given for an empty array.

Output

  For each randomAccess, print $a_p$ in a line.

Constraints

$1 \leq q \leq 200,000$

$0 \leq p < $ the size of $A$

$-1,000,000,000 \leq x \leq 1,000,000,000$

Sample Input 1

8
0 1
0 2
0 3
2
0 4
1 0
1 1
1 2

Sample Output 1

1
2
4

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

  int a[q];
  int i = 0;

  int com;
  int x;
  while (q--) {
    scanf("%d \n", &com);
    switch (com) {
    case 0:
      scanf("%d\n", &x);
      a[i++] = x;
      break;
    case 1:
      scanf("%d\n", &x);
      printf("%d\n", a[x]);
      break;
    case 2:
      a[i--] = -1;
      break;
    }
  }

  return 0;
}

fn solution() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).ok();
    let row: usize = s.trim().parse().unwrap_or(0);
    s.clear();
    let mut array = Vec::new();

    for _ in 0..row {
        io::stdin().read_line(&mut s).ok();
        let v: Vec<isize> = s
            .split_whitespace()
            .map(|e| e.parse().unwrap_or(0))
            .collect();

        match v[0] {
            0 => {
                array.push(v[1]);
            }
            1 => {
                println!("{}", array[v[1] as usize]);
            }
            2 => {
                array.pop();
            }
            _ => println!("error 0 or 1 or 2"),
        }
        s.clear();
    }
}


You are given a string $$$s$$$, consisting only of Latin letters 'a', and a string $$$t$$$, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string $$$s$$$ with a string $$$t$$$. Note that after the replacement string $$$s$$$ might contain letters other than 'a'.You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.Two strings are considered different if they have different length, or they differ at some index.

int solution(void) {
  int Q;
  char s[51];
  char t[51];

  scanf("%d", &Q);
  while (Q--) {
    scanf("%s %s", s, t);
    int a = 0;
    int b = 0;
    for (int i = 0; t[i]; ++i) {
      if (t[i] == 'a') {
        ++a;
      } else {
        b = 1;
      }
    }
    if (a && b) {
      printf("-1\n");
    } else if (b) {
      int len = strlen(s);
      printf("%lld\n", (1LL << len));
    } else if (a) {
      if (a == 1) {
        printf("1\n");
      } else {
        printf("-1\n");
      }
    }
  }

  return 0;
}

fn solution() {
    let mut input = String::new();
    stdin().read_to_string(&mut input).ok();
    let mut output = String::new();
    let mut input = input.split_ascii_whitespace();
    let q: usize = input.next().unwrap().parse().unwrap();
    for _ in 0..q {
        let s = input.next().unwrap();
        let t = input.next().unwrap();
        if t.contains('a') {
            if t.len() > 1 {
                output.push_str("-1\n");
            } else {
                output.push_str("1\n");
            }
        } else {
            let a_count = s.bytes().filter(|&c| c == b'a').count();
            writeln!(output, "{}", 1u64 << a_count).ok();
        }
    }
    print!("{output}");
}


Score : <var>300</var> points

Problem Statement

You are given an integer <var>N</var>.

For two positive integers <var>A</var> and <var>B</var>, we will define <var>F(A,B)</var> as the larger of the following: the number of digits in the decimal notation of <var>A</var>, and the number of digits in the decimal notation of <var>B</var>.

For example, <var>F(3,11) = 2</var> since <var>3</var> has one digit and <var>11</var> has two digits.

Find the minimum value of <var>F(A,B)</var> as <var>(A,B)</var> ranges over all pairs of positive integers such that <var>N = A \times B</var>.

Constraints

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

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

Input

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

<var>N</var>

Output

Print the minimum value of <var>F(A,B)</var> as <var>(A,B)</var> ranges over all pairs of positive integers such that <var>N = A \times B</var>.

Sample Input 1

10000

Sample Output 1

3

<var>F(A,B)</var> has a minimum value of <var>3</var> at <var>(A,B)=(100,100)</var>.

Sample Input 2

1000003

Sample Output 2

7

There are two pairs <var>(A,B)</var> that satisfy the condition: <var>(1,1000003)</var> and <var>(1000003,1)</var>. For these pairs, <var>F(1,1000003)=F(1000003,1)=7</var>.

Sample Input 3

9876543210

Sample Output 3

6

int solution(void) {
  int64_t N;
  scanf("%ld", &N);

  int MIN = 10;
  for (int64_t i = 1; i * i <= N; i++) {
    if (N % i == 0) {
      int64_t B = N / i;
      int M = 0;
      while (B > 0) {
        B /= 10;
        M++;
      }
      MIN = M;
    }
  }
  printf("%d\n", MIN);

  return 0;
}

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();

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

    let keta = |x: usize| {
        let mut y = x;
        let mut res = 0;
        while y > 0 {
            res += 1;
            y /= 10;
        }
        res
    };

    let mut ans = 1 << 30;
    let mut i = 1;
    while i * i <= n {
        if n.is_multiple_of(i) {
            let a = i;
            let b = n / i;
            ans = min(ans, max(keta(a), keta(b)));
        }
        i += 1;
    }
    println!("{}", ans);
}


There is a chessboard of size $$$n$$$ by $$$n$$$. The square in the $$$i$$$-th row from top and $$$j$$$-th column from the left is labelled $$$(i,j)$$$.Currently, Gregor has some pawns in the $$$n$$$-th row. There are also enemy pawns in the $$$1$$$-st row. On one turn, Gregor moves one of his pawns. A pawn can move one square up (from $$$(i,j)$$$ to $$$(i-1,j)$$$) if there is no pawn in the destination square. Additionally, a pawn can move one square diagonally up (from $$$(i,j)$$$ to either $$$(i-1,j-1)$$$ or $$$(i-1,j+1)$$$) if and only if there is an enemy pawn in that square. The enemy pawn is also removed.Gregor wants to know what is the maximum number of his pawns that can reach row $$$1$$$?Note that only Gregor takes turns in this game, and the enemy pawns never move. Also, when Gregor's pawn reaches row $$$1$$$, it is stuck and cannot make any further moves.

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

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

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

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

        let mut c: u32 = 0;
        for p in 0..n {
            if white[p] == '0' {
                continue;
            }

            if p > 0 && black[p - 1] == '1' {
                black[p - 1] = '0';
                c += 1;
            } else if black[p] == '0' {
                black[p] = '0';
                c += 1;
            } else if p + 1 < n && black[p + 1] == '1' {
                black[p + 1] = '0';
                c += 1;
            }
        }
        println!("{}", c);
    }
}


While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface.  Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$?

int solution() {
  float L;
  float H;
  scanf("%f", &H);
  scanf("%f", &L);
  printf("%f", (L * L - H * H) / (2 * H));

  return 0;
}

fn solution() {
    let (h, l) = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse::<f64>().unwrap(),
            iter.next().unwrap().parse::<f64>().unwrap(),
        )
    };

    let answ = (l * l - h * h) / (2.0 * h);
    println!("{:.10}", answ);
}


Score : <var>100</var> points

Problem Statement

		                Kyoto University Programming Contest is a programming contest voluntarily held by some Kyoto University students.
		                This contest is abbreviated as Kyoto University Programming Contest and called KUPC.

		                source: Kyoto University Programming Contest Information

		            The problem-preparing committee met to hold this year's KUPC and <var>N</var> problems were proposed there.
		            The problems are numbered from <var>1</var> to <var>N</var> and the name of <var>i</var>-th problem is <var>P_i</var>.
		            However, since they proposed too many problems, they decided to divide them into some sets for several contests.

		            They decided to divide this year's KUPC into several KUPCs by dividing problems under the following conditions.

 One KUPC provides <var>K</var> problems.

 Each problem appears at most once among all the KUPCs.

 All the first letters of the problem names in one KUPC must be different.

		            You, one of the committee members, want to hold as many KUPCs as possible.
		            Write a program to find the maximum number of KUPCs that can be held this year.

Constraints

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

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

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

 All characters in <var>P_i</var> are capital letters.

		            Note that, for each <var>i</var> and <var>j</var> <var>(1 \leq i < j \leq N)</var>,
                    <var>P_i \neq P_j</var> are not necessarily satisfied.

Input

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

<var>N</var> <var>K</var>
<var>P_1</var>
:
<var>P_N</var>

Output

		                Print the maximum number of KUPCs that can be held on one line.

Sample Input 1

9 3
APPLE
ANT
ATCODER
BLOCK
BULL
BOSS
CAT
DOG
EGG

For example, three KUPCs can be held by dividing the problems as follows.

 First: APPLE, BLOCK, CAT

 Second: ANT, BULL, DOG

 Third: ATCODER, BOSS, EGG

Sample Output 1

3

Sample Input 2

3 2
KU
KYOUDAI
KYOTOUNIV

Sample Output 2

0

No KUPC can be held.

fn solution() {
    let mut s = String::new();
    use std::io::Read;
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut s = s.split_whitespace();
    let n: usize = s.next().unwrap().parse().unwrap();
    let k: usize = s.next().unwrap().parse().unwrap();
    let mut mp = std::collections::BTreeMap::new();
    for _ in 0..n {
        let p = s.next().unwrap().chars().next().unwrap();
        *mp.entry(p).or_insert(0) += 1;
    }
    let mut q = mp
        .values()
        .cloned()
        .collect::<std::collections::BinaryHeap<_>>();
    let mut ans = 0;
    while q.len() >= k {
        let mut r = (0..k)
            .map(|_| q.pop().unwrap() - 1)
            .filter(|&a| a != 0)
            .collect::<std::collections::BinaryHeap<_>>();
        q.append(&mut r);
        ans += 1;
    }
    println!("{}", ans);
}


To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height $$$h$$$ and width $$$w$$$, divided into $$$h \times w$$$ cells. Let $$$(i, j)$$$ denote the cell in the $$$i$$$-th row and the $$$j$$$-th column of the rectangle ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $$$(i, j)$$$ you put a plate into, at least one of the following conditions must be satisfied: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $$$(i, j)$$$ contains a plate, you can't put plates into cells $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.Put as many plates on the table as possible without violating the rules above.

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

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

        let h = it.next().unwrap();
        let w = it.next().unwrap();

        for i in 0..h {
            for j in 0..w {
                let s = if i % 2 == 0 && (j == 0 || j + 1 == w)
                    || j > 1 && j + 2 < w && j % 2 == 0 && (i == 0 || i + 1 == h)
                {
                    "1"
                } else {
                    "0"
                };
                output.write_all(s.as_bytes()).unwrap();
            }
            writeln!(&mut output).unwrap();
        }
        writeln!(&mut output).unwrap();
    }
}


An array $$$b$$$ of length $$$k$$$ is called good if its arithmetic mean is equal to $$$1$$$. More formally, if $$$$$$\frac{b_1 + \cdots + b_k}{k}=1.$$$$$$Note that the value $$$\frac{b_1+\cdots+b_k}{k}$$$ is not rounded up or down. For example, the array $$$[1,1,1,2]$$$ has an arithmetic mean of $$$1.25$$$, which is not equal to $$$1$$$.You are given an integer array $$$a$$$ of length $$$n$$$. In an operation, you can append a non-negative integer to the end of the array. What's the minimum number of operations required to make the array good?We have a proof that it is always possible with finitely many operations.

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

fn solution() {
    let (i, o) = (io::stdin(), io::stdout());
    let mut o = bw::new(o.lock());
    for l in i.lock().lines().skip(2).step_by(2) {
        let (c, s) = l
            .unwrap()
            .split(' ')
            .map(|w| w.parse::<i32>().unwrap())
            .fold((0, 0), |(c, s), x| (c + 1, s + x));
        writeln!(o, "{}", if s < c { 1 } else { s - c }).ok();
    }
}


Score : <var>700</var> points

Problem Statement

You are given a string <var>s</var> of length <var>n</var>.
Does a tree with <var>n</var> vertices that satisfies the following conditions exist?

The vertices are numbered <var>1,2,..., n</var>.

The edges are numbered <var>1,2,..., n-1</var>, and Edge <var>i</var> connects Vertex <var>u_i</var> and <var>v_i</var>.

If the <var>i</var>-th character in <var>s</var> is 1, we can have a connected component of size <var>i</var> by removing one edge from the tree.

If the <var>i</var>-th character in <var>s</var> is 0, we cannot have a connected component of size <var>i</var> by removing any one edge from the tree.

If such a tree exists, construct one such tree.

Constraints

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

<var>s</var> is a string of length <var>n</var> consisting of 0 and 1.

Input

Input is given from Standard Input in the following format:

<var>s</var>

Output

If a tree with <var>n</var> vertices that satisfies the conditions does not exist, print -1.

If a tree with <var>n</var> vertices that satisfies the conditions exist, print <var>n-1</var> lines.
The <var>i</var>-th line should contain <var>u_i</var> and <var>v_i</var> with a space in between.
If there are multiple trees that satisfy the conditions, any such tree will be accepted.

Sample Input 1

1111

Sample Output 1

-1

It is impossible to have a connected component of size <var>n</var> after removing one edge from a tree with <var>n</var> vertices.

Sample Input 2

1110

Sample Output 2

1 2
2 3
3 4

If Edge <var>1</var> or Edge <var>3</var> is removed, we will have a connected component of size <var>1</var> and another of size <var>3</var>. If Edge <var>2</var> is removed, we will have two connected components, each of size <var>2</var>.

Sample Input 3

1010

Sample Output 3

1 2
1 3
1 4

Removing any edge will result in a connected component of size <var>1</var> and another of size <var>3</var>.

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

    let S = buf_it.next().unwrap().chars().collect::<Vec<_>>();
    let N = S.len();

    if S[0] == '0' || S[N - 1] == '1' {
        println!("-1");
        return;
    }
    for i in 0..N - 2 {
        let j = N - 2 - i;
        if S[i] != S[j] {
            println!("-1");
            return;
        }
    }
    let mut j = 1;
    for i in 0..N - 1 {
        if S[i] == '1' {
            println!("{} {}", j, i + 2);
            j = i + 2;
        } else {
            println!("{} {}", j, i + 2);
        }
    }
}


$$$m$$$ chairs are arranged in a circle sequentially. The chairs are numbered from $$$0$$$ to $$$m-1$$$. $$$n$$$ people want to sit in these chairs. The $$$i$$$-th of them wants at least $$$a[i]$$$ empty chairs both on his right and left side. More formally, if the $$$i$$$-th person sits in the $$$j$$$-th chair, then no one else should sit in the following chairs: $$$(j-a[i]) \bmod m$$$, $$$(j-a[i]+1) \bmod m$$$, ... $$$(j+a[i]-1) \bmod m$$$, $$$(j+a[i]) \bmod m$$$.Decide if it is possible to sit down for all of them, under the given limitations.

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long n;
    long long m;
    long long sum = 0;
    scanf("%lld %lld", &n, &m);

    long long a[n];
    long long min = 10000000000;
    long long max = 0;

    for (int i = 0; i < n; i++) {
      scanf("%lld", &a[i]);
      sum += a[i];

      if (a[i] > max) {
        max = a[i];
      }

      if (a[i] < min) {
        min = a[i];
      }
    }

    sum = sum + max - min + n;

    if (n > m || sum > m) {
      printf("NO\n");

    }

    else {
      printf("YES\n");
    }
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let x: Vec<u64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let _n = x[0];
        let m = x[1];
        let a: Vec<u64> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let hi = a.iter().max().unwrap();
        let lo = a.iter().min().unwrap();
        let total = a.len() as u64 + a.iter().sum::<u64>() + hi - lo;
        println!("{}", if total <= m { "YES" } else { "NO" });
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> slimes lining up from left to right. The colors of these slimes will be given as a string <var>S</var> of length <var>N</var> consisting of lowercase English letters. The <var>i</var>-th slime from the left has the color that corresponds to the <var>i</var>-th character of <var>S</var>.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10

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

  char s[100001];
  scanf("%s", s);

  int ans = 1;
  for (int i = 1; i < N; i++) {
    if (s[i] != s[i - 1]) {
      ans++;
    }
  }
  printf("%d", ans);
  return 0;
}

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

    let mut queue = VecDeque::<char>::new();
    for slime in s.chars() {
        match queue.pop_back() {
            None => queue.push_back(slime),
            Some(back) => {
                queue.push_back(back);
                if slime != back {
                    queue.push_back(slime);
                }
            }
        }
    }
    print!("{}", queue.len())
}


Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $$$n$$$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $$$i$$$-th from the left sushi as $$$t_i$$$, where $$$t_i = 1$$$ means it is with tuna, and $$$t_i = 2$$$ means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $$$[2, 2, 2, 1, 1, 1]$$$ is valid, but subsegment $$$[1, 2, 1, 2, 1, 2]$$$ is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.

int solution() {

  int num_sushis = 0;
  int sushi[100000];
  int num_ones = 0;
  int num_twos = 0;
  int current;
  int max = 0;
  scanf("%d", &num_sushis);
  for (int i = 0; i < num_sushis; i++) {
    scanf("%d", &sushi[i]);
  }
  current = sushi[0];
  for (int i = 0; i < num_sushis; i++) {
    if (sushi[i] == 1) {
      if (current == 2) {
        num_ones = 0;
      }
      num_ones++;
    }
    if (sushi[i] == 2) {
      if (current == 1) {
        num_twos = 0;
      }
      num_twos++;
    }

    if (num_ones >= num_twos && num_twos != 0) {
      if (num_twos * 2 > max) {
        max = num_twos * 2;
      }
    }
    if (num_twos >= num_ones && num_ones != 0) {
      if (num_ones * 2 > max) {
        max = num_ones * 2;
      }
    }
    current = sushi[i];
  }
  printf("%d", max);
}

fn solution() {
    let stream = io::stdin();
    let line = stream
        .lock()
        .lines()
        .nth(1)
        .expect("Iterator is inf")
        .expect("Blah");

    let result = line.trim().split(" ").filter_map(|x| x.parse::<u8>().ok());
    let mut cnts = [0u64; 2];
    let mut prev = 0u8;
    let mut answer = 0u64;

    for x in result {
        let counter = x as usize - 1;
        if x == prev {
            cnts[counter] += 1;
        } else {
            answer = answer.max(*cnts.iter().min().expect("ads"));
            prev = x;
            cnts[counter] = 1;
        }
    }
    answer = answer.max(*cnts.iter().min().expect("ads"));
    println!("{}", 2 * answer);
}


Score: <var>100</var> points

Problem Statement

A triple of numbers is said to be poor when two of those numbers are equal but the other number is different from those two numbers.

You will be given three integers <var>A</var>, <var>B</var>, and <var>C</var>. If this triple is poor, print Yes; otherwise, print No.

Constraints

<var>A</var>, <var>B</var>, and <var>C</var> are all integers between <var>1</var> and <var>9</var> (inclusive).

Input

Input is given from Standard Input in the following format:

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

Output

If the given triple is poor, print Yes; otherwise, print No.

Sample Input 1

5 7 5

Sample Output 1

Yes

<var>A</var> and <var>C</var> are equal, but <var>B</var> is different from those two numbers, so this triple is poor.

Sample Input 2

4 4 4

Sample Output 2

No

<var>A</var>, <var>B</var>, and <var>C</var> are all equal, so this triple is not poor.

Sample Input 3

4 9 6

Sample Output 3

No

Sample Input 4

3 3 4

Sample Output 4

Yes

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

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

  if (a == b && a != c) {
    printf("Yes");
  }
  if (b == c && a != c) {
    printf("Yes");
  }
  if (a == c && a != b) {
    printf("Yes");
  }
  if (a == c && a == b) {
    printf("No");
  }
  if (a != c && a != b && b != c) {
    printf("No");
  }
  return 0;
}

fn solution() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line.");
    let x: Vec<&str> = input.split_whitespace().collect();
    if x.len() == 3 {
        let mut count = 0;
        if x[0] == x[1] {
            count += 1;
        }
        if x[0] == x[2] {
            count += 1;
        }
        if x[2] == x[1] {
            count += 1;
        }
        if count == 1 {
            println!("Yes");
        } else {
            println!("No")
        }
    }
}


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

int solution() {
  int n;
  int i;
  int j;
  int arr[2000];

  scanf("%d", &n);
  char s[1003];
  scanf("%s", s);
  for (i = 0; i < n; i++) {
    arr[i] = s[i] - '0';
  }
  int start = 0;
  int min[1003];
  for (i = 0; i < n; i++) {
    min[i] = 10;
  }
  int curr[1003];
  for (i = 0; i < n; i++) {
    start = i;
    int jump = 10 - arr[i];
    for (j = 0; j < n; j++) {
      curr[j] = (arr[(j + start) % n] + jump) % 10;
    }
    j = 0;
    while (j < n && (min[j] == curr[j])) {
      j++;
    }
    if (j < n && min[j] > curr[j]) {
      int k;
      for (k = 0; k < n; k++) {
        min[k] = curr[k];
      }
    }
  }
  for (i = 0; i < n; i++) {
    printf("%d", min[i]);
  }
  printf("\n");
  return 0;
}

fn solution() {
    let n = {
        let mut line = String::new();
        stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        iter.next().unwrap().parse::<usize>().unwrap()
    };

    let mut line = String::new();
    stdin().read_line(&mut line).unwrap();
    let line: Vec<u8> = line.trim().as_bytes().iter().map(|&it| it - b'0').collect();

    let mut answ = line.to_owned();
    for i in 0..10 {
        for shift in 0..n {
            let variant: Vec<u8> = line
                .iter()
                .skip(shift)
                .chain(line.iter().take(shift))
                .map(|&it| (it + i) % 10)
                .collect();

            for i in 0..n {
                if variant[i] == answ[i] {
                    continue;
                } else if variant[i] < answ[i] {
                    answ = variant;
                    break;
                } else {
                    break;
                }
            }
        }
    }
    answ.iter().for_each(|it| print!("{}", it));
    println!()
}


You are given a matrix with $$$n$$$ rows (numbered from $$$1$$$ to $$$n$$$) and $$$m$$$ columns (numbered from $$$1$$$ to $$$m$$$). A number $$$a_{i, j}$$$ is written in the cell belonging to the $$$i$$$-th row and the $$$j$$$-th column, each number is either $$$0$$$ or $$$1$$$.A chip is initially in the cell $$$(1, 1)$$$, and it will be moved to the cell $$$(n, m)$$$. During each move, it either moves to the next cell in the current row, or in the current column (if the current cell is $$$(x, y)$$$, then after the move it can be either $$$(x + 1, y)$$$ or $$$(x, y + 1)$$$). The chip cannot leave the matrix.Consider each path of the chip from $$$(1, 1)$$$ to $$$(n, m)$$$. A path is called palindromic if the number in the first cell is equal to the number in the last cell, the number in the second cell is equal to the number in the second-to-last cell, and so on.Your goal is to change the values in the minimum number of cells so that every path is palindromic.

fn solution() {
    let mut s: String = String::new();
    stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut out = Vec::new();
    for _ in 0..t {
        let h: usize = itr.next().unwrap().parse().unwrap();
        let w: usize = itr.next().unwrap().parse().unwrap();
        let g: Vec<Vec<usize>> = (0..h)
            .map(|_| {
                (0..w)
                    .map(|_| itr.next().unwrap().parse().unwrap())
                    .collect()
            })
            .collect();
        let mut sum = vec![(0, 0); h + w];
        for i in 0..h {
            for j in 0..w {
                if g[i][j] == 0 {
                    sum[i + j].0 += 1;
                } else {
                    sum[i + j].1 += 1;
                }
            }
        }
        let last = h + w - 2;
        let mut ans = 0;

        for i in 0..last / 2 {
            let zero = sum[i].0 + sum[last - i].0;
            let one = sum[i].1 + sum[last - i].1;
            ans += min(zero, one);
        }
        if (h + w) % 2 == 1 {
            let i = last / 2;
            let j = last / 2 + 1;
            let zero = sum[i].0 + sum[j].0;
            let one = sum[i].1 + sum[j].1;
            ans += min(zero, one);
        }
        writeln!(out, "{}", ans).ok();
    }
    stdout().write_all(&out).unwrap();
}


Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.

fn solution() {
    let inputstatus = 1;

    let mut buf = String::new();
    let filename = "inputrust.txt";

    if inputstatus == 0 {
        let mut f = File::open(filename).expect("file not found");
        f.read_to_string(&mut buf)
            .expect("something went wrong reading the file");
    } else {
        std::io::stdin().read_to_string(&mut buf).unwrap();
    }

    let mut iter = buf.split_whitespace();
    let s: Vec<char> = iter.next().unwrap().chars().collect();
    let t: Vec<char> = iter.next().unwrap().chars().collect();
    let mut ans = String::new();
    let n: usize = t.len();
    let mut a = 0;

    for i in 0..n {
        if s[i] == t[i] {
            ans.push(s[i]);
        } else {
            if a == 0 {
                ans.push(s[i]);
            } else {
                ans.push(t[i]);
            }
            a ^= 1;
        }
    }
    if a == 0 {
        println!("{}", ans);
    } else {
        println!("impossible");
    }
}


Given an array $$$a$$$ of length $$$n$$$, you can do at most $$$k$$$ operations of the following type on it:  choose $$$2$$$ different elements in the array, add $$$1$$$ to the first, and subtract $$$1$$$ from the second. However, all the elements of $$$a$$$ have to remain non-negative after this operation. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$.

int solution() {

  int t = 0;
  scanf("%d", &t);

  int n = 0;
  int k = 0;
  int index = 0;
  int a[101] = {0};

  while (t-- > 0) {
    index = 0;

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

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

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

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

      while (a[index] <= 0) {
        index++;
        if (index == (n - 1)) {
          break;
        }
      }
      if (index == (n - 1)) {
        break;
      }

      a[index]--;

      a[n - 1]++;
    }

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

    printf("\n");
  }
  return 0;
}

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

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

    let tt: u32 = input.trim().parse().unwrap();

    for _ in 0..tt {
        input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let v: Vec<&str> = input.trim().split(" ").collect();
        let n: usize = v[0].parse().unwrap();
        let k: usize = v[1].parse().unwrap();

        input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        let v: Vec<&str> = input.trim().split(" ").collect();
        let mut a = Vec::<u32>::with_capacity(n);
        for i in 0..n {
            a.push(v[i].parse::<u32>().unwrap());
        }
        let mut f: usize = 0;
        for _ in 0..k {
            while f < n - 1 && a[f] == 0 {
                f += 1;
            }
            if f == n - 1 {
                break;
            }
            a[f] -= 1;
            a[n - 1] += 1
        }
        for i in 0..n {
            if i == 0 {
                print!("{}", a[i]);
            } else {
                print!(" {}", a[i]);
            }
        }
        println!();
    }
}


Julia is going to cook a chicken in the kitchen of her dormitory. To save energy, the stove in the kitchen automatically turns off after k minutes after turning on.During cooking, Julia goes to the kitchen every d minutes and turns on the stove if it is turned off. While the cooker is turned off, it stays warm. The stove switches on and off instantly.It is known that the chicken needs t minutes to be cooked on the stove, if it is turned on, and 2t minutes, if it is turned off. You need to find out, how much time will Julia have to cook the chicken, if it is considered that the chicken is cooked evenly, with constant speed when the stove is turned on and at a constant speed when it is turned off.

int solution() {
  long long int k;
  long long int d;
  long long int t;
  scanf("%lld %lld %lld", &k, &d, &t);
  if (k % d == 0 || t <= k) {
    printf("%lf", (double)t);
  } else {
    long long int x;
    if (d >= k) {
      x = d;
    } else {
      long long int c = k / d;
      x = (c + 1) * d;
    }

    t *= 2;

    long long int p = (2 * k) + (x - k);

    long long int a = t / p;

    long long int b = t - (a * p);

    double T = (double)a * x;

    if (b <= 2 * k) {
      T = T + (double)b / 2;
    } else {
      T = T + k;
      T = T + ((double)b - 2 * k);
    }
    printf("%lf", T);
  }
  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 k: u64 = it.next().unwrap().parse().unwrap();
    let d: u64 = it.next().unwrap().parse().unwrap();
    let t: u64 = it.next().unwrap().parse().unwrap();

    let c = (k - 1) / d + 1;
    let cl = d * c;

    let pc = cl + k;

    let cc = (2 * t) / pc;

    let rh = (2 * t) % pc;

    let rt = if rh < 2 * k {
        rh as f64 / 2.0
    } else {
        (rh - k) as f64
    };

    let ans = (cl * cc) as f64 + rt;

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


In the pet store on sale there are:  $$$a$$$ packs of dog food;  $$$b$$$ packs of cat food;  $$$c$$$ packs of universal food (such food is suitable for both dogs and cats). Polycarp has $$$x$$$ dogs and $$$y$$$ cats. Is it possible that he will be able to buy food for all his animals in the store? Each of his dogs and each of his cats should receive one pack of suitable food for it.

int solution(int argc, char const *argv[]) {
  int t = 0;
  scanf("%d", &t);

  unsigned long a = 0;
  unsigned long b = 0;
  unsigned long c = 0;
  unsigned long x = 0;
  unsigned long y = 0;

  unsigned long common_pets = 0;

  unsigned long results[10000];

  for (int i = 0; i < t; i++) {
    a = b = c = x = y = 0;
    common_pets = 0;

    scanf("%lu %lu %lu %lu %lu", &a, &b, &c, &x, &y);

    if (x > 0 && a > 0) {
      if (x > a) {
        x = x - a;
      } else {
        x = 0;
      }
    }

    if (y > 0 && b > 0) {
      if (y > b) {
        y = y - b;
      } else {
        y = 0;
      }
    }

    if (x > 0 || y > 0) {
      common_pets = x + y;

      if (common_pets > 0 && c > 0) {
        if (c >= common_pets) {
          common_pets = 0;
        } else {
          common_pets += 1;
        }
      }
    }

    if (common_pets == 0) {

      results[i] = 1;
    } else {
      results[i] = 0;
    }
  }

  for (int m = 0; m < t; m++) {
    if (results[m] == 1) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }

  return 0;
}

fn solution() {
    let mut t = String::new();
    stdin().read_line(&mut t);
    let t = t.trim().parse::<usize>().unwrap();

    for _ in 0..t {
        let mut buf = String::new();
        stdin().read_line(&mut buf);

        let mut v = Vec::with_capacity(5);
        for i in buf.split_whitespace() {
            v.push(i.parse::<i64>().unwrap())
        }

        v[3] -= v[0];
        if v[3] < 0 {
            v[3] = 0
        }
        v[4] -= v[1];
        if v[4] < 0 {
            v[4] = 0
        }
        v[2] -= v[3] + v[4];

        if v[2] < 0 {
            println!("no");
        } else {
            println!("yes");
        }
    }
}


The game of Berland poker is played with a deck of $$$n$$$ cards, $$$m$$$ of which are jokers. $$$k$$$ players play this game ($$$n$$$ is divisible by $$$k$$$).At the beginning of the game, each player takes $$$\frac{n}{k}$$$ cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he gets the number of points equal to $$$x - y$$$, where $$$x$$$ is the number of jokers in the winner's hand, and $$$y$$$ is the maximum number of jokers among all other players. If there are two or more players with maximum number of jokers, all of them are winners and they get $$$0$$$ points.Here are some examples:  $$$n = 8$$$, $$$m = 3$$$, $$$k = 2$$$. If one player gets $$$3$$$ jokers and $$$1$$$ plain card, and another player gets $$$0$$$ jokers and $$$4$$$ plain cards, then the first player is the winner and gets $$$3 - 0 = 3$$$ points;  $$$n = 4$$$, $$$m = 2$$$, $$$k = 4$$$. Two players get plain cards, and the other two players get jokers, so both of them are winners and get $$$0$$$ points;  $$$n = 9$$$, $$$m = 6$$$, $$$k = 3$$$. If the first player gets $$$3$$$ jokers, the second player gets $$$1$$$ joker and $$$2$$$ plain cards, and the third player gets $$$2$$$ jokers and $$$1$$$ plain card, then the first player is the winner, and he gets $$$3 - 2 = 1$$$ point;  $$$n = 42$$$, $$$m = 0$$$, $$$k = 7$$$. Since there are no jokers, everyone gets $$$0$$$ jokers, everyone is a winner, and everyone gets $$$0$$$ points. Given $$$n$$$, $$$m$$$ and $$$k$$$, calculate the maximum number of points a player can get for winning the game.

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let t: usize = itr.next().unwrap().parse().unwrap();
    let mut out = Vec::new();
    for _ in 0..t {
        let n: usize = itr.next().unwrap().parse().unwrap();
        let m: usize = itr.next().unwrap().parse().unwrap();
        let k: usize = itr.next().unwrap().parse().unwrap();

        let one = n / k;
        let max_joker = std::cmp::min(one, m);
        let rem_joker = (m - max_joker + k - 2) / (k - 1);
        writeln!(out, "{}", max_joker - rem_joker).ok();
    }
    stdout().write_all(&out).unwrap();
}


YouKn0wWho has an integer sequence $$$a_1, a_2, \ldots, a_n$$$. He will perform the following operation until the sequence becomes empty: select an index $$$i$$$ such that $$$1 \le i \le |a|$$$ and $$$a_i$$$ is not divisible by $$$(i + 1)$$$, and erase this element from the sequence. Here $$$|a|$$$ is the length of sequence $$$a$$$ at the moment of operation. Note that the sequence $$$a$$$ changes and the next operation is performed on this changed sequence.For example, if $$$a=[3,5,4,5]$$$, then he can select $$$i = 2$$$, because $$$a_2 = 5$$$ is not divisible by $$$i+1 = 3$$$. After this operation the sequence is $$$[3,4,5]$$$.Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation.

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

  while (testcase--) {
    int n;
    scanf("%d", &n);
    int a[n];

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

    int ok = 1;
    for (int i = 0; i < n; i++) {
      int flag = 0;
      for (int j = 2; j <= i + 2; j++) {
        if (a[i] % j != 0) {
          flag = 1;
          break;
        }
      }
      ok &= flag;
    }

    if (ok) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }

  return 0;
}

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

    let mut input_iter = input.split_whitespace();
    let mut next_int = || input_iter.next().unwrap().parse::<i64>().unwrap();

    'task: for _ in 0..next_int() {
        let n = next_int() as usize;

        let mut arr = vec![];
        arr.resize_with(n, &mut next_int);

        'outer: for i in 0..n {
            for j in (0..=i).rev() {
                if arr[i] % (j + 2) as i64 != 0 {
                    continue 'outer;
                }
            }

            println!("NO");
            continue 'task;
        }

        println!("YES");
    }

    Ok(())
}


Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1

int solution() {
  int i;
  int j;
  int a;
  int num;
  int y = 0;
  int l;
  int h;
  int key;

  scanf("%d", &a);

  int list[a];
  char input[12];

  for (i = 0; i < a; i++) {
    scanf("%s %d", input, &num);

    if (input[0] == 'i') {
      list[i] = num;
    }

    else if (input[6] == 'F') {
      i -= 2;
      a -= 2;
    }

    else if (input[6] == 'L') {
      i--;
      a--;
      y++;
    }

    else {
      i--;
      a--;
      l = 0;
      for (j = i; j >= 0; j--) {
        if (l > 0) {
          break;
        }
        if (num == list[j]) {
          key = 0;
          h = i - j;
          l++;

          while (h != key++) {
            list[j + key - 1] = list[j + 1 + key - 1];
          }
          i--;
          a--;
        }
      }
    }
  }

  for (i = 0; i < a - y; i++) {
    if (i == a - y - 1) {
      printf("%d\n", list[a - 1 - i]);
    } else {
      printf("%d ", list[a - 1 - i]);
    }
  }
  return 0;
}

fn solution() {
    let stdin = std::io::stdin();
    let mut buf = String::new();
    stdin.read_line(&mut buf).ok();
    let n: usize = buf.trim().parse().unwrap_or(0);

    let mut dll = Vec::new();

    let mut head = 0;

    for _ in 0..n {
        let mut buf = String::new();
        stdin.read_line(&mut buf).ok();
        let vec: Vec<&str> = buf.split_whitespace().collect();

        if vec[0] == "insert" {
            dll.push(vec[1].parse().unwrap_or(0));
        } else if vec[0] == "delete" {
            for j in (head..dll.len()).rev() {
                if vec[1].parse().unwrap_or(0) == dll[j] {
                    dll.remove(j);
                    break;
                }
            }
        } else if vec[0] == "deleteFirst" {
            dll.pop();
        } else if vec[0] == "deleteLast" {
            head += 1;
        }
    }
    for i in (head..dll.len()).rev() {
        print!("{}", dll[i]);
        if i == head {
            break;
        }
        print!(" ");
    }
    println!();
}


Andre has very specific tastes. Recently he started falling in love with arrays.Andre calls an nonempty array $$$b$$$ good, if sum of its elements is divisible by the length of this array. For example, array $$$[2, 3, 1]$$$ is good, as sum of its elements — $$$6$$$ — is divisible by $$$3$$$, but array $$$[1, 1, 2, 3]$$$ isn't good, as $$$7$$$ isn't divisible by $$$4$$$. Andre calls an array $$$a$$$ of length $$$n$$$ perfect if the following conditions hold:   Every nonempty subarray of this array is good.  For every $$$i$$$ ($$$1 \le i \le n$$$), $$$1 \leq a_i \leq 100$$$. Given a positive integer $$$n$$$, output any perfect array of length $$$n$$$. We can show that for the given constraints such an array always exists.An array $$$c$$$ is a subarray of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

int solution() {
  int n = 0;

  scanf("%d", &n);

  int test[100];

  int temp = 0;

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

  int arr[200];

  for (int i = 0; i < 200; i++) {
    arr[i] = 1;
  }

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

fn solution() {
    let mut inp = String::new();
    stdin().read_line(&mut inp).unwrap();
    let t: u16 = inp.trim().parse().unwrap();
    inp.clear();
    for _ in 0..t {
        stdin().read_line(&mut inp).unwrap();
        let n: u16 = inp.trim().parse().unwrap();
        for _ in 1..n {
            print!("3 ");
        }
        println!("3");
        inp.clear();
    }
}


Alice and Bob received $$$n$$$ candies from their parents. Each candy weighs either 1 gram or 2 grams. Now they want to divide all candies among themselves fairly so that the total weight of Alice's candies is equal to the total weight of Bob's candies.Check if they can do that.Note that candies are not allowed to be cut in half.

int solution() {
  int T;
  scanf("%d", &T);
  while (T--) {
    int arr[100];
    int n;
    scanf("%d", &n);
    int num = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      if (arr[i] == 2) {
        num++;
      }
    }
    if ((n % 2 && num % 2 && n != num) || (n % 2 == 0 && num % 2 == 0)) {
      printf("YES\n");
    } else {
      printf("NO\n");
    }
  }
  return 0;
}

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

    io::stdin().read_line(&mut t).unwrap();

    for _ in 0..t.trim().parse::<i32>().unwrap() {
        let mut n = String::new();

        io::stdin().read_line(&mut n).unwrap();

        let mut candies = String::new();

        io::stdin().read_line(&mut candies).unwrap();

        candies = candies.trim().to_string();

        let ones = candies.split(" ").filter(|&x| x == "1").count();
        let twos = candies.split(" ").collect::<Vec<&str>>().len() - ones;

        if ones % 2 == 1 || (ones == 0 && twos % 2 == 1) {
            println!("NO");
            continue;
        }

        println!("YES");
    }
}