The only difference between easy and hard versions is constraints.There are $$$n$$$ kids, each of them is reading a unique book. At the end of any day, the $$$i$$$-th kid will give his book to the $$$p_i$$$-th kid (in case of $$$i = p_i$$$ the kid will give his book to himself). It is guaranteed that all values of $$$p_i$$$ are distinct integers from $$$1$$$ to $$$n$$$ (i.e. $$$p$$$ is a permutation). The sequence $$$p$$$ doesn't change from day to day, it is fixed.For example, if $$$n=6$$$ and $$$p=[4, 6, 1, 3, 5, 2]$$$ then at the end of the first day the book of the $$$1$$$-st kid will belong to the $$$4$$$-th kid, the $$$2$$$-nd kid will belong to the $$$6$$$-th kid and so on. At the end of the second day the book of the $$$1$$$-st kid will belong to the $$$3$$$-th kid, the $$$2$$$-nd kid will belong to the $$$2$$$-th kid and so on.Your task is to determine the number of the day the book of the $$$i$$$-th child is returned back to him for the first time for every $$$i$$$ from $$$1$$$ to $$$n$$$.Consider the following example: $$$p = [5, 1, 2, 4, 3]$$$. The book of the $$$1$$$-st kid will be passed to the following kids:  after the $$$1$$$-st day it will belong to the $$$5$$$-th kid,  after the $$$2$$$-nd day it will belong to the $$$3$$$-rd kid,  after the $$$3$$$-rd day it will belong to the $$$2$$$-nd kid,  after the $$$4$$$-th day it will belong to the $$$1$$$-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer $$$q$$$ independent queries.

int solution(void) {
  int n;
  int q;
  int *a = calloc(1000002, sizeof(*a));
  int *b = calloc(1000002, sizeof(*a));
  int *temp = calloc(1000002, sizeof(*temp));
  scanf("%d", &q);
  for (int j = 0; j < q; j++) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%d", &a[i]);
    }
    int k = 1;
    while (k != n + 1) {
      if (a[k]) {
        int tmp = a[k];
        int tmp2 = tmp;
        int counter = 0;
        int mas_counter = 0;
        do {
          tmp2 = a[tmp2];
          counter++;
          temp[mas_counter++] = tmp2;
        } while (tmp != tmp2);
        for (int f = 0; f < mas_counter; f++) {
          b[temp[f]] = counter;
          a[temp[f]] = 0;
        }
      }
      k++;
    }
    for (int l = 1; l <= n; l++) {
      printf("%d ", b[l]);
    }
    printf("\n");
  }
  free(a);
  free(b);
  free(temp);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut input = stdin.lock();
    let mut line = String::new();
    input.read_line(&mut line).unwrap();
    let mut queries: i16 = line.trim().parse().unwrap();
    line.clear();
    while queries > 0 {
        input.read_line(&mut line).unwrap();
        let total = line.trim().parse().unwrap();
        line.clear();
        input.read_line(&mut line).unwrap();
        let children = line.split_whitespace();
        let mut permutation = Vec::with_capacity(total);
        for child in children {
            permutation.push(child.parse::<usize>().unwrap() - 1);
        }
        line.clear();
        let mut loop_items = Vec::new();
        let mut books = vec![0; total];
        for book in 0..books.len() {
            if books[book] != 0 {
                continue;
            }
            let mut cur = book;
            loop {
                loop_items.push(cur);
                cur = permutation[cur];
                if cur == book {
                    break;
                }
            }
            let length = loop_items.len();
            for item in 0..loop_items.len() {
                books[loop_items[item]] = length;
            }
            loop_items.clear();
        }
        loop_items.shrink_to_fit();
        for book in books {
            print!("{} ", book);
        }
        println!();
        queries -= 1;
    }
}


You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operations on it:  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(0 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j+x$$$ for all $$$(1 \le j \le i)$$$, which means add $$$x$$$ to all the elements in the prefix ending at $$$i$$$.  choose an index $$$i$$$ $$$(1 \le i \le n)$$$, an integer $$$x$$$ $$$(1 \le x \le 10^6)$$$, and replace $$$a_j$$$ with $$$a_j \% x$$$ for all $$$(1 \le j \le i)$$$, which means replace every element in the prefix ending at $$$i$$$ with the remainder after dividing it by $$$x$$$. Can you make the array strictly increasing in no more than $$$n+1$$$ operations?

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

    let mut l2 = String::new();
    stdin().read_line(&mut l2);
    let l2: Vec<&str> = l2.trim().split(" ").collect();
    let mut v: Vec<usize> = Vec::new();
    v.push(0);
    for x in l2 {
        v.push(x.parse().unwrap());
    }
    println!("{}", n + 1);
    let mut add = 0;
    for i in (1..n + 1).rev() {
        let tmp = (n + i - 1) - ((v[i] + add) % n);
        add += tmp;
        println!("1 {} {}", i, tmp);
    }
    println!("2 {} {}", n, n);
}


Score : <var>500</var> points

Problem Statement

In Takahashi Kingdom, which once existed, there are <var>N</var> cities, and some pairs of cities are connected bidirectionally by roads.
The following are known about the road network:

People traveled between cities only through roads. It was possible to reach any city from any other city, via intermediate cities if necessary.

Different roads may have had different lengths, but all the lengths were positive integers.

Snuke the archeologist found a table with <var>N</var> rows and <var>N</var> columns, <var>A</var>, in the ruin of Takahashi Kingdom.
He thought that it represented the shortest distances between the cities along the roads in the kingdom.

Determine whether there exists a road network such that for each <var>u</var> and <var>v</var>, the integer <var>A_{u, v}</var> at the <var>u</var>-th row and <var>v</var>-th column of <var>A</var> is equal to the length of the shortest path from City <var>u</var> to City <var>v</var>.
If such a network exist, find the shortest possible total length of the roads.

Constraints

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

If <var>i ≠ j</var>, <var>1 \leq A_{i, j} = A_{j, i} \leq 10^9</var>.

<var>A_{i, i} = 0</var>

Inputs

Input is given from Standard Input in the following format:

<var>N</var>
<var>A_{1, 1}</var> <var>A_{1, 2}</var> <var>...</var> <var>A_{1, N}</var>
<var>A_{2, 1}</var> <var>A_{2, 2}</var> <var>...</var> <var>A_{2, N}</var>
<var>...</var>
<var>A_{N, 1}</var> <var>A_{N, 2}</var> <var>...</var> <var>A_{N, N}</var>

Outputs

If there exists no network that satisfies the condition, print -1.
If it exists, print the shortest possible total length of the roads.

Sample Input 1

3
0 1 3
1 0 2
3 2 0

Sample Output 1

3

The network below satisfies the condition:

City <var>1</var> and City <var>2</var> is connected by a road of length <var>1</var>.

City <var>2</var> and City <var>3</var> is connected by a road of length <var>2</var>.

City <var>3</var> and City <var>1</var> is not connected by a road.

Sample Input 2

3
0 1 3
1 0 1
3 1 0

Sample Output 2

-1

As there is a path of length <var>1</var> from City <var>1</var> to City <var>2</var> and City <var>2</var> to City <var>3</var>, there is a path of length <var>2</var> from City <var>1</var> to City <var>3</var>.
However, according to the table, the shortest distance between City <var>1</var> and City <var>3</var> must be <var>3</var>.

Thus, we conclude that there exists no network that satisfies the condition.

Sample Input 3

5
0 21 18 11 28
21 0 13 10 26
18 13 0 23 13
11 10 23 0 17
28 26 13 17 0

Sample Output 3

82

Sample Input 4

3
0 1000000000 1000000000
1000000000 0 1000000000
1000000000 1000000000 0

Sample Output 4

3000000000

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

    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut g = vec![vec![0; n]; n];

    for i in 0..n {
        for j in 0..n {
            g[i][j] = itr.next().unwrap().parse().unwrap();
        }
    }
    let mut ok = true;
    let mut need = vec![vec![true; n]; n];
    for k in 0..n {
        for i in 0..n {
            for j in 0..n {
                if i == j || j == k || k == i {
                    continue;
                }
                if g[i][j] > g[i][k] + g[k][j] {
                    ok = false;
                }
                if g[i][j] == g[i][k] + g[k][j] {
                    need[i][j] = false;
                }
            }
        }
    }
    if ok {
        let mut ans = 0i64;
        for i in 0..n {
            for j in 0..i {
                ans += if need[i][j] { g[i][j] } else { 0 };
            }
        }
        println!("{}", ans);
    } else {
        println!("-1");
    }
}


Many computer strategy games require building cities, recruiting army, conquering tribes, collecting resources. Sometimes it leads to interesting problems. Let's suppose that your task is to build a square city. The world map uses the Cartesian coordinates. The sides of the city should be parallel to coordinate axes. The map contains mines with valuable resources, located at some points with integer coordinates. The sizes of mines are relatively small, i.e. they can be treated as points. The city should be built in such a way that all the mines are inside or on the border of the city square. Building a city takes large amount of money depending on the size of the city, so you have to build the city with the minimum area. Given the positions of the mines find the minimum possible area of the city.

int solution() {
  int n;
  scanf("%d", &n);
  int arrx[n];
  int arry[n];
  for (int i = 0; i < n; i++) {
    scanf("%d %d", &arrx[i], &arry[i]);
  }
  int minx = 1000000000;
  int miny = 1000000000;
  int maxx = -1000000000;
  int maxy = -1000000000;
  for (int i = 0; i < n; i++) {
    if (arrx[i] > maxx) {
      maxx = arrx[i];
    }
    if (arrx[i] < minx) {
      minx = arrx[i];
    }
    if (arry[i] > maxy) {
      maxy = arry[i];
    }
    if (arry[i] < miny) {
      miny = arry[i];
    }
  }
  long long a = maxx - minx;
  long long b = maxy - miny;
  if (a > b) {
    printf("%lld\n", a * a);
  } else {
    printf("%lld\n", b * b);
  }
}

fn solution() {
    let mut input_text = String::new();
    io::stdin()
        .read_line(&mut input_text)
        .expect("failed to read from stdin");

    let n: usize = input_text.trim().parse().unwrap();
    let mut min_x: i32 = 0x3f3f3f3f;
    let mut min_y: i32 = 0x3f3f3f3f;
    let mut max_x: i32 = -0x3f3f3f3f;
    let mut max_y: i32 = -0x3f3f3f3f;

    for _ in 0..n {
        input_text = String::new();
        io::stdin()
            .read_line(&mut input_text)
            .expect("failed to read from stdin");

        let inputs: Vec<i32> = input_text
            .trim()
            .split(" ")
            .map(|x| x.parse().expect("Not an integer!"))
            .collect();

        let x = inputs[0];
        let y = inputs[1];

        min_x = std::cmp::min(min_x, x);
        min_y = std::cmp::min(min_y, y);
        max_x = std::cmp::max(max_x, x);
        max_y = std::cmp::max(max_y, y);
    }
    let d: i32 = std::cmp::max(max_x - min_x, max_y - min_y);
    println!("{}", (d as i64) * (d as i64));
}


Score : <var>300</var> points

Problem Statement

AtCoDeer the deer is going on a trip in a two-dimensional plane.
In his plan, he will depart from point <var>(0, 0)</var> at time <var>0</var>, then for each <var>i</var> between <var>1</var> and <var>N</var> (inclusive), he will visit point <var>(x_i,y_i)</var> at time <var>t_i</var>.

If AtCoDeer is at point <var>(x, y)</var> at time <var>t</var>, he can be at one of the following points at time <var>t+1</var>: <var>(x+1,y)</var>, <var>(x-1,y)</var>, <var>(x,y+1)</var> and <var>(x,y-1)</var>.
Note that he cannot stay at his place.
Determine whether he can carry out his plan.

Constraints

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

<var>0</var> <var>≤</var> <var>x_i</var> <var>≤</var> <var>10^5</var>

<var>0</var> <var>≤</var> <var>y_i</var> <var>≤</var> <var>10^5</var>

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

<var>t_i</var> <var><</var> <var>t_{i+1}</var> (<var>1</var> <var>≤</var> <var>i</var> <var>≤</var> <var>N-1</var>)

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>t_1</var> <var>x_1</var> <var>y_1</var>
<var>t_2</var> <var>x_2</var> <var>y_2</var>
<var>:</var>
<var>t_N</var> <var>x_N</var> <var>y_N</var>

Output

If AtCoDeer can carry out his plan, print Yes; if he cannot, print No.

Sample Input 1

2
3 1 2
6 1 1

Sample Output 1

Yes

For example, he can travel as follows: <var>(0,0)</var>, <var>(0,1)</var>, <var>(1,1)</var>, <var>(1,2)</var>, <var>(1,1)</var>, <var>(1,0)</var>, then <var>(1,1)</var>.

Sample Input 2

1
2 100 100

Sample Output 2

No

It is impossible to be at <var>(100,100)</var> two seconds after being at <var>(0,0)</var>.

Sample Input 3

2
5 1 1
100 1 1

Sample Output 3

No

int solution(void) {
  int x = 0;
  int y = 1;
  int a = 0;
  int b = 0;
  int c = 0;
  int d = 0;
  int e = 0;
  int f = 0;
  int g = 0;
  int h = 0;
  int i = 0;
  scanf("%d", &x);
  while (x >= y) {
    scanf("%d %d %d", &a, &b, &c);
    g = abs(b - e);
    h = abs(c - f);
    if (a - d < g) {
      puts("No");
      return 0;
    }
    i = a - d - g;
    if (i < h) {
      puts("No");
      return 0;
    }
    if ((i - h) % 2) {
      puts("No");
      return 0;
    } else {
    }

    y++;
    d = a;
    e = b;
    f = c;
  }
  puts("Yes");
  return 0;
}

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

    let mut v: Vec<isize> = vec![0; 3];
    for _ in 0..n {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let u: Vec<isize> = s.trim().split(' ').map(|x| x.parse().unwrap()).collect();
        let t = u[0] - v[0];
        let d = (u[1] - v[1] + u[2] - v[2]).abs();
        if t < d || (t - d) % 2 == 1 {
            println!("No");
            return;
        }
        v = u;
    }
    println!("Yes");
}


A： A-Z-

問題

<var>26</var> マスの円環状のボードがあり、各マスには大文字のアルファベット <var>1</var> 文字が、アルファベット順に時計回りに書かれています。すなわち、 'A' のマスの時計回り隣は 'B' のマスで、 'B' のマスの隣は 'C' のマスで、・・・、 'Z' のマスの時計回り隣は 'A' のマスです。

また、ボードには 'A' のマスに駒が <var>1</var> つ置かれています。

あなたは、文字列 <var>S</var> を受け取り、 <var>S</var> の先頭から <var>1</var> 文字ずつ見て駒を操作します。 <var>i</var> 回目の操作は以下のようになります。

その時点で駒のあるマスから  <var>S</var> の <var>i</var> 文字目のアルファベットのマスを目指して、駒を時計回りに <var>1</var> マスずつ移動させる。このとき少なくとも <var>1</var> マスは移動するとする。したがって、例えば 'A' のマスから 'A' のマスに移動する際は、ボードを <var>1</var> 周しなくてはならない。

上記の操作の結果、駒が 'A' のマスを何回踏んだかを答えてください。なお「 'A' のマスを踏む」とは、 'Z' のマスから 'A' のマスに駒を進めることを言います。

入力形式

入力は <var>1</var> 行で与えられる。

<var>S</var>

<var>S</var> はあなたが受け取る文字列を表す。

制約

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

 <var>S</var> は英大文字のみで構成される。

出力形式

'A' のマスを何回踏んだかを <var>1</var> 行で出力せよ。

入力例1

AIZU

出力例1

2

A -> A (ここで 1 回)

A -> I (ここまで 1 回)

I -> Z (ここまで 1 回)

Z -> U (ここまで 2 回)

入力例2

HOKKAIDO

出力例2

4

int solution() {
  int i;
  int ans = 0;
  char *S = (char *)malloc(sizeof(char) * 102);
  S[0] = 'A';
  scanf("%s", &S[1]);
  for (i = 1; S[i] != '\0'; i++) {
    if (S[i] <= S[i - 1]) {
      ans++;
    }
  }
  printf("%d\n", ans);
  return 0;
}

fn solution() {
    input!(S:chars);
    let S: Vec<char> = S;
    let mut ans = 0;
    let mut now: char = 'A';
    for i in 0..S.len() {
        if S[i] <= now {
            ans += 1;
        }
        now = S[i];
    }
    println!("{}", ans);
}


You are given an array $$$a$$$ of size $$$n$$$. Each element in this array is an integer between $$$1$$$ and $$$10^9$$$.You can perform several operations to this array. During an operation, you can replace an element in the array with any integer between $$$1$$$ and $$$10^9$$$. Output the minimum number of operations needed such that the resulting array doesn't contain any local maximums, and the resulting array after the operations.An element $$$a_i$$$ is a local maximum if it is strictly larger than both of its neighbors (that is, $$$a_i > a_{i - 1}$$$ and $$$a_i > a_{i + 1}$$$). Since $$$a_1$$$ and $$$a_n$$$ have only one neighbor each, they will never be a local maximum.

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

    for i in 0..input {
        let mut input = String::new();
        io::stdin().read_line(&mut input);
        let non: i32 = input.trim().parse().unwrap();

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

        let mut p: usize = 1;
        let mut count = 0;
        loop {
            if p as i32 > non - 1 - 1 {
                break;
            }

            if vector[p - 1] < vector[p] && vector[p] > vector[p + 1] {
                if p as i32 <= non - 3 - 1 {
                    if vector[p + 1] < vector[p + 2] && vector[p + 2] > vector[p + 3] {
                        vector[p + 1] = max(vector[p], vector[p + 2]);
                        count += 1;
                        p += 1;
                    } else {
                        vector[p + 1] = vector[p];
                        count += 1;
                        p += 1;
                    }
                } else {
                    vector[p + 1] = vector[p];
                    count += 1;
                    p += 1;
                }
            } else {
                p += 1;
            }
        }

        println!("{}", count);
        vector.iter().for_each(|x| print!("{} ", x));
        println!();
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> integers, <var>A_1, A_2, ..., A_N</var>, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between <var>1</var> and <var>10^9</var> (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the <var>N</var> integers on the blackboard after your move.

Constraints

All values in input are integers.

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

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

Output

Input is given from Standard Input in the following format:

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

Output

Print the maximum possible greatest common divisor of the <var>N</var> integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace <var>7</var> with <var>4</var>, the greatest common divisor of the three integers on the blackboard will be <var>2</var>, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.

int solution(void) {
  int n;
  scanf("%d", &n);
  long long int a[n];
  long long int min1 = 10000000000;
  long long int min2 = 10000000000;
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
    if (min2 > a[i]) {
      min2 = a[i];
    } else if (min1 > a[i]) {
      min1 = a[i];
    }
  }
  for (long long int i = min1;; i--) {
    int cnt = 0;
    for (int j = 0; j < n; j++) {
      if (a[j] % i > 0) {
        cnt++;
      }
      if (cnt > 1) {
        break;
      }
    }
    if (cnt < 2) {
      printf("%lld\n", i);
      return 0;
    }
  }
  return 0;
}

fn solution() {
    input! {
        n: usize,
        a: [i64; n],
    }

    let f = |i| a.iter().filter(|&&a| a % i == 0).count();

    let mut ans = 1;
    for &a in a[0..2].iter() {
        for i in 1.. {
            if i * i > a {
                break;
            }
            if a % i == 0 {
                if f(i) >= n - 1 {
                    ans = max(ans, i);
                }
                if f(a / i) >= n - 1 {
                    ans = max(ans, a / i);
                }
            }
        }
    }

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


You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$), $$$a_{x}+a_{y} \neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.

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();
        for _ in 0..n {
            print!("1 ");
        }
        println!();
    }
}


Score: <var>500</var> points

Problem Statement

<var>N</var> people are standing in a queue, numbered <var>1, 2, 3, ..., N</var> from front to back. Each person wears a hat, which is red, blue, or green.

The person numbered <var>i</var> says:

"In front of me, exactly <var>A_i</var> people are wearing hats with the same color as mine."

Assuming that all these statements are correct, find the number of possible combinations of colors of the <var>N</var> people's hats.

Since the count can be enormous, compute it modulo <var>1000000007</var>.

Constraints

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

<var>0 \leq A_i \leq N-1</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the number of possible combinations of colors of the <var>N</var> people's hats, modulo <var>1000000007</var>.

Sample Input 1

6
0 1 2 3 4 5

Sample Output 1

3

We have three possible combinations, as follows:

Red, Red, Red, Red, Red, Red

Blue, Blue, Blue, Blue, Blue, Blue

Green, Green, Green, Green, Green, Green

Sample Input 2

3
0 0 0

Sample Output 2

6

Sample Input 3

54
0 0 1 0 1 2 1 2 3 2 3 3 4 4 5 4 6 5 7 8 5 6 6 7 7 8 8 9 9 10 10 11 9 12 10 13 14 11 11 12 12 13 13 14 14 15 15 15 16 16 16 17 17 17

Sample Output 3

115295190

int solution() {
  int n;
  scanf("%d", &n);
  int i;
  int a[100005];
  for (i = 0; i < n; i++) {
    scanf("%d", &a[i]);
  }
  long long int p = 1000000007;
  long long int dp[100005];
  long long int count[100005];
  for (i = 0; i < n; i++) {
    dp[i] = 0;
  }
  for (i = 0; i < n; i++) {
    count[i] = 0;
  }
  for (i = 0; i < n; i++) {
    if (a[i] == 0) {
      dp[i] = 3 - count[0];
    } else {
      dp[i] = count[a[i] - 1] - count[a[i]];
    }
    count[a[i]]++;
  }
  long long int ans = 1;
  for (i = 0; i < n; i++) {
    ans = ans * dp[i] % p;
  }
  printf("%lld\n", ans);
  return 0;
}

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

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

    let mut ans: u64 = 1;
    let mut cnt = vec![0; n + 1];
    let modulo: u64 = 1000000007;

    cnt[0] = 3;
    for i in 0..n {
        ans = ans * cnt[a[i]] % modulo;
        cnt[a[i] + 1] += 1;
        cnt[a[i]] -= 1;
    }
    println!("{}", ans);
}


Given an array of integer $$$a_1, a_2, \ldots, a_n$$$. In one operation you can make $$$a_i := a_i + 1$$$ if $$$i < n$$$ and $$$a_i \leq a_{i + 1}$$$, or $$$i = n$$$ and $$$a_i \leq a_1$$$.You need to check whether the array $$$a_1, a_2, \ldots, a_n$$$ can become equal to the array $$$b_1, b_2, \ldots, b_n$$$ in some number of operations (possibly, zero). Two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$ are called equal if $$$a_i = b_i$$$ for all integers $$$i$$$ from $$$1$$$ to $$$n$$$.

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

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

    let t: usize = input.token();
    for _ in 0..t {
        let n: usize = input.token();
        let a: Vec<i32> = (0..n).map(|_| input.token()).collect();
        let b: Vec<i32> = (0..n).map(|_| input.token()).collect();

        let mut result = true;
        for i in 0..n {
            let next_i = if i == n - 1 { 0 } else { i + 1 };
            if a[i] > b[i] {
                result = false;
                break;
            }
            if b[i] != a[i] && b[i] - 1 > b[next_i] {
                result = false;
                break;
            }
        }
        writeln!(output, "{}", if result { "YES" } else { "NO" }).unwrap();
    }
}


Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price $$$z$$$ chizhiks per coconut. Sasha has $$$x$$$ chizhiks, Masha has $$$y$$$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has $$$5$$$ chizhiks, Masha has $$$4$$$ chizhiks, and the price for one coconut be $$$3$$$ chizhiks. If the girls don't exchange with chizhiks, they will buy $$$1 + 1 = 2$$$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $$$6$$$ chizhiks, Masha will have $$$3$$$ chizhiks, and the girls will buy $$$2 + 1 = 3$$$ coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).

int solution(void) {
  long long x;
  long long y;
  long long z;
  scanf("%lld %lld %lld", &x, &y, &z);
  if (z > 0) {
    long long a;
    long long b;
    long long c;
    long long d;
    long long e;
    long long f;
    long long m;
    long long mn;
    a = x % z;
    d = x / z;
    b = y % z;
    e = y / z;
    c = (x + y) % z;
    f = (x + y) / z;
    if (a > b) {
      m = z - a;
      if (m > b) {
        mn = 0;
      } else {
        mn = m;
      }
    } else {
      m = z - b;
      if (m > a) {
        mn = 0;
      } else {
        mn = m;
      }
    }
    printf("%lld %lld", f, mn);
  }
  return 0;
}

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

    handle.read_to_string(&mut buffer).expect("stdin");

    let arr: Vec<_> = buffer
        .split_whitespace()
        .map(|x| x.parse::<i64>().unwrap())
        .collect();

    let x = *arr.get(0).unwrap();
    let y = *arr.get(1).unwrap();
    let z = *arr.get(2).unwrap();

    let total = x + y;

    let max_poss = total / z;
    let a = x % z;
    let b = y % z;

    let min_debt = if b + a >= z { z - cmp::max(a, b) } else { 0 };

    println!("{} {}", max_poss, min_debt);
}


Score : <var>100</var> points

Problem Statement

<var>N</var> of us are going on a trip, by train or taxi.

The train will cost each of us <var>A</var> yen (the currency of Japan).

The taxi will cost us a total of <var>B</var> yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

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

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us <var>4 \times 2 = 8</var> yen, and the taxi will cost us <var>9</var> yen, so the minimum total travel expense is <var>8</var> yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8

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

  scanf("%d %d %d", &n, &a, &b);
  if (n * a >= b) {
    printf("%d", b);
  } else {
    printf("%d", n * a);
  }
}

fn solution() {
    let mut line = String::new();
    let _ = std::io::stdin().read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();
    let n: i32 = vec[0].parse().unwrap();
    let a: i32 = vec[1].parse().unwrap();
    let b: i32 = vec[2].parse().unwrap();

    println!("{}", std::cmp::min(n * a, b));
}


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$) —   $$$(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$$$, where $$$\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.

int solution(void) {
  int linenum;

  scanf("%d", &linenum);

  int len[linenum];

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

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

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

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

        println!(
            "{}",
            (1..=n).map(|x| x.to_string()).collect::<Vec<_>>().join(" ")
        );
    }
}


Let's call a binary string $$$T$$$ of length $$$m$$$ indexed from $$$1$$$ to $$$m$$$ paranoid if we can obtain a string of length $$$1$$$ by performing the following two kinds of operations $$$m-1$$$ times in any order : Select any substring of $$$T$$$ that is equal to 01, and then replace it with 1. Select any substring of $$$T$$$ that is equal to 10, and then replace it with 0.For example, if $$$T = $$$ 001, we can select the substring $$$[T_2T_3]$$$ and perform the first operation. So we obtain $$$T = $$$ 01.You are given a binary string $$$S$$$ of length $$$n$$$ indexed from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ $$$1 \le l \le r \le n$$$ such that $$$S[l \ldots r]$$$ (the substring of $$$S$$$ from $$$l$$$ to $$$r$$$) is a paranoid string.

int solution() {
  int t;
  int n;
  char s[200001];

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

    scanf("%s", s);

    long long int count = n;
    for (int k = 1; k < n; k++) {
      if (s[k] == '1' && s[k - 1] == '0') {
        count = count + k;
      }
      if (s[k] == '0' && s[k - 1] == '1') {
        count = count + k;
      }
    }
    printf("%lli\n", count);
  }

  return 0;
}

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

    let mut lines = content.lines();
    let num_tests: i32 = lines.next().unwrap().parse().unwrap();
    for _ in 0..num_tests {
        let _n: i32 = lines.next().unwrap().parse().unwrap();
        let s: Vec<char> = lines.next().unwrap().chars().collect();
        let mut result = s.len() as i64;
        for i in 1..s.len() {
            if s[i - 1] != s[i] {
                result += i as i64;
            }
        }
        println!("{result}");
    }
}


You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:   has at least one red bean (or the number of red beans $$$r_i \ge 1$$$);  has at least one blue bean (or the number of blue beans $$$b_i \ge 1$$$);  the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \le d$$$) Can you distribute all beans?

fn solution() {
    let mut buff = String::new();
    io::stdin().read_line(&mut buff).unwrap();
    let t = buff.trim().parse::<u16>().unwrap();
    for _ in 0..t {
        buff = String::new();
        io::stdin().read_line(&mut buff).unwrap();
        let v = buff
            .split_whitespace()
            .map(|x| x.parse::<i32>().unwrap())
            .collect::<Vec<i32>>();
        let mut r = v[0];
        let mut b = v[1];
        if b > r {
            mem::swap(&mut r, &mut b);
        }
        let mut flag = false;
        if r % b == 0 {
            let a = r / b;
            let dif = a - 1;
            if dif <= v[2] {
                flag = true;
            }
        } else {
            let a = (r / b) + 1;
            let dif = a - 1;
            if dif <= v[2] {
                flag = true;
            }
        }
        if flag {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


You are given two integers $$$x$$$ and $$$y$$$ (it is guaranteed that $$$x > y$$$). You may choose any prime integer $$$p$$$ and subtract it any number of times from $$$x$$$. Is it possible to make $$$x$$$ equal to $$$y$$$?Recall that a prime number is a positive integer that has exactly two positive divisors: $$$1$$$ and this integer itself. The sequence of prime numbers starts with $$$2$$$, $$$3$$$, $$$5$$$, $$$7$$$, $$$11$$$.Your program should solve $$$t$$$ independent test cases.

int solution() {
  long long n;
  long long m;
  scanf("%lld", &n);
  while (scanf("%lld%lld", &n, &m) == 2) {
    printf(n - m == 1 ? "NO\n" : "YES\n");
  }
}

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

    for _ in 0..t {
        s.clear();
        std::io::stdin().read_line(&mut s).unwrap();
        let vec = s
            .split_whitespace()
            .map(|x| x.parse::<i64>().unwrap())
            .collect::<Vec<i64>>();

        if vec[0] - vec[1] == 1 {
            println!("No");
        } else {
            println!("Yes");
        }
    }
}


For some binary string $$$s$$$ (i.e. each character $$$s_i$$$ is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length $$$2$$$ were written. For each pair (substring of length $$$2$$$), the number of '1' (ones) in it was calculated.You are given three numbers:  $$$n_0$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$0$$$;  $$$n_1$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$1$$$;  $$$n_2$$$ — the number of such pairs of consecutive characters (substrings) where the number of ones equals $$$2$$$. For example, for the string $$$s=$$$"1110011110", the following substrings would be written: "11", "11", "10", "00", "01", "11", "11", "11", "10". Thus, $$$n_0=1$$$, $$$n_1=3$$$, $$$n_2=5$$$.Your task is to restore any suitable binary string $$$s$$$ from the given values $$$n_0, n_1, n_2$$$. It is guaranteed that at least one of the numbers $$$n_0, n_1, n_2$$$ is greater than $$$0$$$. Also, it is guaranteed that a solution exists.

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

    io::stdin().read_line(&mut input)?;
    let n = input.trim().parse().unwrap();
    for _ in 0..n {
        input.clear();
        io::stdin().read_line(&mut input)?;

        let numbers: Vec<u8> = input
            .trim()
            .split(" ")
            .map(|x| x.parse().unwrap())
            .take(3)
            .collect();
        let (n0, mut n1, n2) = (numbers[0], numbers[1], numbers[2]);

        let mut result = String::new();
        if n1 > 0 && n1 % 2 == 0 {
            result.push('0');
            n1 -= 1;
        }
        if n2 > 0 || n1 > 0 {
            result.push('1');
        }
        for _ in 0..n2 {
            result.push('1');
        }
        for i in 0..n1 {
            if i % 2 == 0 {
                result.push('0');
            } else {
                result.push('1');
            }
        }
        if n0 > 0 && (result.is_empty() || result.ends_with('1')) {
            result.push('0');
        }
        for _ in 0..n0 {
            result.push('0');
        }
        println!("{}", result);
    }

    Ok(())
}


You have an $$$n \times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \leq x \leq n$$$ and $$$1 \leq y \leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side.  Such arrangement of $$$3$$$ rooks on the $$$4 \times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard or report that there is no such arrangement.

int solution() {
  int N;
  scanf("%d", &N);
  int chess[N][2];
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < 2; j++) {
      scanf("%d", &chess[i][j]);
    }
  }

  for (int k = 0; k < N; k++) {
    int count = 0;
    if (chess[k][1] <= ceil(chess[k][0] / 2.0)) {

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

        for (int j = 0; j < chess[k][0]; j++) {

          if (i == j && i % 2 == 0 && j % 2 == 0 &&
              (count <= (chess[k][1] - 1))) {

            printf("R");
            count++;

          }

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

    }

    else {
      printf("-1\n");
    }
  }
  return 0;
}

fn solution() {
    let mut handle = std::io::BufWriter::new(std::io::stdout());
    let mut test_no = String::new();
    std::io::stdin().read_line(&mut test_no).unwrap();
    let test_no: u8 = test_no.trim().parse().unwrap();
    for _ in 0..test_no {
        let mut string = String::new();
        std::io::stdin().read_line(&mut string).unwrap();
        let stray: Vec<&str> = string.trim().split(' ').collect();
        let array: Vec<u8> = stray.iter().map(|x| x.parse().unwrap()).collect();
        if array[1] > array[0].div_ceil(2) {
            writeln!(handle, "-1").expect("");
        } else {
            let dotstr = ".".repeat(array[0].into());
            let dotarr: Vec<char> = dotstr.chars().collect();
            let mut full_dotarr = vec![dotarr; array[0].into()];
            for i in 0..array[1] {
                full_dotarr[(2 * i) as usize][(2 * i) as usize] = 'R';
            }
            for i in full_dotarr.iter() {
                writeln!(handle, "{}", i.iter().collect::<String>()).ok();
            }
        }
    }
}


Bajtek, known for his unusual gifts, recently got an integer array $$$x_0, x_1, \ldots, x_{k-1}$$$.Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array $$$a$$$ of length $$$n + 1$$$. As a formal description of $$$a$$$ says, $$$a_0 = 0$$$ and for all other $$$i$$$ ($$$1 \le i \le n$$$) $$$a_i = x_{(i-1)\bmod k} + a_{i-1}$$$, where $$$p \bmod q$$$ denotes the remainder of division $$$p$$$ by $$$q$$$.For example, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then:  $$$a_0 = 0$$$,  $$$a_1 = x_{0\bmod 3}+a_0=x_0+0=1$$$,  $$$a_2 = x_{1\bmod 3}+a_1=x_1+1=3$$$,  $$$a_3 = x_{2\bmod 3}+a_2=x_2+3=6$$$,  $$$a_4 = x_{3\bmod 3}+a_3=x_0+6=7$$$,  $$$a_5 = x_{4\bmod 3}+a_4=x_1+7=9$$$. So, if the $$$x = [1, 2, 3]$$$ and $$$n = 5$$$, then $$$a = [0, 1, 3, 6, 7, 9]$$$.Now the boy hopes that he will be able to restore $$$x$$$ from $$$a$$$! Knowing that $$$1 \le k \le n$$$, help him and find all possible values of $$$k$$$ — possible lengths of the lost array.

int solution() {
  int n;
  int a = 0;
  int ai;
  int c = 0;
  scanf("%d", &n);
  int A[n];
  int R[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &ai);
    A[i] = ai - a;
    a = ai;
  }

  for (int k = 1; k <= n; k++) {
    char p = 1;
    for (int i = k; i < n; i++) {
      if (A[i % k] != A[i]) {
        p = 0;
        break;
      }
    }
    if (p) {
      R[c] = k;
      c++;
    }
  }
  printf("%d\n", c);
  for (int i = 0; i < c; i++) {
    printf("%d ", R[i]);
  }

  return 0;
}

fn solution() {
    let sin = io::stdin();
    let mut f = sin.lock();
    let mut buf = String::new();
    f.read_line(&mut buf).unwrap();
    let n: usize = buf.trim().parse().unwrap();
    buf = "".to_string();
    f.read_line(&mut buf).unwrap();
    let mut a = Vec::<i32>::new();
    a.push(0i32);
    for p in buf.split_whitespace().map(|s| s.parse().unwrap()) {
        a.push(p);
    }

    let mut b = vec![0i32; n];
    for i in 0..n {
        b[i] = a[i + 1] - a[i];
    }
    let mut ans = Vec::<usize>::new();
    for k in 1..n {
        let mut z: bool = true;
        for i in k..n {
            if b[i] != b[i - k] {
                z = false;
                break;
            }
        }
        if z {
            ans.push(k);
        }
    }
    ans.push(n);
    let mut sp = String::new();
    for p in ans.iter() {
        sp = sp + &p.to_string() + " ";
    }
    println!("{}", ans.len());
    println!("{}", sp)
}


Score : <var>100</var> points

Problem Statement

A programming competition site AtCode regularly holds programming contests.

The next contest on AtCode is called ABC, which is rated for contestants with ratings less than <var>1200</var>.

The contest after the ABC is called ARC, which is rated for contestants with ratings less than <var>2800</var>.

The contest after the ARC is called AGC, which is rated for all contestants.

Takahashi's rating on AtCode is <var>R</var>. What is the next contest rated for him?

Constraints

<var>0 ≤ R ≤ 4208</var>

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

Input

Input is given from Standard Input in the following format:

<var>R</var>

Output

Print the name of the next contest rated for Takahashi (ABC, ARC or AGC).

Sample Input 1

1199

Sample Output 1

ABC

<var>1199</var> is less than <var>1200</var>, so ABC will be rated.

Sample Input 2

1200

Sample Output 2

ARC

<var>1200</var> is not less than <var>1200</var> and ABC will be unrated, but it is less than <var>2800</var> and ARC will be rated.

Sample Input 3

4208

Sample Output 3

AGC

int solution() {
  int R = 0;

  scanf("%d", &R);

  if (R < 1200) {
    printf("ABC");
  } else if (1200 <= R && R < 2800) {
    printf("ARC");
  } else if (2800 <= R) {
    printf("AGC");
  }

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut s = String::new();
    stdin.read_line(&mut s).ok();
    s.pop();
    let r = u32::from_str(&s).expect("e");
    if r < 1200 {
        println!("ABC");
    } else if r < 2800 {
        println!("ARC");
    } else {
        println!("AGC");
    }
}


Score : <var>100</var> points

Problem Statement

Cat Snuke is learning to write characters.
Today, he practiced writing digits 1 and 9, but he did it the other way around.

You are given a three-digit integer <var>n</var> written by Snuke.
Print the integer obtained by replacing each digit 1 with 9 and each digit 9 with 1 in <var>n</var>.

Constraints

<var>111 \leq n \leq 999</var>

<var>n</var> is an integer consisting of digits 1 and 9.

Input

Input is given from Standard Input in the following format:

<var>n</var>

Output

Print the integer obtained by replacing each occurrence of 1 with 9 and each occurrence of 9 with 1 in <var>n</var>.

Sample Input 1

119

Sample Output 1

991

Replace the 9 in the ones place with 1, the 1 in the tens place with 9 and the 1 in the hundreds place with 9. The answer is 991.

Sample Input 2

999

Sample Output 2

111

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

    let mut v: Vec<char> = s.chars().collect();

    for i in &mut v {
        if *i == '1' {
            *i = '9';
        } else if *i == '9' {
            *i = '1';
        }
    }

    println! {"{}{}{}", v[0], v[1], v[2]};
}


Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit.   For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.

int solution() {
  int n;
  int a;
  int b;
  int c;
  int d;
  int sum = 0;
  scanf("%d\n", &n);
  while (n--) {
    sum = 0;
    scanf("%d %d %d %d\n", &a, &b, &c, &d);
    if (a > c) {
      sum += a - c;
    } else {
      sum += c - a;
    }
    if (b > d) {
      sum += b - d;
    } else {
      sum += d - b;
    }
    if (a != c && b != d) {
      sum += 2;
    }
    printf("%d\n", sum);
  }
  return 0;
}

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let test: i64 = str.trim().parse().unwrap();
    for _ in 0..test {
        str.clear();
        let _ = stdin().read_line(&mut str).unwrap();
        let mut iter = str.split_whitespace();
        let x1: i64 = iter.next().unwrap().parse().unwrap();
        let y1: i64 = iter.next().unwrap().parse().unwrap();
        let x2: i64 = iter.next().unwrap().parse().unwrap();
        let y2: i64 = iter.next().unwrap().parse().unwrap();
        let mut d = (x1 - x2).abs() + (y1 - y2).abs();
        if (x1 - x2) * (y1 - y2) != 0 {
            d += 2;
        }
        println!("{}", d);
    }
}


Score : <var>500</var> points

Problem Statement

Takahashi has decided to work on <var>K</var> days of his choice from the <var>N</var> days starting with tomorrow.

You are given an integer <var>C</var> and a string <var>S</var>. Takahashi will choose his workdays as follows:

After working for a day, he will refrain from working on the subsequent <var>C</var> days.

If the <var>i</var>-th character of <var>S</var> is x, he will not work on Day <var>i</var>, where Day <var>1</var> is tomorrow, Day <var>2</var> is the day after tomorrow, and so on.

Find all days on which Takahashi is bound to work.

Constraints

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

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

<var>0 \leq C \leq N</var>

The length of <var>S</var> is <var>N</var>.

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

Takahashi can choose his workdays so that the conditions in Problem Statement are satisfied.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>K</var> <var>C</var>
<var>S</var>

Output

Print all days on which Takahashi is bound to work in ascending order, one per line.

Sample Input 1

11 3 2
ooxxxoxxxoo

Sample Output 1

6

Takahashi is going to work on <var>3</var> days out of the <var>11</var> days. After working for a day, he will refrain from working on the subsequent <var>2</var> days.

There are four possible choices for his workdays: Day <var>1,6,10</var>, Day <var>1,6,11</var>, Day <var>2,6,10</var>, and Day <var>2,6,11</var>.

Thus, he is bound to work on Day <var>6</var>.

Sample Input 2

5 2 3
ooxoo

Sample Output 2

1
5

There is only one possible choice for his workdays: Day <var>1,5</var>.

Sample Input 3

5 1 0
ooooo

Sample Output 3

There may be no days on which he is bound to work.

Sample Input 4

16 4 3
ooxxoxoxxxoxoxxo

Sample Output 4

11
16

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

    let (n, k, c): (usize, usize, usize) = {
        let mut buf = String::new();
        reader.read_line(&mut buf).unwrap();
        let mut iter = buf.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };

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

    let mut left = vec![0; k];
    let (mut li, mut lj) = (0, 0);
    while li < n && lj < k {
        if s[li] == 'o' {
            left[lj] = li;
            li += c;
            lj += 1;
        }
        li += 1;
    }

    let mut right = vec![0; k];
    let (mut ri, mut rj) = (0, 0);
    while ri < n && rj < k {
        if s[n - 1 - ri] == 'o' {
            right[k - 1 - rj] = n - 1 - ri;
            ri += c;
            rj += 1;
        }
        ri += 1;
    }

    for i in 0..k {
        if left[i] == right[i] {
            writeln!(writer, "{}", left[i] + 1).unwrap();
        }
    }
}


Score : <var>100</var> points

Problem Statement

Print the <var>K</var>-th element of the following sequence of length <var>32</var>:

1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>K</var>

Output

Print the <var>K</var>-th element.

Sample Input 1

6

Sample Output 1

2

The <var>6</var>-th element is <var>2</var>.

Sample Input 2

27

Sample Output 2

5

The <var>27</var>-th element is <var>5</var>.

fn solution() {
    let array = [
        1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4,
        1, 51,
    ];
    let mut input = String::new();

    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    let index: usize = input.trim().parse().expect("uooo");

    println!("{}", array[index - 1]);
}


Red Dragonfly

  It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed.

  When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate the distance between their heads.

Input

  The input is given in the following format.

$x_1$ $x_2$

  The input line provides dragonflies’ head positions $x_1$ and $x_2$ ($0 \leq x_1, x_2 \leq 100$) as integers.

Output

  Output the distance between the two red dragonflies in a line.

Sample Input 1

20 30

Sample Output 1

10

Sample Input 2

50 25

Sample Output 2

25

Sample Input 3

25 25

Sample output 3

0

fn solution() {
    let stdin = stdin();
    let line = stdin.lock().lines().next().unwrap().unwrap();
    let mut iter = line.split_whitespace().map(|s| s.parse::<i32>().unwrap());

    let (a, b) = (iter.next().unwrap(), iter.next().unwrap());

    println!("{}", (a - b).abs());
}


Score : <var>400</var> points

Problem Statement

Takahashi is going to buy <var>N</var> items one by one.

The price of the <var>i</var>-th item he buys is <var>A_i</var> yen (the currency of Japan).

He has <var>M</var> discount tickets, and he can use any number of them when buying an item.

If <var>Y</var> tickets are used when buying an item priced <var>X</var> yen, he can get the item for <var>\frac{X}{2^Y}</var> (rounded down to the nearest integer) yen.

What is the minimum amount of money required to buy all the items?

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum amount of money required to buy all the items.

Sample Input 1

3 3
2 13 8

Sample Output 1

9

We can buy all the items for <var>9</var> yen, as follows:

Buy the <var>1</var>-st item for <var>2</var> yen without tickets.

Buy the <var>2</var>-nd item for <var>3</var> yen with <var>2</var> tickets.

Buy the <var>3</var>-rd item for <var>4</var> yen with <var>1</var> ticket.

Sample Input 2

4 4
1 9 3 5

Sample Output 2

6

Sample Input 3

1 100000
1000000000

Sample Output 3

0

We can buy the item priced <var>1000000000</var> yen for <var>0</var> yen with <var>100000</var> tickets.

Sample Input 4

10 1
1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000

Sample Output 4

9500000000

int solution(void) {
  int n;
  int m;
  int a[200000] = {0};
  scanf("%d %d", &n, &m);
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    int ind = i;
    while (ind > 0 && a[ind] > a[(ind - 1) / 2]) {
      int temp = a[ind];
      a[ind] = a[(ind - 1) / 2];
      a[(ind - 1) / 2] = temp;
      ind = (ind - 1) / 2;
    }
  }

  for (int j = 0; j < m; j++) {
    a[0] = a[0] / 2;
    int ind = 0;
    while (a[ind] < a[(2 * ind) + 1] || a[ind] < a[(2 * ind) + 2]) {
      int ind2;
      if (a[(2 * ind) + 1] >= a[(2 * ind) + 2]) {
        ind2 = 2 * ind + 1;
      } else {
        ind2 = 2 * ind + 2;
      }
      int temp = a[ind];
      a[ind] = a[ind2];
      a[ind2] = temp;
      ind = ind2;
    }
  }

  long sum = 0;
  for (int k = 0; k < n; k++) {
    sum += a[k];
  }

  printf("%ld", sum);
  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let m = it.next().unwrap().parse::<usize>().unwrap();
    let a = (0..n)
        .map(|_| it.next().unwrap().parse::<i64>().unwrap())
        .collect::<Vec<_>>();
    let mut qu = BinaryHeap::from(a);
    for _i in 0..m {
        let v = qu.pop().unwrap();
        qu.push(v / 2);
    }
    println!("{}", qu.iter().sum::<i64>());
}


Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.Anton's room can be represented as a grid with $$$n$$$ rows and $$$m$$$ columns. Let $$$(i, j)$$$ denote the cell in row $$$i$$$ and column $$$j$$$. Anton is currently standing at position $$$(i, j)$$$ in his room. To annoy Anton, Riley decided to throw exactly two yo-yos in cells of the room (they can be in the same cell).Because Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to $$$(i, j)$$$ by travelling only to adjacent by side cells. That is, if he is in cell $$$(x, y)$$$ then he can travel to the cells $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ and $$$(x, y - 1)$$$ in one step (if a cell with those coordinates exists).Riley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is maximized. But because he is very busy, he asked you to tell him.

int solution() {
  short int t;
  scanf("%hd", &t);
  int arr[t][4];
  for (short int i = 0; i < t; i++) {
    for (short int j = 0; j < 4; j++) {
      scanf("%d", &arr[i][j]);
    }
  }
  for (int i = 0; i < t; i++) {
    printf("%d %d %d %d\n", arr[i][0], 1, 1, arr[i][1]);
  }

  return 0;
}

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

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

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

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

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

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

        let n = it.next().unwrap();
        let m = it.next().unwrap();
        let _i = it.next().unwrap();
        let _j = it.next().unwrap();

        writeln!(&mut output, "{} {} {} {}", 1, 1, n, m).unwrap();
    }
}


Berland crossword is a puzzle that is solved on a square grid with $$$n$$$ rows and $$$n$$$ columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that:   exactly $$$U$$$ cells in the top row are black;  exactly $$$R$$$ cells in the rightmost column are black;  exactly $$$D$$$ cells in the bottom row are black;  exactly $$$L$$$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.

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

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

    let _t = it.next();

    'outer: while let Some(n) = it.next() {
        let u = it.next().unwrap();
        let r = it.next().unwrap();
        let b = it.next().unwrap();
        let l = it.next().unwrap();

        let a = [u, r, b, l];

        for i in 0..(1 << 4) {
            let works = (0..4).all(|j| {
                let s = i & (1 << j);
                let e = i & (1 << ((j + 1) % 4));

                let up = n - if s == 0 { 1 } else { 0 } - if e == 0 { 1 } else { 0 };

                let low = if s != 0 { 1 } else { 0 } + if e != 0 { 1 } else { 0 };

                (low..=up).contains(&a[j])
            });

            if works {
                println!("YES");
                continue 'outer;
            }
        }

        println!("NO");
    }
}


Let's call a string adorable if its letters can be realigned in such a way that they form two consequent groups of equal symbols (note that different groups must contain different symbols). For example, ababa is adorable (you can transform it to aaabb, where the first three letters form a group of a-s and others — a group of b-s), but cccc is not since in each possible consequent partition letters in these two groups coincide.You're given a string s. Check whether it can be split into two non-empty subsequences such that the strings formed by these subsequences are adorable. Here a subsequence is an arbitrary set of indexes of the string.

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

    let mut a = [0; 26];
    let mut uc = 0;
    let mut tc = 0;
    let s = input.trim();
    for i in s.bytes().map(|b| (b - b'a') as usize) {
        if a[i] == 0 {
            uc += 1;
        } else if a[i] == 1 {
            tc += 1;
        }
        a[i] += 1;
    }

    let ans = match uc {
        4 => true,
        3 if s.len() >= 4 => true,
        2 if s.len() >= 4 && tc >= 2 => true,
        _ => false,
    };
    if ans {
        println!("Yes");
    } else {
        println!("No");
    }
}


Score : <var>500</var> points

Problem Statement

This is an interactive task.

Let <var>N</var> be an odd number at least <var>3</var>.

There are <var>N</var> seats arranged in a circle.
The seats are numbered <var>0</var> through <var>N-1</var>.
For each <var>i</var> (<var>0 ≤ i ≤ N - 2</var>), Seat <var>i</var> and Seat <var>i + 1</var> are adjacent.
Also, Seat <var>N - 1</var> and Seat <var>0</var> are adjacent.

Each seat is either vacant, or oppupied by a man or a woman.
However, no two adjacent seats are occupied by two people of the same sex.
It can be shown that there is at least one empty seat where <var>N</var> is an odd number at least <var>3</var>.

You are given <var>N</var>, but the states of the seats are not given.
Your objective is to correctly guess the ID number of any one of the empty seats.
To do so, you can repeatedly send the following query:

Choose an integer <var>i</var> (<var>0 ≤ i ≤ N - 1</var>). If Seat <var>i</var> is empty, the problem is solved. Otherwise, you are notified of the sex of the person in Seat <var>i</var>.

Guess the ID number of an empty seat by sending at most <var>20</var> queries.

Constraints

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

<var>3 ≤ N ≤ 99</var> <var>999</var>

Input and Output

First, <var>N</var> is given from Standard Input in the following format:

<var>N</var>

Then, you should send queries.
A query should be printed to Standart Output in the following format.
Print a newline at the end.

<var>i</var>

The response to the query is given from Standard Input in the following format:

<var>s</var>

Here, <var>s</var> is Vacant, Male or Female.
Each of these means that Seat <var>i</var> is empty, occupied by a man and occupied by a woman, respectively.

Notice

Flush Standard Output each time you print something. Failure to do so may result in TLE.

Immediately terminate the program when <var>s</var> is Vacant. Otherwise, the verdict is indeterminate.

The verdict is indeterminate if more than <var>20</var> queries or ill-formatted queries are sent.

Sample Input / Output 1

In this sample, <var>N = 3</var>, and Seat <var>0</var>, <var>1</var>, <var>2</var> are occupied by a man, occupied by a woman and vacant, respectively.

Input	Output

3

	0

Male

	1

Female

	2

Vacant

int solution() {
  long n;
  scanf("%ld", &n);
  char s[100001][7];
  printf("0\n");
  fflush(stdout);
  scanf("%s", s[0]);
  if (s[0][0] == 'V') {
    return 0;
  }
  int i;
  long min = 0;
  long max = n;
  for (i = 1; i < 19; i++) {
    printf("%ld\n", (max + min) / 2);
    fflush(stdout);
    scanf("%s", s[(max + min) / 2]);
    if (s[(max + min) / 2][0] == 'V') {
      break;
    }
    if (((long)((max + min) / 2) - min) % 2 == 0) {
      if (s[min][0] == s[(max + min) / 2][0]) {
        min = (max + min) / 2;
      } else {
        max = (max + min) / 2;
      }
      continue;
    }
    if (s[min][0] == s[(max + min) / 2][0]) {
      max = (max + min) / 2;
    } else {
      min = (max + min) / 2;
    }
  }
  return 0;
}

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

    println!("0");
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();

    let mut start = buf.trim().to_string();
    if start == "Vacant" {
        return;
    }

    let mut begin = 0;
    let mut end = n;
    for _ in 0..19 {
        let mid = (begin + end) / 2;
        println!("{}", mid);

        let mut buf = String::new();
        std::io::stdin().read_line(&mut buf).unwrap();
        let current = buf.trim().to_string();
        if current == "Vacant" {
            return;
        }

        if begin + 1 == mid {
            begin = mid;
        } else if (mid - begin).is_multiple_of(2) && current == start
            || (mid - begin) % 2 == 1 && current != start
        {
            begin = mid;
            start = current;
        } else {
            end = mid;
        }
    }
}


Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically, he wants to get from $$$(0,0)$$$ to $$$(x,0)$$$ by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its $$$n$$$ favorite numbers: $$$a_1, a_2, \ldots, a_n$$$. What is the minimum number of hops Rabbit needs to get from $$$(0,0)$$$ to $$$(x,0)$$$? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points $$$(x_i, y_i)$$$ and $$$(x_j, y_j)$$$ is $$$\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}$$$.For example, if Rabbit has favorite numbers $$$1$$$ and $$$3$$$ he could hop from $$$(0,0)$$$ to $$$(4,0)$$$ in two hops as shown below. Note that there also exists other valid ways to hop to $$$(4,0)$$$ in $$$2$$$ hops (e.g. $$$(0,0)$$$ $$$\rightarrow$$$ $$$(2,-\sqrt{5})$$$ $$$\rightarrow$$$ $$$(4,0)$$$).    Here is a graphic for the first example. Both hops have distance $$$3$$$, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number $$$a_i$$$ and hops with distance equal to $$$a_i$$$ in any direction he wants. The same number can be used multiple times.

int solution() {
  int t;
  int n;
  int x;
  scanf("%d", &t);
  while (t-- > 0) {
    scanf("%d%d", &n, &x);
    int arr[n];
    int count = INT_MAX;
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
    }
    for (int i = n - 1; i >= 0 && x > 0; i--) {
      int temp = x >= arr[i] ? (x + arr[i] - 1) / arr[i] : 2;
      if (count > temp) {
        count = temp;
      }
    }
    printf("%d\n", count);
  }
  return 0;
}

fn solution() {
    let t = {
        let mut buf = String::new();
        stdin().read_line(&mut buf).expect("Failed to read line");
        buf.trim().parse::<i32>().unwrap()
    };
    for _ in 0..t {
        let (_, x) = {
            let mut buf = String::new();
            stdin().read_line(&mut buf).expect("Failed to read");
            let nums: Vec<i32> = buf
                .trim()
                .split_ascii_whitespace()
                .map(|c| c.parse().unwrap())
                .collect();
            (nums[0], nums[1])
        };
        let nums: Vec<i32> = {
            let mut buf = String::new();
            stdin().read_line(&mut buf).expect("Failed to read");
            buf.trim()
                .split_ascii_whitespace()
                .map(|c| c.parse().unwrap())
                .collect()
        };
        let ans;
        if nums.contains(&x) {
            ans = 1;
        } else {
            let max_ = nums.iter().max().unwrap();
            ans = max(2, (x + max_ - 1) / max_);
        }
        println!("{}", ans);
    }
}


There are $$$n$$$ boxes with different quantities of candies in each of them. The $$$i$$$-th box has $$$a_i$$$ candies inside.You also have $$$n$$$ friends that you want to give the candies to, so you decided to give each friend a box of candies. But, you don't want any friends to get upset so you decided to eat some (possibly none) candies from each box so that all boxes have the same quantity of candies in them. Note that you may eat a different number of candies from different boxes and you cannot add candies to any of the boxes.What's the minimum total number of candies you have to eat to satisfy the requirements?

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().flat_map(str::parse);
    let t: usize = input.next().unwrap();
    for _ in 0..t {
        let n = input.next().unwrap();
        let a: Vec<_> = input.by_ref().take(n).collect();
        let min = *a.iter().min().unwrap();
        let sum = a.iter().fold(0, |acc, &x| x - min + acc);
        writeln!(output, "{sum}").ok();
    }
    print!("{output}");
}


Score: <var>500</var> points

Problem Statement

You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.

There are <var>N</var> attendees in the party, and they are given attendee numbers from <var>1</var> through <var>N</var>. The height of Attendee <var>i</var> is <var>A_i</var>.

According to an examination beforehand, you know that a pair of attendees satisfying the condition below will make the transaction.

The absolute difference of their attendee numbers is equal to the sum of their heights.

There are <var>\frac{N(N-1)}{2}</var> ways to choose two from the <var>N</var> attendees and make a pair. Among them, how many satisfy the condition above?

P.S.: We cannot let you know the secret.

Constraints

All values in input are integers.

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

<var>1 \leq A_i \leq 10^9\ (1 \leq i \leq 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>\dots</var> <var>A_N</var>

Output

Print the number of pairs satisfying the condition.

Sample Input 1

6
2 3 3 1 3 1

Sample Output 1

3

<var>A_1 + A_4 = 3</var>, so the pair of Attendee <var>1</var> and <var>4</var> satisfy the condition.

<var>A_2 + A_6 = 4</var>, so the pair of Attendee <var>2</var> and <var>6</var> satisfy the condition.

<var>A_4 + A_6 = 2</var>, so the pair of Attendee <var>4</var> and <var>6</var> satisfy the condition.

No other pair satisfies the condition, so you should print <var>3</var>.

Sample Input 2

6
5 2 4 2 8 8

Sample Output 2

0

No pair satisfies the condition, so you should print <var>0</var>.

Sample Input 3

32
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5

Sample Output 3

22

int solution() {
  int n;
  scanf("%d", &n);
  static int a[200003];
  static int conne[200003][2];

  for (int i = 1; i <= n; i++) {
    conne[i][0] = conne[i][1] = 0;
  }

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

  long long int count = 0;
  for (int i = 2; i < n; i++) {
    count = count + (long long int)(conne[i][0]) * (long long int)(conne[i][1]);
  }
  printf("%lld\n", count);
  return 0;
}

fn solution() {
    let mut line = String::new();
    let stdin = std::io::stdin();
    let _ = stdin.read_line(&mut line);
    line.clear();
    let _ = stdin.read_line(&mut line);
    let a: Vec<_> = line
        .split_whitespace()
        .map(|x| x.parse::<i64>().unwrap())
        .collect();
    let (mut map1, mut map2) = (HashMap::new(), HashMap::new());
    for (i, &x) in a.iter().enumerate() {
        let i = i as i64;
        map1.insert(x + i, *map1.get(&(x + i)).unwrap_or(&0) + 1);
        map2.insert(i - x, *map2.get(&(i - x)).unwrap_or(&0) + 1);
    }
    let mut cnt = 0;
    for (k, v) in map1.iter() {
        if let Some(n) = map2.get(k) {
            cnt += (*n as i64) * (*v as i64);
        }
    }
    println!("{}", cnt);
}


You are given an array $$$a$$$ of size $$$n$$$.You can perform the following operation on the array:   Choose two different integers $$$i, j$$$ $$$(1 \leq i < j \leq n$$$), replace $$$a_i$$$ with $$$x$$$ and $$$a_j$$$ with $$$y$$$. In order not to break the array, $$$a_i | a_j = x | y$$$ must be held, where $$$|$$$ denotes the bitwise OR operation. Notice that $$$x$$$ and $$$y$$$ are non-negative integers. Please output the minimum sum of the array you can get after using the operation above any number of times.

int solution(void) {
  int t = 0;
  scanf("%d", &t);
  while (t--) {
    int n = 0;
    scanf("%d", &n);
    int a[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &a[i]);
    }
    int or = a[0];
    for (int i = 1; i < n; i++) {
      or = or | a[i];
    }
    printf("%d\n", or);
  }
  return 0;
}

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

    for _i in 0..T {
        let mut input = String::new();
        io::stdin().read_line(&mut input);
        let n: usize = input.trim().parse().unwrap();

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

        let mut count: i32 = 0;
        for i in 0..n {
            count |= vector[i];
        }
        println!("{}", count);
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> sightseeing spots on the <var>x</var>-axis, numbered <var>1, 2, ..., N</var>.
Spot <var>i</var> is at the point with coordinate <var>A_i</var>.
It costs <var>|a - b|</var> yen (the currency of Japan) to travel from a point with coordinate <var>a</var> to another point with coordinate <var>b</var> along the axis.

You planned a trip along the axis.
In this plan, you first depart from the point with coordinate <var>0</var>, then visit the <var>N</var> spots in the order they are numbered, and finally return to the point with coordinate <var>0</var>.

However, something came up just before the trip, and you no longer have enough time to visit all the <var>N</var> spots, so you decided to choose some <var>i</var> and cancel the visit to Spot <var>i</var>.
You will visit the remaining spots as planned in the order they are numbered.
You will also depart from and return to the point with coordinate <var>0</var> at the beginning and the end, as planned.

For each <var>i = 1, 2, ..., N</var>, find the total cost of travel during the trip when the visit to Spot <var>i</var> is canceled.

Constraints

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

<var>-5000 \leq A_i \leq 5000</var> (<var>1 \leq i \leq N</var>)

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print <var>N</var> lines.
In the <var>i</var>-th line, print the total cost of travel during the trip when the visit to Spot <var>i</var> is canceled.

Sample Input 1

3
3 5 -1

Sample Output 1

12
8
10

Spot <var>1</var>, <var>2</var> and <var>3</var> are at the points with coordinates <var>3</var>, <var>5</var> and <var>-1</var>, respectively.
For each <var>i</var>, the course of the trip and the total cost of travel when the visit to Spot <var>i</var> is canceled, are as follows:

For <var>i = 1</var>, the course of the trip is <var>0 \rightarrow 5 \rightarrow -1 \rightarrow 0</var> and the total cost of travel is <var>5 + 6 + 1 = 12</var> yen.

For <var>i = 2</var>, the course of the trip is <var>0 \rightarrow 3 \rightarrow -1 \rightarrow 0</var> and the total cost of travel is <var>3 + 4 + 1 = 8</var> yen.

For <var>i = 3</var>, the course of the trip is <var>0 \rightarrow 3 \rightarrow 5 \rightarrow 0</var> and the total cost of travel is <var>3 + 2 + 5 = 10</var> yen.

Sample Input 2

5
1 1 1 2 0

Sample Output 2

4
4
4
2
4

Sample Input 3

6
-679 -2409 -3258 3095 -3291 -4462

Sample Output 3

21630
21630
19932
8924
21630
19288

int solution() {
  int points = 0;
  int diff = 0;
  int diff2 = 0;
  int total = 0;
  int cnt = 0;
  int p[100002] = {0};

  scanf("%d", &points);

  while (cnt < points) {
    scanf("%d", &p[cnt + 1]);

    diff = p[cnt + 1] - p[cnt];
    if (diff < 0) {
      diff = diff * -1;
    }
    total = total + diff;

    cnt++;
  }

  if (p[cnt] < 0) {
    total = total - p[cnt];
  } else {
    total = total + p[cnt];
  }

  for (cnt = 0; cnt < points; cnt++) {
    diff = p[cnt] - p[cnt + 1];
    diff2 = p[cnt + 1] - p[cnt + 2];

    if (diff * diff2 > 0) {
      printf("%d\n", total);
    } else {
      if (diff > diff2) {
        diff = diff - diff2;
      } else {
        diff = diff2 - diff;
      }

      diff2 = p[cnt + 2] - p[cnt];

      if (diff2 < 0) {
        diff2 = diff2 * -1;
      }

      printf("%d\n", total - diff + diff2);
    }
  }

  return 0;
}

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

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let mut an = vec![0];
    let iter = buf.split_whitespace();
    for it in iter {
        an.push(it.parse::<i32>().unwrap());
    }
    let mut sum = 0;
    for i in 0..n {
        sum += (an[i + 1] - an[i]).abs();
    }
    sum += an[n].abs();
    for i in 0..n - 1 {
        println!(
            "{}",
            sum - (an[i + 1] - an[i]).abs() - (an[i + 2] - an[i + 1]).abs()
                + (an[i + 2] - an[i]).abs()
        );
    }
    println!(
        "{}",
        sum - (an[n] - an[n - 1]).abs() - an[n].abs() + an[n - 1].abs()
    );
}


Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that.  Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then:  at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$);  at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$);  the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).

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();
    for _ in 0..t {
        let n: usize = itr.next().unwrap().parse().unwrap();
        let mut a: Vec<usize> = (0..n)
            .map(|_| itr.next().unwrap().parse().unwrap())
            .collect();
        a.sort();
        let mut ans = 1;
        for i in 0..n {
            if a[i] <= 1 + i {
                ans = i + 2;
            }
        }
        println!("{}", ans);
    }
}


Score : <var>700</var> points

Problem Statement

Takahashi is playing with <var>N</var> cards.

The <var>i</var>-th card has an integer <var>X_i</var> on it.

Takahashi is trying to create as many pairs of cards as possible satisfying one of the following conditions:

The integers on the two cards are the same.

The sum of the integers on the two cards is a multiple of <var>M</var>.

Find the maximum number of pairs that can be created.

Note that a card cannot be used in more than one pair.

Constraints

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

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

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

Input

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

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

Output

Print the maximum number of pairs that can be created.

Sample Input 1

7 5
3 1 4 1 5 9 2

Sample Output 1

3

Three pairs <var>(3,2), (1,4)</var> and <var>(1,9)</var> can be created.

It is possible to create pairs <var>(3,2)</var> and <var>(1,1)</var>, but the number of pairs is not maximized with this.

Sample Input 2

15 10
1 5 6 10 11 11 11 20 21 25 25 26 99 99 99

Sample Output 2

6

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

    let mut memo: Vec<Vec<usize>> = vec![Vec::new(); 100010];
    let mut ans = 0;
    for i in 0..n {
        memo[x[i] % m].push(x[i]);
    }
    for i in 0..m / 2 + 1 {
        if i == 0 || (m.is_multiple_of(2) && i == m / 2) {
            ans += memo[i].len() / 2;
        } else {
            let mut a = memo[i].clone();
            let mut b = memo[m - i].clone();
            if a.len() < b.len() {
                std::mem::swap(&mut a, &mut b);
            }
            let mut same = 0;
            let mut idx = 0;
            while idx < a.len() {
                while idx < a.len() - 1 && a[idx] == a[idx + 1] {
                    idx += 2;
                    same += 1;
                }
                idx += 1;
            }
            ans += b.len() + std::cmp::min((a.len() - b.len()) / 2, same);
        }
    }
    println!("{}", ans);
}


Score: <var>100</var> points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string <var>S</var> representing the weather in the town today. Predict the weather tomorrow.

Constraints

<var>S</var> is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny

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

    io::stdin().read_line(&mut w).expect("Failed to read line");

    let w_str: &str = &w;

    match w_str {
        "Sunny\n" => println!("Cloudy"),
        "Cloudy\n" => println!("Rainy"),
        "Rainy\n" => println!("Sunny"),
        _ => println!("retry enter!"),
    }
}


Score : <var>100</var> points

Problem Statement

Takahashi is a member of a programming competition site, ButCoder.

Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.

The Displayed Rating of a member is equal to their Inner Rating if the member has participated in <var>10</var> or more contests. Otherwise, the Displayed Rating will be their Inner Rating minus <var>100 \times (10 - K)</var> when the member has participated in <var>K</var> contests.

Takahashi has participated in <var>N</var> contests, and his Displayed Rating is <var>R</var>. Find his Inner Rating.

Constraints

All values in input are integers.

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

<var>0 \leq R \leq 4111</var>

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>R</var>

Output

Print his Inner Rating.

Sample Input 1

2 2919

Sample Output 1

3719

Takahashi has participated in <var>2</var> contests, which is less than <var>10</var>, so his Displayed Rating is his Inner Rating minus <var>100 \times (10 - 2) = 800</var>.

Thus, Takahashi's Inner Rating is <var>2919 + 800 = 3719</var>.

Sample Input 2

22 3051

Sample Output 2

3051

int solution(void) {

  int N = 0;
  int R = 0;

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

  if (N < 10) {

    R = R + 100 * (10 - N);
  }

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

  return 0;
}

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

    io::stdin()
        .read_line(&mut buf)
        .expect("Failed to read line");
    let vec_1: Vec<&str> = buf.split_whitespace().collect();
    let n: i32 = vec_1[0].parse().unwrap_or(0);
    let r: i32 = vec_1[1].parse().unwrap_or(0);
    let ans = if n >= 10 { r } else { r + 100 * (10 - n) };

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


Score : <var>200</var> points

Problem Statement

A sequence <var>a=\{a_1,a_2,a_3,......\}</var> is determined as follows:

The first term <var>s</var> is given as input.

Let <var>f(n)</var> be the following function: <var>f(n) = n/2</var> if <var>n</var> is even, and <var>f(n) = 3n+1</var> if <var>n</var> is odd.

<var>a_i = s</var> when <var>i = 1</var>, and <var>a_i = f(a_{i-1})</var> when <var>i > 1</var>.

Find the minimum integer <var>m</var> that satisfies the following condition:

There exists an integer <var>n</var> such that <var>a_m = a_n (m > n)</var>.

Constraints

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

All values in input are integers.

It is guaranteed that all elements in <var>a</var> and the minimum <var>m</var> that satisfies the condition are at most <var>1000000</var>.

Input

Input is given from Standard Input in the following format:

<var>s</var>

Output

Print the minimum integer <var>m</var> that satisfies the condition.

Sample Input 1

8

Sample Output 1

5

<var>a=\{8,4,2,1,4,2,1,4,2,1,......\}</var>. As <var>a_5=a_2</var>, the answer is <var>5</var>.

Sample Input 2

7

Sample Output 2

18

<var>a=\{7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1,4,2,1,......\}</var>.

Sample Input 3

54

Sample Output 3

114

int solution() {
  int s = 0;
  scanf("%d", &s);
  int count[1000000];
  for (int i = 0; i < 1000000; i++) {
    count[i] = 0;
  }
  int buf = s;
  int ans = 0;
  while (1) {
    count[buf]++;
    ans++;
    if (count[buf] > 1) {
      break;
    }
    if (buf % 2 == 0) {
      buf = buf / 2;
    } else {
      buf = 3 * buf + 1;
    }
  }
  printf("%d\n", ans);
  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 s: usize = iter.next().unwrap().parse().unwrap();

    let mut a: Vec<usize> = vec![s];

    let mut prev = s;

    if s == 1 || s == 2 || s == 4 {
        println!("{}", 4);
    } else {
        loop {
            let next = if prev.is_multiple_of(2) {
                prev / 2
            } else {
                3 * prev + 1
            };
            a.push(next);

            if next == 4 {
                break;
            }
            prev = next;
        }

        println!("{}", a.len() + 3);
    }
}


Score : <var>100</var> points

Problem Statement

On the Planet AtCoder, there are four types of bases: A, C, G and T. A bonds with T, and C bonds with G.

You are given a letter <var>b</var> as input, which is A, C, G or T. Write a program that prints the letter representing the base that bonds with the base <var>b</var>.

Constraints

<var>b</var> is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

<var>b</var>

Output

Print the letter representing the base that bonds with the base <var>b</var>.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C

int solution(void) {
  char s[1];
  scanf("%s", s);

  if (*s == 'A') {
    puts("T");

  } else if (*s == 'T') {
    puts("A");

  } else if (*s == 'C') {
    puts("G");

  } else if (*s == 'G') {
    puts("C");
  }

  return 0;
}

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

    std::io::stdin().read_line(&mut b).expect("failed");

    let s = b.trim();
    match s {
        "A" => println!("T"),
        "T" => println!("A"),
        "C" => println!("G"),
        "G" => println!("C"),
        _ => println!("_"),
    }
}


Score : <var>200</var> points

Problem Statement

Some number of chocolate pieces were prepared for a training camp.
The camp had <var>N</var> participants and lasted for <var>D</var> days.
The <var>i</var>-th participant (<var>1 \leq i \leq N</var>) ate one chocolate piece on each of the following days in the camp: the <var>1</var>-st day, the <var>(A_i + 1)</var>-th day, the <var>(2A_i + 1)</var>-th day, and so on.
As a result, there were <var>X</var> chocolate pieces remaining at the end of the camp. During the camp, nobody except the participants ate chocolate pieces.

Find the number of chocolate pieces prepared at the beginning of the camp.

Constraints

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

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

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

<var>1 \leq A_i \leq 100</var> (<var>1 \leq i \leq N</var>)

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>D</var> <var>X</var>
<var>A_1</var>
<var>A_2</var>
<var>:</var>
<var>A_N</var>

Output

Find the number of chocolate pieces prepared at the beginning of the camp.

Sample Input 1

3
7 1
2
5
10

Sample Output 1

8

The camp has <var>3</var> participants and lasts for <var>7</var> days.
Each participant eats chocolate pieces as follows:

The first participant eats one chocolate piece on Day <var>1</var>, <var>3</var>, <var>5</var> and <var>7</var>, for a total of four.

The second participant eats one chocolate piece on Day <var>1</var> and <var>6</var>, for a total of two.

The third participant eats one chocolate piece only on Day <var>1</var>, for a total of one.

Since the number of pieces remaining at the end of the camp is one, the number of pieces prepared at the beginning of the camp is <var>1 + 4 + 2 + 1 = 8</var>.

Sample Input 2

2
8 20
1
10

Sample Output 2

29

Sample Input 3

5
30 44
26
18
81
18
6

Sample Output 3

56

int solution(void) {

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

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

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

    x += ((d - 1) / a[i]) + 1;
  }

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

  return 0;
}

fn solution() {
    let scan = std::io::stdin();
    let mut line = String::new();
    let _ = scan.read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();
    let l: i32 = vec[0].parse().unwrap();

    let scan = std::io::stdin();
    let mut line = String::new();
    let _ = scan.read_line(&mut line);
    let vec: Vec<&str> = line.split_whitespace().collect();
    let d: i32 = vec[0].parse().unwrap();
    let mut ans: i32 = vec[1].parse().unwrap();

    for _ in 0..l {
        let scan = std::io::stdin();
        let mut line = String::new();
        let _ = scan.read_line(&mut line);
        let vec: Vec<&str> = line.split_whitespace().collect();
        let a: i32 = vec[0].parse().unwrap();
        let mut cnt = 1;
        'l1: loop {
            if cnt > d {
                break 'l1;
            }
            ans += 1;
            cnt += a;
        }
    }

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


Score : <var>600</var> points

Problem Statement

We have a tree with <var>N</var> vertices and <var>N-1</var> edges, respectively numbered <var>1, 2,\cdots, N</var> and <var>1, 2, \cdots, N-1</var>. Edge <var>i</var> connects Vertex <var>u_i</var> and <var>v_i</var>.

For integers <var>L, R</var> (<var>1 \leq L \leq R \leq N</var>), let us define a function <var>f(L, R)</var> as follows:

Let <var>S</var> be the set of the vertices numbered <var>L</var> through <var>R</var>. <var>f(L, R)</var> represents the number of connected components in the subgraph formed only from the vertex set <var>S</var> and the edges whose endpoints both belong to <var>S</var>.

Compute <var>\sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R)</var>.

Constraints

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

<var>1 \leq u_i, v_i \leq N</var>

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>u_1</var> <var>v_1</var>
<var>u_2</var> <var>v_2</var>
<var>:</var>
<var>u_{N-1}</var> <var>v_{N-1}</var>

Output

Print <var>\sum_{L=1}^{N} \sum_{R=L}^{N} f(L, R)</var>.

Sample Input 1

3
1 3
2 3

Sample Output 1

7

We have six possible pairs <var>(L, R)</var> as follows:

For <var>L = 1, R = 1</var>, <var>S = \{1\}</var> and we have <var>1</var> connected component.

For <var>L = 1, R = 2</var>, <var>S = \{1, 2\}</var> and we have <var>2</var> connected components.

For <var>L = 1, R = 3</var>, <var>S = \{1, 2, 3\}</var> and we have <var>1</var> connected component, since <var>S</var> contains both endpoints of each of the edges <var>1, 2</var>.

For <var>L = 2, R = 2</var>, <var>S = \{2\}</var> and we have <var>1</var> connected component.

For <var>L = 2, R = 3</var>, <var>S = \{2, 3\}</var> and we have <var>1</var> connected component, since <var>S</var> contains both endpoints of Edge <var>2</var>.

For <var>L = 3, R = 3</var>, <var>S = \{3\}</var> and we have <var>1</var> connected component.

The sum of these is <var>7</var>.

Sample Input 2

2
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

113

int solution() {
  int i;
  int N;
  int u;
  int w;
  long long ans = 0;
  long long tmp;
  scanf("%d", &N);
  for (i = 1; i <= N; i++) {
    ans += (long long)(N - i + 2) * (N - i + 1) / 2;
  }
  for (i = 1; i <= N - 1; i++) {
    scanf("%d %d", &u, &w);
    if (u > w) {
      u ^= w;
      w ^= u;
      u ^= w;
    }
    ans -= (long long)u * (N - w + 1);
  }
  printf("%lld\n", ans);
  fflush(stdout);
  return 0;
}

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

    let mut ans = 0;
    for i in 1..=n {
        ans += i * (n - i + 1);
    }

    for _ in 0..(n - 1) {
        let [u, v]: [usize; 2] = {
            let mut buf = String::new();
            std::io::stdin().read_line(&mut buf).unwrap();
            let mut iter = buf.split_whitespace();
            [
                iter.next().unwrap().parse().unwrap(),
                iter.next().unwrap().parse().unwrap(),
            ]
        };
        ans -= if u < v {
            u * (n - v + 1)
        } else {
            v * (n - u + 1)
        };
    }

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


Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

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

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

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

    let mut n = words[0];
    let mut m = words[1];

    let mut ans = String::new();

    while m > n && n > 0 && m > 0 {
        ans.push_str("110");
        n -= 1;
        m -= 2;
    }

    if m >= n {
        while n > 0 && m > 0 {
            ans.push_str("10");
            n -= 1;
            m -= 1;
        }
    } else {
        while n > 0 && m > 0 {
            ans.push_str("01");
            n -= 1;
            m -= 1;
        }
    }

    if n > 1 || m > 2 {
        println!("-1");
        return;
    }

    print!("{}", ans);
    for _ in 0..m {
        print!("1");
    }
    for _ in 0..n {
        print!("0");
    }
    println!();
}