Score : <var>300</var> points

Problem Statement

You've come to your favorite store Infinitesco to buy some ice tea.

The store sells ice tea in bottles of different volumes at different costs.
Specifically, a <var>0.25</var>-liter bottle costs <var>Q</var> yen, a <var>0.5</var>-liter bottle costs <var>H</var> yen, a <var>1</var>-liter bottle costs <var>S</var> yen, and a <var>2</var>-liter bottle costs <var>D</var> yen.
The store has an infinite supply of bottles of each type.

You want to buy exactly <var>N</var> liters of ice tea. How many yen do you have to spend?

Constraints

<var>1 \leq Q, H, S, D \leq 10^8</var>

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

All input values are integers.

Input

Input is given from Standard Input in the following format:

<var>Q</var> <var>H</var> <var>S</var> <var>D</var>
<var>N</var>

Output

Print the smallest number of yen you have to spend to buy exactly <var>N</var> liters of ice tea.

Sample Input 1

20 30 70 90
3

Sample Output 1

150

Buy one <var>2</var>-liter bottle and two <var>0.5</var>-liter bottles. You'll get <var>3</var> liters for <var>90 + 30 + 30 = 150</var> yen.

Sample Input 2

10000 1000 100 10
1

Sample Output 2

100

Even though a <var>2</var>-liter bottle costs just <var>10</var> yen, you need only <var>1</var> liter.
Thus, you have to buy a <var>1</var>-liter bottle for <var>100</var> yen.

Sample Input 3

10 100 1000 10000
1

Sample Output 3

40

Now it's better to buy four <var>0.25</var>-liter bottles for <var>10 + 10 + 10 + 10 = 40</var> yen.

Sample Input 4

12345678 87654321 12345678 87654321
123456789

Sample Output 4

1524157763907942

int solution(void) {
  long long int q;
  long long int h;
  long long int s;
  long long int d;
  long long int n;
  scanf("%lld %lld %lld %lld", &q, &h, &s, &d);
  scanf("%lld", &n);
  long long int cost = 0;
  long long int count = 0;
  if (q * 8 < h * 4 && q * 8 < s * 2 && q * 8 < d) {
    count = n / 0.25;
    n -= 0.25 * count;
    cost += q * count;
    printf("%lld", cost);
    return 0;
  }
  if (h * 4 < q * 8 && h * 4 < s * 2 && h * 4 < d) {
    count = n / 0.5;
    n -= 0.5 * count;
    cost += h * count;
    if (n == 0) {
      printf("%lld", cost);
      return 0;
    }
    count = n / 0.25;
    n -= 0.25 * count;
    cost += q * count;
    printf("%lld", cost);
    return 0;
  }
  if (s * 2 < h * 4 && s * 2 < q * 8 && s * 2 < d) {
    count = n / 1;
    n -= 1 * count;
    cost += s * count;
    if (n == 0) {
      printf("%lld", cost);
      return 0;
    }
    if (q * 8 < h * 4 && q * 8 < d) {
      count = n / 0.25;
      n -= 0.25 * count;
      cost += q * count;
      printf("%lld", cost);
      return 0;
    } else if (h * 4 < q * 8 && h * 4 < d) {
      count = n / 0.5;
      n -= 0.5 * count;
      cost += h * count;
      if (n == 0) {
        printf("%lld", cost);
        return 0;
      }
      count = n / 0.25;
      n -= 0.25 * count;
      cost += q * count;
      printf("%lld", cost);
      return 0;
    }
  } else if (d < h * 4 && d < s * 2 && d < q * 8) {
    count = n / 2;
    n -= 2 * count;
    cost += d * count;
    if (n == 0) {
      printf("%lld", cost);
      return 0;
    }
    if (q * 8 < h * 4 && q * 8 < s * 2) {
      count = n / 0.25;
      n -= 0.25 * count;
      cost += q * count;
      printf("%lld", cost);
      return 0;
    } else if (h * 4 < q * 8 && h * 4 < s * 2) {
      count = n / 0.5;
      n -= 0.5 * count;
      cost += h * count;
      if (n == 0) {
        printf("%lld", cost);
        return 0;
      }
      count = n / 0.25;
      n -= 0.25 * count;
      cost += q * count;
      printf("%lld", cost);
      return 0;
    } else if (s * 2 < h * 4 && s * 2 < q * 8) {
      count = n / 1;
      n -= 1 * count;
      cost += s * count;
      if (n == 0) {
        printf("%lld", cost);
        return 0;
      }
      if (q * 8 < h * 4) {
        count = n / 0.25;
        n -= 0.25 * count;
        cost += q * count;
        printf("%lld", cost);
        return 0;
      } else if (h * 4 < q * 8) {
        count = n / 0.5;
        n -= 0.5 * count;
        cost += h * count;
        if (n == 0) {
          printf("%lld", cost);
          return 0;
        }
        count = n / 0.25;
        n -= 0.25 * count;
        cost += q * count;
        printf("%lld", cost);
        return 0;
      }
    }
  }
  return 0;
}

fn solution() {
    let (Q, H, S, D): (i64, i64, i64, i64) = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        let mut iter = line.split_whitespace();
        (
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
            iter.next().unwrap().parse().unwrap(),
        )
    };
    let N: i64 = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };

    let C = {
        let mut C = vec![(8 * Q, 0), (4 * H, 1), (2 * S, 2), (D, 3)];
        C.sort();
        C
    };
    let (c, i) = C[0];
    let ans = if i == 3 {
        (N / 2) * c + (N % 2) * (C[1].0 / 2)
    } else {
        N * (c / 2)
    };

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


Score : <var>400</var> points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings <var>s</var> and <var>t</var> are said to be isomorphic when the following conditions are satisfied:

<var>|s| = |t|</var> holds.

For every pair <var>i, j</var>, one of the following holds:

<var>s_i = s_j</var> and <var>t_i = t_j</var>.

<var>s_i \neq s_j</var> and <var>t_i \neq t_j</var>.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string <var>s</var> is said to be in normal form when the following condition is satisfied:

For every string <var>t</var> that is isomorphic to <var>s</var>, <var>s \leq t</var> holds. Here <var>\leq</var> denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer <var>N</var>.
Print all strings of length <var>N</var> that are in normal form, in lexicographically ascending order.

Constraints

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Assume that there are <var>K</var> strings of length <var>N</var> that are in normal form: <var>w_1, \ldots, w_K</var> in lexicographical order.
Output should be in the following format:

<var>w_1</var>
<var>:</var>
<var>w_K</var>

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab

int solution(void) {

  int n;
  scanf("%d", &n);
  int generate[n];
  for (int i = 0; i < n; i++) {
    generate[i] = 0;
  }
  int max[n];
  while (1) {
    for (int i = 0; i < n; i++) {
      max[0] = 0;
      if (i != 0 && generate[i] > max[i - 1]) {
        max[i] = generate[i];
      } else {
        max[i] = max[i - 1];
      }
      printf("%c", 'a' + generate[i]);
    }
    printf("\n");
    if (generate[n - 1] == n - 1) {
      break;
    }
    for (int i = n - 1; i >= 1; i--) {
      if (generate[i] > max[i - 1]) {
        generate[i] = 0;
      } else {
        generate[i]++;
        break;
      }
    }
  }

  return 0;
}

fn solution() {
    input! {
        n: usize,
    };
    let mut s = vec![0; n];
    loop {
        for c in s.iter() {
            print!("{}", (*c + b'a') as char);
        }
        println!();
        let mut change = false;
        for i in (1..n).rev() {
            if s[i] == s[..i].iter().max().unwrap() + 1 {
                s[i] = 0
            } else {
                s[i] += 1;
                change = true;
                break;
            }
        }
        if !change {
            break;
        }
    }
}


void solution(int arr[], int size) {
  int i, j, min = arr[0], max = arr[0], range;

  for (i = 1; i < size; i++) {
    if (arr[i] < min)
      min = arr[i];
    if (arr[i] > max)
      max = arr[i];
  }
  range = max - min + 1;

  int *holes = (int *)malloc(sizeof(int) * range);
  for (i = 0; i < range; i++) {
    holes[i] = 0;
  }
  for (i = 0; i < size; i++) {
    holes[arr[i] - min]++;
  }

  j = 0;
  for (i = 0; i < range; i++) {
    while (holes[i] > 0) {
      arr[j] = i + min;
      holes[i]--;
      j++;
    }
  }

  free(holes);
}

fn solution(array: &mut [i32]) {
    if let (Some(min), Some(max)) = (array.iter().min(), array.iter().max()) {
        let holes_range: usize = (max - min + 1) as usize;
        let mut holes = vec![0; holes_range];
        let mut holes_repeat = vec![0; holes_range];
        for i in array.iter() {
            let index = *i - min;
            holes[index as usize] = *i;
            holes_repeat[index as usize] += 1;
        }
        let mut index = 0;
        for i in 0..holes_range {
            while holes_repeat[i] > 0 {
                array[index] = holes[i];
                index += 1;
                holes_repeat[i] -= 1;
            }
        }
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> people. The name of the <var>i</var>-th person is <var>S_i</var>.

We would like to choose three people so that the following conditions are met:

The name of every chosen person begins with M, A, R, C or H.

There are no multiple people whose names begin with the same letter.

How many such ways are there to choose three people, disregarding order?

Note that the answer may not fit into a <var>32</var>-bit integer type.

Constraints

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

<var>S_i</var> consists of uppercase English letters.

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

<var>S_i \neq S_j (i \neq j)</var>

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S_1</var>
<var>:</var>
<var>S_N</var>

Output

If there are <var>x</var> ways to choose three people so that the given conditions are met, print <var>x</var>.

Sample Input 1

5
MASHIKE
RUMOI
OBIRA
HABORO
HOROKANAI

Sample Output 1

2

We can choose three people with the following names:

MASHIKE, RUMOI, HABORO

MASHIKE, RUMOI, HOROKANAI

Thus, we have two ways.

Sample Input 2

4
ZZ
ZZZ
Z
ZZZZZZZZZZ

Sample Output 2

0

Note that there may be no ways to choose three people so that the given conditions are met.

Sample Input 3

5
CHOKUDAI
RNG
MAKOTO
AOKI
RINGO

Sample Output 3

7

int solution(void) {
  int num;
  long long int m = 0;
  long long int a = 0;
  long long int r = 0;
  long long int c = 0;
  long long int h = 0;

  long long int ans = 0;
  long long int mix[10];
  char name[100000][11];
  scanf("%d", &num);

  for (int i = 0; i < num; i++) {
    scanf("%s", name[i]);
    switch (name[i][0]) {
    case 'M':
      m++;
      break;
    case 'A':
      a++;
      break;
    case 'R':
      r++;
      break;
    case 'C':
      c++;
      break;
    case 'H':
      h++;
      break;
    default:
      break;
    }
  }

  mix[0] = m * a * r;
  mix[1] = m * a * c;
  mix[2] = m * a * h;
  mix[3] = m * r * c;
  mix[4] = m * r * h;
  mix[5] = m * c * h;
  mix[6] = a * r * c;
  mix[7] = a * r * h;
  mix[8] = a * c * h;
  mix[9] = r * c * h;

  for (int i = 0; i < 10; i++) {
    ans += mix[i];
  }
  printf("%lld\n", ans);
}

fn solution() {
    let mut buf: String = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<usize>().unwrap();
    let mut map: HashMap<char, i64> = HashMap::new();
    for _ in 0..n {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        let c: char = buf.chars().next().unwrap();
        if c != 'M' && c != 'A' && c != 'R' && c != 'C' && c != 'H' {
            continue;
        }
        let i: i64 = match map.get(&c) {
            Some(i) => *i,
            None => 0,
        };
        map.insert(c, i + 1);
    }
    let ans: i64 = match map.len() {
        3 => map.values().copied().product(),
        4 => {
            let vs = map.values().copied().collect::<Vec<i64>>();
            vs[0] * vs[1] * vs[2]
                + vs[1] * vs[2] * vs[3]
                + vs[2] * vs[3] * vs[0]
                + vs[3] * vs[0] * vs[1]
        }
        5 => {
            let vs = map.values().copied().collect::<Vec<i64>>();
            vs[0] * vs[1] * vs[2]
                + vs[1] * vs[2] * vs[3]
                + vs[2] * vs[3] * vs[4]
                + vs[3] * vs[4] * vs[0]
                + vs[4] * vs[0] * vs[1]
                + vs[0] * vs[1] * vs[3]
                + vs[1] * vs[2] * vs[4]
                + vs[2] * vs[3] * vs[0]
                + vs[3] * vs[4] * vs[1]
                + vs[4] * vs[0] * vs[2]
        }
        _ => 0,
    };
    println!("{}", ans);
}


Score : <var>300</var> points

Problem Statement

There is a circular pond with a perimeter of <var>K</var> meters, and <var>N</var> houses around them.

The <var>i</var>-th house is built at a distance of <var>A_i</var> meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the <var>N</var> houses.

Constraints

<var>2 \leq K \leq 10^6</var>

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

<var>0 \leq A_1 < ... < A_N < K</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the <var>N</var> houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the <var>1</var>-st house and go to the <var>2</var>-nd and <var>3</var>-rd houses in this order, the total distance traveled will be <var>10</var>.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the <var>2</var>-nd house and go to the <var>1</var>-st and <var>3</var>-rd houses in this order, the total distance traveled will be <var>10</var>.

int solution(void) {

  int K = 0;
  int N = 0;
  int max = 0;

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

  int A[N];
  int distance[N];

  for (int i = 0; i < N; i++) {
    scanf("%d", &A[i]);

    if (i > 0) {
      distance[i] = A[i] - A[i - 1];
    }
    if (distance[i] > max) {
      max = distance[i];
    }
  }
  distance[0] = (K - A[N - 1]) + A[0];

  if (distance[0] > max) {
    max = distance[0];
  }
  max = K - max;

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

  return 0;
}

fn solution() {
    let mut s = String::new();
    let mut s2 = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let s_spl: Vec<&str> = s.trim().split(' ').collect();
    let k: i32 = s_spl[0].to_string().parse().unwrap();
    let mut max = -1;
    let mut a_first = -1;
    let mut a_old = -1;
    io::stdin().read_line(&mut s2).unwrap();
    for s_loop in s2.trim().split(' ') {
        let a: i32 = s_loop.parse().unwrap();
        if a_old == -1 {
            a_first = a;
        } else {
            max = cmp::max(max, a - a_old);
        }
        a_old = a;
    }
    max = cmp::max(max, k + a_first - a_old);
    println!("{}", k - max);
}


One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

int solution(void) {

  int n = 0;
  int m = 0;
  int count = 0;

  int floors[100][200] = {{0}};

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

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m * 2; j++) {
      scanf("%d", floors[i] + j);
      if (j % 2 && floors[i][j - 1] + floors[i][j]) {
        count++;
      }
    }
  }

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

  return 0;
}

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

    let vec = input
        .lines()
        .map(|line| line.split_whitespace())
        .map(|item| {
            item.map(|item| item.parse::<i32>().unwrap())
                .collect::<Vec<i32>>()
        })
        .collect::<Vec<Vec<i32>>>();

    let floors = vec[0][0];
    let flats_per_floor = vec[0][1];
    let windows = flats_per_floor * 2;

    let mut lighter = i32::default();

    for floor in 1usize..floors as usize + 1usize {
        for window in (0usize..windows as usize).step_by(2) {
            if vec[floor][window] != 0 || vec[floor][window + 1usize] != 0 {
                lighter += 1;
            }
        }
    }

    println!("{}", &lighter);
}


Score : <var>300</var> points

Problem Statement

You are given a string <var>S</var> consisting of lowercase English letters.
Another string <var>T</var> is initially empty.
Determine whether it is possible to obtain <var>S = T</var> by performing the following operation an arbitrary number of times:

Append one of the following at the end of <var>T</var>: dream, dreamer, erase and eraser.

Constraints

<var>1≦|S|≦10^5</var>

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

Input

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

<var>S</var>

Output

If it is possible to obtain <var>S = T</var>, print YES. Otherwise, print NO.

Sample Input 1

erasedream

Sample Output 1

YES

Append erase and dream at the end of <var>T</var> in this order, to obtain <var>S = T</var>.

Sample Input 2

dreameraser

Sample Output 2

YES

Append dream and eraser at the end of <var>T</var> in this order, to obtain <var>S = T</var>.

Sample Input 3

dreamerer

Sample Output 3

NO

int solution() {
  char s[100050];
  char temp[10];
  scanf("%s", s);
  int i = 0;
  int end = strlen(s);
  int isPosible = 1;

  while (isPosible) {

    if (i == end) {
      break;
    }
    strncpy(temp, s + i, 5);
    i += 5;
    if (strcmp(temp, "dream") != 0 && strcmp(temp, "erase") != 0) {
      isPosible = 0;

    } else if (strcmp(temp, "erase") == 0) {

      if (s[i] == 'r') {

        i++;
      }
    } else {

      if (s[i] == 'e' && s[i + 1] == 'r') {

        strncpy(temp, s + i, 5);
        if (strcmp(temp, "erase") != 0) {
          i += 2;
        }
      }
    }
  }

  if (isPosible) {
    puts("YES");
  } else {
    puts("NO");
  }

  return 0;
}

fn solution() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let s = buf.trim();
    let n = s.len();
    let mut g = vec![Vec::new(); n];
    let mut reach = vec![0; n + 1];
    reach[0] = 1;
    for &t in &["dream", "dreamer", "erase", "eraser"] {
        for p in s.match_indices(t) {
            g[p.0].push(p.0 + t.len());
        }
    }
    for i in 0..n {
        if reach[i] == 0 {
            continue;
        }
        for &t in &g[i] {
            reach[t] = 1;
        }
    }
    println!("{}", if reach[n] == 1 { "YES" } else { "NO" });
}


Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has h2 health points and an attack power of a2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.Vova's character has h1 health points and an attack power of a1. Also he has a large supply of healing potions, each of which increases his current amount of health points by c1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that c1 > a2.The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by a1) or drink a healing potion (it increases Vova's health by c1; Vova's health can exceed h1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by a2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.

int solution() {
  int map[10005];
  int sum = 0;
  int h1;
  int a1;
  int c1;
  int h2;
  int a2;
  scanf("%d %d %d %d %d", &h1, &a1, &c1, &h2, &a2);
  for (int i = 0;; i++) {
    if (h1 > a2 && h2 > a1) {
      map[sum] = 1;
      h1 = h1 - a2;
      h2 = h2 - a1;

      sum++;
      continue;
    }
    if (h1 <= a2 && h2 > a1) {
      map[sum] = 2;
      h1 = h1 + c1;
      h1 = h1 - a2;

      sum++;
      continue;
    }
    if (h1 <= a2 && h2 <= a1) {
      map[sum] = 1;

      sum++;
      break;
    }
    if (h1 > a2 && h2 <= a1) {
      map[sum] = 1;

      sum++;
      break;
    }
  }
  printf("%d\n", sum);
  for (int i = 0; i < sum; i++) {
    if (map[i] == 1) {
      printf("STRIKE\n");
    } else if (map[i] == 2) {
      printf("HEAL\n");
    }
  }
  return 0;
}

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

    let (mut h1, a1, c1, mut h2, a2) = (
        it.next().unwrap(),
        it.next().unwrap(),
        it.next().unwrap(),
        it.next().unwrap(),
        it.next().unwrap(),
    );

    let mut ans_str = String::new();

    let mut ans_n = 1;

    while h2 > a1 {
        ans_n += 1;
        if h1 > a2 {
            ans_str.push_str("STRIKE\n");
            h2 -= a1;
        } else {
            ans_str.push_str("HEAL\n");
            h1 += c1;
        }
        h1 -= a2;
    }

    ans_str.push_str("STRIKE\n");

    print!("{}\n{}", ans_n, ans_str);
}


You talked to Polycarp and asked him a question. You know that when he wants to answer "yes", he repeats Yes many times in a row.Because of the noise, you only heard part of the answer — some substring of it. That is, if he answered YesYes, then you could hear esY, YesYes, sYes, e, but you couldn't Yess, YES or se.Determine if it is true that the given string $$$s$$$ is a substring of YesYesYes... (Yes repeated many times in a row).

int solution() {
  int t = 0;
  scanf("%d", &t);
  int i = 0;
  char s1[53] = "YesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesY";
  char s2[1000][51] = {0};
  char s3[1000][4] = {0};
  for (i = 0; i < t; i++) {

    scanf("%s", s2[i]);
    if (strstr(s1, s2[i]) != NULL) {
      strcpy(s3[i], "YES");
    } else {
      strcpy(s3[i], "NO");
    }
  }
  for (i = 0; i < t; i++) {
    puts(s3[i]);
  }

  return 0;
}

fn solution() {
    let srch = "YesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYesYes";
    let mut buf = BufWriter::new(io::stdout().lock());
    io::stdin().lines().skip(1).flatten().for_each(|s| {
        let ans = if srch.contains(s.as_str()) {
            "YES"
        } else {
            "NO"
        };
        writeln!(buf, "{ans}").ok();
    });
}


Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times:   $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$),  $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$),  $$$a := a \ | \ b$$$ (replace $$$a$$$ with the bitwise OR of $$$a$$$ and $$$b$$$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$.

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let xs: Vec<usize> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .collect();
        let mut a = xs[0];
        let b = xs[1];
        let mut ans1 = 0;
        loop {
            if a == b {
                break;
            }
            if a | b == b {
                ans1 += 1;
                break;
            }
            a += 1;
            ans1 += 1;
        }
        let a = xs[0];
        let mut b = xs[1];
        let mut ans2 = 0;
        for _ in 0..ans1 {
            if a == b {
                break;
            }
            if a | b == b {
                ans2 += 1;
                break;
            }
            b += 1;
            ans2 += 1;
        }
        println!("{}", min(ans1, ans2));
    }
}


Score : <var>200</var> points

Problem Statement

Print all the integers that satisfies the following in ascending order:

Among the integers between <var>A</var> and <var>B</var> (inclusive), it is either within the <var>K</var> smallest integers or within the <var>K</var> largest integers.

Constraints

<var>1 \leq A \leq B \leq 10^9</var>

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>B</var> <var>K</var>

Output

Print all the integers that satisfies the condition above in ascending order.

Sample Input 1

3 8 2

Sample Output 1

3
4
7
8

<var>3</var> is the first smallest integer among the integers between <var>3</var> and <var>8</var>.

<var>4</var> is the second smallest integer among the integers between <var>3</var> and <var>8</var>.

<var>7</var> is the second largest integer among the integers between <var>3</var> and <var>8</var>.

<var>8</var> is the first largest integer among the integers between <var>3</var> and <var>8</var>.

Sample Input 2

4 8 3

Sample Output 2

4
5
6
7
8

Sample Input 3

2 9 100

Sample Output 3

2
3
4
5
6
7
8
9

int solution(void) {

  static int a;
  static int b;
  static int k;
  scanf("%d%d%d", &a, &b, &k);

  if (a + k - 1 < b - k + 1) {

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

      printf("%d\n", a + i);
    }

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

      printf("%d\n", b - k + i + 1);
    }

  } else {

    for (int i = a; i <= b; i++) {

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

  return 0;
}

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

    let a: i32 = iter.next().unwrap().parse().unwrap();
    let b: i32 = iter.next().unwrap().parse().unwrap();
    let k: i32 = iter.next().unwrap().parse().unwrap();

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

    for i in a..(a + k) {
        if i <= b - k || i <= b {
            v.push(i)
        }
    }
    for i in (b - k + 1)..(b + 1) {
        if v.last().unwrap() < &i {
            v.push(i)
        }
    }

    for i in v {
        println!("{}", i)
    }
}


椅子の総数

選手のみなさん、パソコン甲子園にようこそ。パソコン甲子園の本選は会津大学で行われ、会場内では
１つの机に１チームが割り当てられます。パソコン甲子園は１チーム２人なので、チーム数×２脚の椅子が必要です。大学では、他にも様々なイベントの会場設営で机と椅子を準備する機会がありますが、必要な机と椅子の数も様々です。そこで、あるイベントに対して準備する机の数と、机１つあたりに必要な椅子の数が与えられたとき、必要な椅子の総数を計算するプログラムを作成してください。

入力

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

<var>d</var> <var>c</var>

入力は１行であり、必要な机の数 <var>d</var> (1 ≤ <var>d</var> ≤ 100) と机１つあたりに必要な椅子の数 <var>c</var> (1 ≤ <var>c</var> ≤ 10) を表す整数が与えられる。

出力

イベントにおいて必要な椅子の総数を１行に出力する。

入出力例

入力例１

20 2

 出力例１

40

入力例２

1 1

 出力例２

1

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

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

    let (d, c) = {
        let mut iter = input.split_whitespace().map(|s| s.parse::<u32>().unwrap());

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

    println!("{}", d * c);
}


You are given a long decimal number $$$a$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$. You also have a function $$$f$$$ that maps every digit from $$$1$$$ to $$$9$$$ to some (possibly the same) digit from $$$1$$$ to $$$9$$$.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $$$a$$$, and replace each digit $$$x$$$ from this segment with $$$f(x)$$$. For example, if $$$a = 1337$$$, $$$f(1) = 1$$$, $$$f(3) = 5$$$, $$$f(7) = 3$$$, and you choose the segment consisting of three rightmost digits, you get $$$1553$$$ as the result.What is the maximum possible number you can obtain applying this operation no more than once?

fn solution() {
    let mut _buffer = String::new();
    io::stdin()
        .read_line(&mut _buffer)
        .expect("failed to read input");
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read input");
    let mut a = buffer
        .trim()
        .chars()
        .map(|c| c.to_digit(10).unwrap() as u8)
        .collect::<Vec<u8>>();
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("failed to read input");
    let f = buffer
        .split_whitespace()
        .map(|x| x.parse::<u8>().unwrap())
        .collect::<Vec<u8>>();

    let mut started = false;
    for i in &mut a {
        if f[*i as usize - 1] > *i {
            if !started {
                started = true;
            }
            *i = f[*i as usize - 1];
        } else if f[*i as usize - 1] < *i && started {
            break;
        }
    }
    for i in &a {
        print!("{}", *i);
    }
    println!();
}


There are three sticks with integer lengths $$$l_1, l_2$$$ and $$$l_3$$$.You are asked to break exactly one of them into two pieces in such a way that:   both pieces have positive (strictly greater than $$$0$$$) integer length;  the total length of the pieces is equal to the original length of the stick;  it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle.Determine if it's possible to do that.

fn solution() {
    let mut t = String::new();
    io::stdin().read_line(&mut t).expect("read t");
    let t: i32 = t.trim().parse().expect("parse t");

    for _ in 0..t {
        let mut l = String::new();
        io::stdin().read_line(&mut l).expect("read l");
        let l: Result<Vec<i32>, _> = l.trim().split(' ').map(str::parse).collect();
        let mut l = l.expect("parse l");
        l.sort();
        if (l[0] + l[1] == l[2])
            || (l[0] % 2 == 0 && l[1] == l[2])
            || (l[0] == l[1] && l[2] % 2 == 0)
        {
            println!("YES");
        } else {
            println!("NO");
        }
    }
}


Score : <var>600</var> points

Problem Statement

In Dwango Co., Ltd., there is a content distribution system named 'Dwango Media Cluster', and it is called 'DMC' for short.

The name 'DMC' sounds cool for Niwango-kun, so he starts to define DMC-ness of a string.

Given a string <var>S</var> of length <var>N</var> and an integer <var>k</var> <var>(k \geq 3)</var>,
he defines the <var>k</var>-DMC number of <var>S</var> as the number of triples <var>(a, b, c)</var> of integers that satisfy the following conditions:

<var>0 \leq a < b < c \leq N - 1</var>

<var>S[a]</var> = D

<var>S[b]</var> = M

<var>S[c]</var> = C

<var>c-a < k</var>

Here <var>S[a]</var> is the <var>a</var>-th character of the string <var>S</var>. Indexing is zero-based, that is, <var>0 \leq a \leq N - 1</var> holds.

For a string <var>S</var> and <var>Q</var> integers <var>k_0, k_1, ..., k_{Q-1}</var>, calculate the <var>k_i</var>-DMC number of <var>S</var> for each <var>i</var> <var>(0 \leq i \leq Q-1)</var>.

Constraints

<var>3 \leq N \leq 10^6</var>

<var>S</var> consists of uppercase English letters

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

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

All numbers given in input are integers

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>S</var>
<var>Q</var>
<var>k_{0}</var> <var>k_{1}</var> <var>...</var> <var>k_{Q-1}</var>

Output

Print <var>Q</var> lines.
The <var>i</var>-th line should contain the <var>k_i</var>-DMC number of the string <var>S</var>.

Sample Input 1

18
DWANGOMEDIACLUSTER
1
18

Sample Output 1

1

<var>(a,b,c) = (0, 6, 11)</var> satisfies the conditions.

Strangely, Dwango Media Cluster does not have so much DMC-ness by his definition.

Sample Input 2

18
DDDDDDMMMMMCCCCCCC
1
18

Sample Output 2

210

The number of triples can be calculated as <var>6\times 5\times 7</var>.

Sample Input 3

54
DIALUPWIDEAREANETWORKGAMINGOPERATIONCORPORATIONLIMITED
3
20 30 40

Sample Output 3

0
1
2

<var>(a, b, c) = (0, 23, 36), (8, 23, 36)</var> satisfy the conditions except the last one, namely, <var>c-a < k_i</var>.

By the way, DWANGO is an acronym for "Dial-up Wide Area Network Gaming Operation".

Sample Output 4

30
DMCDMCDMCDMCDMCDMCDMCDMCDMCDMC
4
5 10 15 20

Sample Output 4

10
52
110
140

fn solution() {
    let mut s = String::new();
    use std::io::{Read, Write};
    std::io::stdin().read_to_string(&mut s).unwrap();
    let mut it = s.split_whitespace();
    let _n: usize = it.next().unwrap().parse().unwrap();
    let s: Vec<_> = it.next().unwrap().chars().collect();
    let _q: usize = it.next().unwrap().parse().unwrap();
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    for k in it.map(|a| a.parse::<usize>().unwrap()) {
        let mut ans = 0u64;
        let mut cnt = (0, 0, 0);
        for i in 0..s.len() {
            match s[i] {
                'D' => cnt.0 += 1,
                'M' => {
                    cnt.1 += 1;
                    cnt.2 += cnt.0;
                }
                'C' => {
                    ans += cnt.2;
                }
                _ => (),
            }
            if i < k - 1 {
                continue;
            }
            match s[i - (k - 1)] {
                'D' => {
                    cnt.0 -= 1;
                    cnt.2 -= cnt.1;
                }
                'M' => {
                    cnt.1 -= 1;
                }
                _ => (),
            }
        }
        writeln!(out, "{}", ans).unwrap();
    }
}


Score : <var>200</var> points

Problem Statement

Given is a string <var>S</var>. Replace every character in <var>S</var> with x and print the result.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Replace every character in <var>S</var> with x and print the result.

Sample Input 1

sardine

Sample Output 1

xxxxxxx

Replacing every character in <var>S</var> with x results in xxxxxxx.

Sample Input 2

xxxx

Sample Output 2

xxxx

Sample Input 3

gone

Sample Output 3

xxxx

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).expect("");
    buf = buf.trim().to_string();
    for _n in 0..buf.len() {
        print!("x");
    }
    println!();
}


In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game.Tzuyu gave Sana two integers $$$a$$$ and $$$b$$$ and a really important quest.In order to complete the quest, Sana has to output the smallest possible value of ($$$a \oplus x$$$) + ($$$b \oplus x$$$) for any given $$$x$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.

int solution() {
  int t = 0;
  scanf("%d", &t);
  for (int i = 0; i < t; i++) {
    int a = 0;
    int b = 0;
    int x = 0;
    scanf("%d %d", &a, &b);
    if (a == b) {
      printf("0\n");
    } else {
      x = a ^ b;
      printf("%d\n", x);
    }
  }
}

fn solution() {
    let mut input = "".split_ascii_whitespace();
    let mut read = || loop {
        if let Some(word) = input.next() {
            break word;
        }
        input = {
            let mut input = "".to_owned();
            io::stdin().read_line(&mut input).unwrap();
            if input.is_empty() {
                panic!("reached EOF");
            }
            Box::leak(input.into_boxed_str()).split_ascii_whitespace()
        };
    };

    let t = read!(usize);
    for _ in 0..t {
        let a = read!(i64);
        let b = read!(i64);
        println!("{}", a ^ b);
    }
}


Score : <var>200</var> points

Problem Statement

Snuke lives on an infinite two-dimensional plane. He is going on an <var>N</var>-day trip.
At the beginning of Day <var>1</var>, he is at home. His plan is described in a string <var>S</var> of length <var>N</var>.
On Day <var>i(1 ≦ i ≦ N)</var>, he will travel a positive distance in the following direction:

North if the <var>i</var>-th letter of <var>S</var> is N

West if the <var>i</var>-th letter of <var>S</var> is W

South if the <var>i</var>-th letter of <var>S</var> is S

East if the <var>i</var>-th letter of <var>S</var> is E

He has not decided each day's travel distance. Determine whether it is possible to set each day's travel distance so that he will be back at home at the end of Day <var>N</var>.

Constraints

<var>1 ≦ | S | ≦ 1000</var>

<var>S</var> consists of the letters N, W, S, E.

Input

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

<var>S</var>

Output

Print Yes if it is possible to set each day's travel distance so that he will be back at home at the end of Day <var>N</var>. Otherwise, print No.

Sample Input 1

SENW

Sample Output 1

Yes

If Snuke travels a distance of <var>1</var> on each day, he will be back at home at the end of day <var>4</var>.

Sample Input 2

NSNNSNSN

Sample Output 2

Yes

Sample Input 3

NNEW

Sample Output 3

No

Sample Input 4

W

Sample Output 4

No

fn solution() {
    let mut stdin = io::stdin();
    let mut lines = String::new();
    let _ = stdin.read_to_string(&mut lines);
    let vec = lines.lines().collect::<Vec<&str>>();
    let s = vec[0];

    let mut ncnt = 0;
    let mut scnt = 0;
    let mut ecnt = 0;
    let mut wcnt = 0;
    for i in s.chars() {
        match i {
            'N' => {
                ncnt += 1;
            }
            'S' => {
                scnt += 1;
            }
            'E' => {
                ecnt += 1;
            }
            'W' => {
                wcnt += 1;
            }
            _ => {}
        }
    }
    if (ncnt == 0 && scnt != 0)
        || (scnt == 0 && ncnt != 0)
        || (ecnt == 0 && wcnt != 0)
        || (wcnt == 0 && ecnt != 0)
    {
        println!("No");
    } else {
        println!("Yes");
    }
}


Score : <var>100</var> points

Problem Statement

There are <var>N</var> stones, numbered <var>1, 2, \ldots, N</var>.
For each <var>i</var> (<var>1 \leq i \leq N</var>), the height of Stone <var>i</var> is <var>h_i</var>.

There is a frog who is initially on Stone <var>1</var>.
He will repeat the following action some number of times to reach Stone <var>N</var>:

If the frog is currently on Stone <var>i</var>, jump to Stone <var>i + 1</var> or Stone <var>i + 2</var>. Here, a cost of <var>|h_i - h_j|</var> is incurred, where <var>j</var> is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone <var>N</var>.

Constraints

All values in input are integers.

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>h_1</var> <var>h_2</var> <var>\ldots</var> <var>h_N</var>

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path <var>1</var> → <var>2</var> → <var>4</var>, the total cost incurred would be <var>|10 - 30| + |30 - 20| = 30</var>.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path <var>1</var> → <var>2</var>, the total cost incurred would be <var>|10 - 10| = 0</var>.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path <var>1</var> → <var>3</var> → <var>5</var> → <var>6</var>, the total cost incurred would be <var>|30 - 60| + |60 - 60| + |60 - 50| = 40</var>.

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

    let mut dp: Vec<i64> = vec![1 << 30; n + 2];
    dp[0] = 0;
    for i in 0..n - 1 {
        dp[i + 1] = std::cmp::min(dp[i + 1], dp[i] + (a[i + 1] - a[i]).abs());

        if i + 2 < n {
            dp[i + 2] = std::cmp::min(dp[i + 2], dp[i] + (a[i + 2] - a[i]).abs());
        }
    }
    println!("{}", dp[n - 1]);
}


Score : <var>400</var> points

Problem Statement

Given is a string <var>S</var> consisting of L and R.

Let <var>N</var> be the length of <var>S</var>. There are <var>N</var> squares arranged from left to right, and the <var>i</var>-th character of <var>S</var> from the left is written on the <var>i</var>-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below <var>10^{100}</var> times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

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

Each character of <var>S</var> is L or R.

The first and last characters of <var>S</var> are R and L, respectively.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is <var>0, 2, 1, 1, 1</var> from left to right.

After each child performed two moves, the number of children standing on each square is <var>0, 1, 2, 1, 1</var> from left to right.

After each child performed <var>10^{100}</var> moves, the number of children standing on each square is <var>0, 1, 2, 1, 1</var> from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

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

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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

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

    let s = {
        let mut input = String::new();
        stdin.read_line(&mut input).unwrap();
        input.trim().to_string()
    };

    let vec = {
        let mut vec = Vec::with_capacity(100_000);

        let mut state = 'R';
        let mut counter: i32 = 0;

        for c in s.chars() {
            if c == state {
                counter += 1;
            } else {
                vec.push(counter);
                counter = 1;
                state = if state == 'R' { 'L' } else { 'R' };
            }
        }
        vec.push(counter);

        vec
    };

    for i in 0..vec.len() / 2 {
        let i = 2 * i;
        let x = (vec[i] + 1) / 2 + vec[i + 1] / 2;
        let y = vec[i] / 2 + (vec[i + 1] + 1) / 2;

        let xp: Vec<u8> = (0..2 * vec[i] - 2)
            .map(|i| if i % 2 == 0 { 48 } else { 32 })
            .collect();
        let yp: Vec<u8> = (0..2 * vec[i + 1] - 2)
            .map(|i| if i % 2 == 0 { 48 } else { 32 })
            .collect();

        print!(
            "{}{} {} {}",
            String::from_utf8(xp).unwrap(),
            x,
            y,
            String::from_utf8(yp).unwrap(),
        );
    }

    println!();
}


Score : <var>300</var> points

Problem Statement

Does <var>\sqrt{a} + \sqrt{b} < \sqrt{c}</var> hold?

Constraints

<var>1 \leq a, b, c \leq 10^9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>a \ b \ c</var>

Output

If <var>\sqrt{a} + \sqrt{b} < \sqrt{c}</var>, print Yes; otherwise, print No.

Sample Input 1

2 3 9

Sample Output 1

No

<var>\sqrt{2} + \sqrt{3} < \sqrt{9}</var> does not hold.

Sample Input 2

2 3 10

Sample Output 2

Yes

<var>\sqrt{2} + \sqrt{3} < \sqrt{10}</var> holds.

fn solution() {
    let mut s: String = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.split_whitespace();
    let a: i64 = itr.next().unwrap().parse().unwrap();
    let b: i64 = itr.next().unwrap().parse().unwrap();
    let c: i64 = itr.next().unwrap().parse().unwrap();
    let x = 4 * a * b;
    let y = c - a - b;
    if y > 0 && x < y * y {
        println!("Yes");
    } else {
        println!("No");
    }
}


Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples:  if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$$$;  if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$$$;  if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows.

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 n: i64 = str.trim().parse().unwrap();
        if n == 3 {
            println!("1 0 0");
        } else if n < 5 {
            println!("-1");
        } else {
            let mut t: i64 = 0;
            let mut f: i64 = (n / 5) - 1;
            let mut s: i64 = 0;
            match n % 5 {
                0 => f += 1,
                1 => t += 2,
                2 => s += 1,
                3 => {
                    f += 1;
                    t += 1
                }
                4 => t += 3,
                _ => t += 0,
            }
            println!("{} {} {}", t, f, s);
        }
    }
}


Score : <var>300</var> points

Problem Statement

In Takahashi Kingdom, there is an archipelago of <var>N</var> islands, called Takahashi Islands.
For convenience, we will call them Island <var>1</var>, Island <var>2</var>, ..., Island <var>N</var>.

There are <var>M</var> kinds of regular boat services between these islands.
Each service connects two islands. The <var>i</var>-th service connects Island <var>a_i</var> and Island <var>b_i</var>.

Cat Snuke is on Island <var>1</var> now, and wants to go to Island <var>N</var>.
However, it turned out that there is no boat service from Island <var>1</var> to Island <var>N</var>, so he wants to know whether it is possible to go to Island <var>N</var> by using two boat services.

Help him.

Constraints

<var>3 ≤ N ≤ 200</var> <var>000</var>

<var>1 ≤ M ≤ 200</var> <var>000</var>

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

<var>(a_i, b_i) \neq (1, N)</var>

If <var>i \neq j</var>, <var>(a_i, b_i) \neq (a_j, b_j)</var>.

Input

Input is given from Standard Input in the following format:

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

Output

If it is possible to go to Island <var>N</var> by using two boat services, print POSSIBLE; otherwise, print IMPOSSIBLE.

Sample Input 1

3 2
1 2
2 3

Sample Output 1

POSSIBLE

Sample Input 2

4 3
1 2
2 3
3 4

Sample Output 2

IMPOSSIBLE

You have to use three boat services to get to Island <var>4</var>.

Sample Input 3

100000 1
1 99999

Sample Output 3

IMPOSSIBLE

Sample Input 4

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

Sample Output 4

POSSIBLE

You can get to Island <var>5</var> by using two boat services: Island <var>1</var> -> Island <var>4</var> -> Island <var>5</var>.

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    let v: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
    let mut x: Vec<usize> = Vec::new();
    let mut y: HashSet<usize> = HashSet::new();
    for _ in 0..v[1] {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).unwrap();
        let u: Vec<usize> = s.split_whitespace().map(|x| x.parse().unwrap()).collect();
        if u[0] == 1 {
            x.push(u[1]);
        }
        if u[1] == v[0] {
            y.insert(u[0]);
        }
    }
    for i in &x {
        if y.contains(i) {
            println!("POSSIBLE");
            return;
        }
    }
    println!("IMPOSSIBLE");
}


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

int solution() {
  int t;
  int n;
  int x;
  int d;
  int h;
  scanf("%d", &t);
  while (t--) {
    int D = 0;
    int max = 0;
    scanf("%d%d", &n, &x);
    for (int i = 0; i < n; i++) {
      scanf("%d%d", &d, &h);
      if (d > max) {
        max = d;
      }
      if (d - h > D) {
        D = d - h;
      }
    }
    if (max >= x) {
      printf("1\n");
    } else if (max < x && D <= 0) {
      printf("-1\n");
    } else {
      int ans;
      ans = (x + D - max - 1) / D + 1;
      printf("%d\n", ans);
    }
  }
  return 0;
}

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

    let t = get!();
    for _ in 0..t {
        let n = get!();
        let x = get!();
        let mut bs = vec![];
        let mut max_d = 0;
        for _ in 0..n {
            let d = get!();
            let h = get!();
            if d > h {
                bs.push((d, h));
            }
            max_d = std::cmp::max(max_d, d);
        }
        if max_d >= x {
            println!("1");
            continue;
        }
        if bs.is_empty() {
            println!("-1");
            continue;
        }
        let mut ans = std::i64::MAX;
        for &(d, h) in bs.iter() {
            let mut c = (max_d - x) / (h - d);
            while x - d * c + h * c > max_d {
                c += 1;
            }
            ans = std::cmp::min(ans, c + 1);
        }
        println!("{}", ans);
    }
}


Igor the analyst has adopted n little bunnies. As we all know, bunnies love carrots. Thus, Igor has bought a carrot to be shared between his bunnies. Igor wants to treat all the bunnies equally, and thus he wants to cut the carrot into n pieces of equal area. Formally, the carrot can be viewed as an isosceles triangle with base length equal to 1 and height equal to h. Igor wants to make n - 1 cuts parallel to the base to cut the carrot into n pieces. He wants to make sure that all n pieces have the same area. Can you help Igor determine where to cut the carrot so that each piece have equal area?  Illustration to the first example.

int solution() {
  double n;
  double h;
  scanf("%lf%lf", &n, &h);
  for (int i = 1; i < n; i++) {
    printf("%.12lf\n", sqrt(i / n) * h);
  }
  return 0;
}

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

    for k in 1..n as usize {
        let ans = h * (k as f64 / n).sqrt();
        println!("{}", ans);
    }
}


The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings:   $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$);  $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$);  $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.

int solution() {
  int n = 0;
  int i = 0;
  long long int ans = 0;
  char current = 0;
  char s[524228];
  char stroka_answer[32];
  int m[524228];
  int M = 0;
  scanf("%d", &n);
  scanf("%s", s);
  for (i = 0; i < n; i++) {
    if (s[i] != current) {
      current = s[i];
      M++;
      m[M - 1] = 1;
    } else {
      m[M - 1]++;
    }
  }
  if (M == 1) {
    ans = ((long long int)n) * ((long long int)(n - 1)) / 2;
  } else {
    ans = m[0] + m[M - 1] - M + 1;
    for (i = 1; i < M - 1; i++) {
      ans += 2 * m[i];
    }
    ans = ((long long int)n) * ((long long int)(n - 1)) / 2 - ans;
  }
  stroka_answer[31] = 0;
  i = 30;
  while (ans != 0) {
    stroka_answer[i] = (ans % 10) + '0';
    ans /= 10;
    i--;
  }
  printf("%s\n", stroka_answer + i + 1);
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin
        .lock()
        .lines()
        .map(|l| l.expect("stdin line exhausted"));

    let n: usize = lines.next().and_then(|s| s.parse().ok()).expect("read n");
    let mut s: Vec<_> = lines.next().expect("read s").bytes().collect();
    assert_eq!(s.len(), n);

    let mut res = {
        let t = n as i64;
        t * (t - 1) / 2
    };
    for x in 0..2 {
        let mut cur = 1;
        for i in 1..n {
            if s[i] == s[i - 1] {
                cur += 1;
            } else {
                res -= cur - x;
                cur = 1;
            }
        }
        s.reverse();
    }

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


Score: <var>400</var> points

Problem Statement

Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.

The shop sells <var>N</var> kinds of cakes.

Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The <var>i</var>-th kind of cake has the beauty of <var>x_i</var>, the tastiness of <var>y_i</var> and the popularity of <var>z_i</var>.

These values may be zero or negative.

Ringo has decided to have <var>M</var> pieces of cakes here. He will choose the set of cakes as follows:

Do not have two or more pieces of the same kind of cake.

Under the condition above, choose the set of cakes to maximize (the absolute value of the total beauty) + (the absolute value of the total tastiness)  + (the absolute value of the total popularity).

Find the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Constraints

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

<var>M</var> is an integer between <var>0</var> and <var>N</var> (inclusive).

<var>x_i, y_i, z_i \ (1 \leq i \leq N)</var> are integers between <var>-10 \ 000 \ 000 \ 000</var> and <var>10 \ 000 \ 000 \ 000</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var>
<var>x_1</var> <var>y_1</var> <var>z_1</var>
<var>x_2</var> <var>y_2</var> <var>z_2</var>
 <var>:</var>  <var>:</var>
<var>x_N</var> <var>y_N</var> <var>z_N</var>

Output

Print the maximum possible value of (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) for the set of cakes that Ringo chooses.

Sample Input 1

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

Sample Output 1

56

Consider having the <var>2</var>-nd, <var>4</var>-th and <var>5</var>-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: <var>1 + 3 + 9 = 13</var>

Tastiness: <var>5 + 5 + 7 = 17</var>

Popularity: <var>9 + 8 + 9 = 26</var>

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is <var>13 + 17 + 26 = 56</var>. This is the maximum value.

Sample Input 2

5 3
1 -2 3
-4 5 -6
7 -8 -9
-10 11 -12
13 -14 15

Sample Output 2

54

Consider having the <var>1</var>-st, <var>3</var>-rd and <var>5</var>-th kinds of cakes. The total beauty, tastiness and popularity will be as follows:

Beauty: <var>1 + 7 + 13 = 21</var>

Tastiness: <var>(-2) + (-8) + (-14) = -24</var>

Popularity: <var>3 + (-9) + 15 = 9</var>

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is <var>21 + 24 + 9 = 54</var>. This is the maximum value.

Sample Input 3

10 5
10 -80 21
23 8 38
-94 28 11
-26 -2 18
-69 72 79
-26 -86 -54
-72 -50 59
21 65 -32
40 -94 87
-62 18 82

Sample Output 3

638

If we have the <var>3</var>-rd, <var>4</var>-th, <var>5</var>-th, <var>7</var>-th and <var>10</var>-th kinds of cakes, the total beauty, tastiness and popularity will be <var>-323</var>, <var>66</var> and <var>249</var>, respectively.

The value (the absolute value of the total beauty) + (the absolute value of the total tastiness) + (the absolute value of the total popularity) here is <var>323 + 66 + 249 = 638</var>. This is the maximum value.

Sample Input 4

3 2
2000000000 -9000000000 4000000000
7000000000 -5000000000 3000000000
6000000000 -1000000000 8000000000

Sample Output 4

30000000000

The values of the beauty, tastiness and popularity of the cakes and the value to be printed may not fit into 32-bit integers.

fn solution() {
    let mut count_line = String::new();
    std::io::stdin().read_line(&mut count_line).ok();
    let mut count_it = count_line.split_whitespace();
    let line_count: u32 = count_it.next().unwrap().parse().unwrap();
    let amount: u32 = count_it.next().unwrap().parse().unwrap();
    let values: Vec<(i64, i64, i64)> = (0..line_count)
        .map(|_| {
            let mut s = String::new();
            std::io::stdin().read_line(&mut s).ok();
            let mut it = s.split_whitespace();
            (
                it.next().unwrap().parse().unwrap(),
                it.next().unwrap().parse().unwrap(),
                it.next().unwrap().parse().unwrap(),
            )
        })
        .collect();
    let mut ppp: BinaryHeap<i64> = values.iter().map(|v| v.0 + v.1 + v.2).collect();
    let mut ppp_val = 0;
    for _ in 0..amount {
        ppp_val += ppp.pop().unwrap();
    }
    let mut ppm: BinaryHeap<i64> = values.iter().map(|v| v.0 + v.1 - v.2).collect();
    let mut ppm_val = 0;
    for _ in 0..amount {
        ppm_val += ppm.pop().unwrap();
    }
    let mut pmp: BinaryHeap<i64> = values.iter().map(|v| v.0 - v.1 + v.2).collect();
    let mut pmp_val = 0;
    for _ in 0..amount {
        pmp_val += pmp.pop().unwrap();
    }
    let mut pmm: BinaryHeap<i64> = values.iter().map(|v| v.0 - v.1 - v.2).collect();
    let mut pmm_val = 0;
    for _ in 0..amount {
        pmm_val += pmm.pop().unwrap();
    }
    let mut mpp: BinaryHeap<i64> = values.iter().map(|v| -v.0 + v.1 + v.2).collect();
    let mut mpp_val = 0;
    for _ in 0..amount {
        mpp_val += mpp.pop().unwrap();
    }
    let mut mpm: BinaryHeap<i64> = values.iter().map(|v| -v.0 + v.1 - v.2).collect();
    let mut mpm_val = 0;
    for _ in 0..amount {
        mpm_val += mpm.pop().unwrap();
    }
    let mut mmp: BinaryHeap<i64> = values.iter().map(|v| -v.0 - v.1 + v.2).collect();
    let mut mmp_val = 0;
    for _ in 0..amount {
        mmp_val += mmp.pop().unwrap();
    }
    let mut mmm: BinaryHeap<i64> = values.iter().map(|v| -v.0 - v.1 - v.2).collect();
    let mut mmm_val = 0;
    for _ in 0..amount {
        mmm_val += mmm.pop().unwrap();
    }
    println!(
        "{}",
        [ppp_val, ppm_val, pmp_val, pmm_val, mpp_val, mpm_val, mmp_val, mmm_val]
            .iter()
            .fold(0, |acc, x| if acc >= *x { acc } else { *x })
    );
}


You are given three integers $$$a \le b \le c$$$.In one move, you can add $$$+1$$$ or $$$-1$$$ to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers $$$A \le B \le C$$$ such that $$$B$$$ is divisible by $$$A$$$ and $$$C$$$ is divisible by $$$B$$$.You have to answer $$$t$$$ independent test cases.

int solution() {
  int n;
  scanf("%d", &n);
  while (n--) {
    int res = 90009;
    int a;
    int b;
    int c;
    int aa;
    int bb;
    int cc;
    scanf("%d %d %d", &a, &b, &c);
    for (int i = 1; i <= 10100; i++) {
      for (int j = 1; i * j <= 10100; j++) {
        for (int k = 1; i * j * k <= 10100; k++) {
          int d = abs(a - i) + abs(b - (i * j)) + abs(c - (i * j * k));
          if (d < res) {
            res = d;
            aa = i;
            bb = j * i;
            cc = i * j * k;
          }
        }
      }
    }
    printf("%d\n%d %d %d\n", res, aa, bb, cc);
  }
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines().map(|l| l.unwrap());
    let t: u64 = lines.next().unwrap().trim().parse().unwrap();
    for _ in 0..t {
        let line = lines.next().unwrap();
        let mut parts = line.split_whitespace();
        let a: i64 = parts.next().unwrap().parse().unwrap();
        let b: i64 = parts.next().unwrap().parse().unwrap();
        let c: i64 = parts.next().unwrap().parse().unwrap();

        let mut besta = -1;
        let mut bestb = -1;
        let mut bestc = -1;
        let mut bestcost = 10000000;

        let limit = 40000;
        for ac in 1..limit {
            let mut bcs = Vec::new();
            let mut bc = ac;
            while bc <= limit {
                bcs.push(bc);
                bc += ac;
            }

            for bc in bcs {
                let mut cc1 = c - (c % bc);
                let cc2 = cc1 + bc;

                if cc1 == 0 {
                    cc1 = cc2;
                }

                let cost1 = (ac - a).abs() + (bc - b).abs() + (cc1 - c).abs();
                let cost2 = (ac - a).abs() + (bc - b).abs() + (cc2 - c).abs();

                if cost1 < bestcost {
                    besta = ac;
                    bestb = bc;
                    bestc = cc1;
                    bestcost = cost1;
                }

                if cost2 < bestcost {
                    besta = ac;
                    bestb = bc;
                    bestc = cc2;
                    bestcost = cost2;
                }
            }
        }

        println!("{}", bestcost);
        println!("{} {} {}", besta, bestb, bestc);
    }
}


Score : <var>300</var> points

Problem Statement

Let <var>f(n)</var> be the number of triples of integers <var>(x,y,z)</var> that satisfy both of the following conditions:

<var>1 \leq x,y,z</var>

<var>x^2 + y^2 + z^2 + xy + yz + zx = n</var>

Given an integer <var>N</var>, find each of <var>f(1),f(2),f(3),\ldots,f(N)</var>.

Constraints

All values in input are integers.

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print <var>N</var> lines. The <var>i</var>-th line should contain the value <var>f(i)</var>.

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For <var>n=6</var>, only <var>(1,1,1)</var> satisfies both of the conditions. Thus, <var>f(6) = 1</var>.

For <var>n=11</var>, three triples, <var>(1,1,2)</var>, <var>(1,2,1)</var>, and <var>(2,1,1)</var>, satisfy both of the conditions. Thus, <var>f(6) = 3</var>.

For <var>n=17</var>, three triples, <var>(1,2,2)</var>, <var>(2,1,2)</var>, and <var>(2,2,1)</var>, satisfy both of the conditions. Thus, <var>f(17) = 3</var>.

For <var>n=18</var>, three triples, <var>(1,1,3)</var>, <var>(1,3,1)</var>, and <var>(3,1,1)</var>, satisfy both of the conditions. Thus, <var>f(18) = 3</var>.

int solution(void) {
  int datanum = 0;
  int x = 0;
  int y = 0;
  int z = 0;
  int n = 0;
  int i = 0;
  int count = 0;

  scanf("%d", &datanum);

  for (i = 1; i <= datanum; i++) {
    count = 0;
    for (x = 1; x < 99; x++) {
      for (y = 1; y < 99; y++) {
        for (z = 1; z < 99; z++) {
          n = (x * x) + (y * y) + (z * z) + (x * y) + (y * z) + (z * x);
          if (n > i) {
            break;
          }
          if (n == i) {
            count++;
          }
        }
      }
    }
    printf("%d\n", count);
  }

  return 0;
}

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

    let mut memo = vec![0; 10010];
    let mut x = 1;
    while x * x <= n {
        let mut y = 1;
        while y * y <= n {
            let mut z = 1;
            while z * z <= n {
                let val = x * x + y * y + z * z + x * y + y * z + z * x;
                if val <= n {
                    memo[val] += 1;
                }
                z += 1;
            }
            y += 1;
        }
        x += 1;
    }
    let mut out = Vec::new();

    for i in 1..=n {
        writeln!(out, "{}", memo[i]).ok();
    }
    stdout().write_all(&out).unwrap();
}


Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed his luck.When he arrived home, he began to study how his generator works and learned the algorithm. The process of generating a permutation consists of $$$n$$$ steps. At the $$$i$$$-th step, a place is chosen for the number $$$i$$$ $$$(1 \leq i \leq n)$$$. The position for the number $$$i$$$ is defined as follows:  For all $$$j$$$ from $$$1$$$ to $$$n$$$, we calculate $$$r_j$$$  — the minimum index such that $$$j \leq r_j \leq n$$$, and the position $$$r_j$$$ is not yet occupied in the permutation. If there are no such positions, then we assume that the value of $$$r_j$$$ is not defined.  For all $$$t$$$ from $$$1$$$ to $$$n$$$, we calculate $$$count_t$$$  — the number of positions $$$1 \leq j \leq n$$$ such that $$$r_j$$$ is defined and $$$r_j = t$$$.  Consider the positions that are still not occupied by permutation and among those we consider the positions for which the value in the $$$count$$$ array is maximum.  The generator selects one of these positions for the number $$$i$$$. The generator can choose any position. Let's have a look at the operation of the algorithm in the following example:  Let $$$n = 5$$$ and the algorithm has already arranged the numbers $$$1, 2, 3$$$ in the permutation. Consider how the generator will choose a position for the number $$$4$$$:  The values of $$$r$$$ will be $$$r = [3, 3, 3, 4, \times]$$$, where $$$\times$$$ means an indefinite value.  Then the $$$count$$$ values will be $$$count = [0, 0, 3, 1, 0]$$$.  There are only two unoccupied positions in the permutation: $$$3$$$ and $$$4$$$. The value in the $$$count$$$ array for position $$$3$$$ is $$$3$$$, for position $$$4$$$ it is $$$1$$$.  The maximum value is reached only for position $$$3$$$, so the algorithm will uniquely select this position for number $$$4$$$. Satisfied with his purchase, Denis went home. For several days without a break, he generated permutations. He believes that he can come up with random permutations no worse than a generator. After that, he wrote out the first permutation that came to mind $$$p_1, p_2, \ldots, p_n$$$ and decided to find out if it could be obtained as a result of the generator.Unfortunately, this task was too difficult for him, and he asked you for help. It is necessary to define whether the written permutation could be obtained using the described algorithm if the generator always selects the position Denis needs.

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

  do {
    long long int n;
    scanf("%lld", &n);

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

    long long int sol = 0;
    for (i = 0; i < n - 1; ++i) {
      if (a[i] + 1 < a[i + 1]) {
        sol = 1;
      }
    }

    if (sol == 0) {
      printf("Yes\n");
    } else {
      printf("No\n");
    }

    --t;
  } while (t != 0);
}

fn solution() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let t: usize = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..t {
        let n: usize = lines.next().unwrap().unwrap().parse().unwrap();
        let mut xs: Vec<(usize, usize)> = lines
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .map(|x| x.parse().unwrap())
            .enumerate()
            .collect();
        xs.sort_by(|a, b| a.1.cmp(&b.1));
        let mut lo = xs[0].0;
        let mut hi = n;
        let mut beg = 0;
        let mut ok = true;
        for i in 0..n {
            if i >= beg + hi - lo {
                hi = lo;
                lo = xs[i].0;
                beg = i;
            }
            if xs[i].0 != lo + i - beg {
                ok = false;
                break;
            }
        }
        println!("{}", if ok { "YES" } else { "NO" });
    }
}


You have a sequence $$$a_1, a_2, \ldots, a_n$$$ of length $$$n$$$, consisting of integers between $$$1$$$ and $$$m$$$. You also have a string $$$s$$$, consisting of $$$m$$$ characters B.You are going to perform the following $$$n$$$ operations.   At the $$$i$$$-th ($$$1 \le i \le n$$$) operation, you replace either the $$$a_i$$$-th or the $$$(m + 1 - a_i)$$$-th character of $$$s$$$ with A. You can replace the character at any position multiple times through the operations. Find the lexicographically smallest string you can get after these operations.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ of the same length if and only if in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

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

  while (--t >= 0) {
    int n = 0;
    int m = 0;
    scanf("%d", &n);
    scanf("%d", &m);

    char *carr = (char *)malloc(sizeof(char) * (m + 1));

    for (int i = 0; i < m; ++i) {
      carr[i] = 'B';
    }
    carr[m] = '\0';

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

      int rpos = 0;
      int lpos = 0;

      if (m + 1 < pos + pos) {
        lpos = m - pos;
        rpos = pos - 1;
      } else {
        lpos = pos - 1;
        rpos = m - pos;
      }

      if (carr[lpos] == 'A') {
        carr[rpos] = 'A';
      } else {
        carr[lpos] = 'A';
      }
    }

    printf("%s\n", carr);

    free(carr);
  }
}

fn solution() {
    let n = std::io::stdin()
        .lock()
        .lines()
        .next()
        .unwrap()
        .unwrap()
        .parse::<i32>()
        .unwrap();
    for _ in 0..n {
        let mut k = String::new();
        let mut l = String::new();
        std::io::stdin().read_line(&mut k);
        std::io::stdin().read_line(&mut l);
        let k = k
            .trim()
            .split(" ")
            .flat_map(str::parse::<i32>)
            .collect::<Vec<_>>();
        let l = l
            .trim()
            .split(" ")
            .flat_map(str::parse::<i32>)
            .collect::<Vec<_>>();
        let mut poss = Vec::new();
        for jm in l.iter() {
            if *jm > k[1] + 1 - jm {
                poss.push(k[1] + 1 - jm);
                poss.push(*jm);
                continue;
            }
            poss.push(*jm);
            poss.push(k[1] + 1 - jm);
        }

        let _cnt = 0;
        let mut cnp = Vec::new();
        for (p1, p2) in poss.iter().enumerate() {
            if p1 % 2 != 0 {
                continue;
            }
            if cnp.contains(p2) && cnp.contains(&poss[p1 + 1]) {
                continue;
            }
            if cnp.contains(p2) {
                cnp.push(poss[p1 + 1]);
                continue;
            } else {
                cnp.push(*p2);
                continue;
            }
        }
        cnp.sort();
        for jk in 0..k[1] {
            if cnp.contains(&(jk + 1)) {
                print!("A");
            } else {
                print!("B")
            }
        }
        println!();
    }
}


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

fn solution() {
    use std::io;
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
    let friends: Vec<u32> = buf
        .split_whitespace()
        .map(|str| str.trim().parse().unwrap())
        .collect();
    let mut gave = vec![0; friends.len()];
    for (i, gave_to) in friends.into_iter().enumerate() {
        let gave_to = gave_to as usize;
        gave[gave_to - 1] = i;
    }
    for (i, from) in gave.into_iter().enumerate() {
        if i != 0 {
            print!(" ");
        }
        print!("{}", from + 1);
    }
    println!();
}


You are given two integer arrays $$$a$$$ and $$$b$$$ of length $$$n$$$.You can reverse at most one subarray (continuous subsegment) of the array $$$a$$$. Your task is to reverse such a subarray that the sum $$$\sum\limits_{i=1}^n a_i \cdot b_i$$$ is maximized.

int solution() {
  long long int n;
  long long int i;
  long long int a[5003];
  long long int b[5003];
  long long int d;
  long long int j;
  long long int mult1[5005];
  long long int mult2[5005];
  long long int sum1;
  long long int sum2;
  long long int sum;
  long long int x;
  long long int y;
  scanf("%lld", &n);
  for (i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
  }
  for (i = 0; i < n; i++) {
    scanf("%lld", &b[i]);
  }
  sum1 = 0;
  sum2 = 0;
  for (j = 0; j < n; j++) {
    sum1 = sum1 + a[j] * b[j];
    mult1[j] = sum1;
    sum2 = sum2 + a[n - 1 - j] * b[n - 1 - j];
    mult2[j] = sum2;
  }
  d = 0;
  for (i = 0; i < n; i++) {
    x = i;
    y = i;
    sum = 0;
    while (x >= 0 && y < n) {
      if (x == y) {
        sum = sum + a[x] * b[x];
      } else {
        sum = sum + a[x] * b[y] + a[y] * b[x];
      }
      x--;
      y++;
      sum1 = 0;
      if (x >= 0) {
        sum1 = sum1 + mult1[x];
      }
      if (y < n) {
        sum1 = sum1 + mult2[n - y - 1];
      }
      if (d < (sum + sum1)) {
        d = sum + sum1;
      }
    }
  }
  for (i = 0; i < n - 1; i++) {
    x = i;
    y = i + 1;
    sum = 0;
    while (x >= 0 && y < n) {
      sum = sum + a[x] * b[y] + a[y] * b[x];
      x--;
      y++;
      sum1 = 0;
      if (x >= 0) {
        sum1 = sum1 + mult1[x];
      }
      if (y < n) {
        sum1 = sum1 + mult2[n - y - 1];
      }
      if (d < (sum + sum1)) {
        d = sum + sum1;
      }
    }
  }
  printf("%lld\n", d);
  return 0;
}

fn solution() {
    let mut str = String::new();
    let _ = stdin().read_line(&mut str).unwrap();
    let n: usize = str.trim().parse().unwrap();
    let mut A: Vec<i64> = vec![0; n + 1];
    let mut B: Vec<i64> = vec![0; n + 1];
    let mut A_dot_B: Vec<Vec<i64>> = vec![Vec::new(); n];
    let mut A_not_B: Vec<i64> = vec![0; n];
    let mut a_str = String::new();
    let mut b_str = String::new();
    let _ = stdin().read_line(&mut a_str).unwrap();
    let _ = stdin().read_line(&mut b_str).unwrap();
    let mut a_iter = a_str.split_whitespace();
    let mut b_iter = b_str.split_whitespace();
    for i in 0..n {
        let a: i64 = a_iter.next().unwrap().parse().unwrap();
        let b: i64 = b_iter.next().unwrap().parse().unwrap();
        A[i] = a;
        B[i] = b;
        A_not_B[i] = a * b;
    }
    for i in 2..n + 1 {
        A_not_B[n - i] += A_not_B[n - i + 1];
    }

    A_dot_B[0].push(A[0] * B[0]);
    let mut max_sum = 0;
    for i in 1..n {
        for j in 0..i + 1 {
            let new_dot = if i == j {
                A_dot_B[i - 1][i - 1] + B[i] * A[i]
            } else if j + 1 < i {
                A_dot_B[i - 1][j + 1] - B[j] * A[j] + B[j] * A[i] + B[i] * A[j]
            } else {
                A_dot_B[i - 1][j] - B[j] * A[j] + B[j] * A[i] + B[i] * A[j]
            };
            if i < n - 1 && max_sum < new_dot + A_not_B[i + 1] {
                max_sum = new_dot + A_not_B[i + 1];
            }
            A_dot_B[i].push(new_dot);
        }
    }
    for i in 0..n {
        if A_dot_B[n - 1][i] > max_sum {
            max_sum = A_dot_B[n - 1][i];
        }
    }
    println!("{}", max_sum);
}


You are given a string $$$s$$$ of length $$$n$$$ consisting of characters a and/or b.Let $$$\operatorname{AB}(s)$$$ be the number of occurrences of string ab in $$$s$$$ as a substring. Analogically, $$$\operatorname{BA}(s)$$$ is the number of occurrences of ba in $$$s$$$ as a substring.In one step, you can choose any index $$$i$$$ and replace $$$s_i$$$ with character a or b.What is the minimum number of steps you need to make to achieve $$$\operatorname{AB}(s) = \operatorname{BA}(s)$$$?Reminder:The number of occurrences of string $$$d$$$ in $$$s$$$ as substring is the number of indices $$$i$$$ ($$$1 \le i \le |s| - |d| + 1$$$) such that substring $$$s_i s_{i + 1} \dots s_{i + |d| - 1}$$$ is equal to $$$d$$$. For example, $$$\operatorname{AB}($$$aabbbabaa$$$) = 2$$$ since there are two indices $$$i$$$: $$$i = 2$$$ where aabbbabaa and $$$i = 6$$$ where aabbbabaa.

fn solution() {
    let stdin = io::stdin();
    let mut n = String::new();

    stdin.read_line(&mut n).unwrap();
    let n = n.trim().parse::<i32>().unwrap();

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

        let ab = s.matches("ab").count();
        let ba = s.matches("ba").count();

        if ab > ba {
            let pos = s.rfind("b").unwrap();
            s.replace_range(pos..pos + 1, "a");
        } else if ab < ba {
            let pos = s.rfind("a").unwrap();
            s.replace_range(pos..pos + 1, "b");
        }

        println!("{s}");
    }
}


You are given two integers $$$n$$$ and $$$m$$$. Calculate the number of pairs of arrays $$$(a, b)$$$ such that:  the length of both arrays is equal to $$$m$$$;  each element of each array is an integer between $$$1$$$ and $$$n$$$ (inclusive);  $$$a_i \le b_i$$$ for any index $$$i$$$ from $$$1$$$ to $$$m$$$;  array $$$a$$$ is sorted in non-descending order;  array $$$b$$$ is sorted in non-ascending order. As the result can be very large, you should print it modulo $$$10^9+7$$$.

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

    let arr = buffer
        .split_whitespace()
        .map(|x| x.parse::<usize>().expect("convert to number"))
        .collect::<Vec<_>>();

    let n = arr[0];
    let m = arr[1];

    const M: u64 = 1_000_000_000 + 7;

    let mut a = vec![1u64; n];
    let mut b = vec![1u64; n];

    for _ in 1..m {
        for j in 0..n {
            a[j] = (a[j] + if j > 0 { a[j - 1] } else { 0 }) % M;
        }
    }

    for _ in 1..m {
        for j in (0..n).rev() {
            b[j] = (b[j] + if j < n - 1 { b[j + 1] } else { 0 }) % M;
        }
    }

    let mut ans = 0;
    let mut accum = 0;
    for i in (0..n).rev() {
        accum = (accum + b[i]) % M;
        ans = (((a[i] * accum) % M) + ans) % M;
    }

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


Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:   $$$f(0) = a$$$;  $$$f(1) = b$$$;  $$$f(n) = f(n-1) \oplus f(n-2)$$$ when $$$n > 1$$$, where $$$\oplus$$$ denotes the bitwise XOR operation. You are given three integers $$$a$$$, $$$b$$$, and $$$n$$$, calculate $$$f(n)$$$.You have to answer for $$$T$$$ independent test cases.

int solution() {
  int qtos;
  int a;
  int b;
  int n;
  scanf("%d", &qtos);
  if (qtos >= 1 && qtos <= 1000) {
    for (int i = 0; i < qtos; i++) {
      scanf("%d %d %d", &a, &b, &n);
      if (a >= 0 && b >= 0 && n >= 0) {
        if (n % 3 == 0) {
          printf("%d\n", a);
        } else if (n % 3 == 1) {
          printf("%d\n", b);
        } else {
          printf("%d\n", a ^ b);
        }
      }
    }
  }
  return 0;
}

fn solution() {
    let mut t = String::new();
    io::stdin()
        .read_line(&mut t)
        .expect("failed to read from stdin");
    let t: u32 = t.trim().parse().expect("expect a number");
    for _ in 0..t {
        let mut line = String::new();
        io::stdin()
            .read_line(&mut line)
            .expect("failed to read from stdin");
        let mut iter = line.split_whitespace();
        let a: u32 = iter
            .next()
            .expect("expect a number")
            .trim()
            .parse()
            .unwrap();
        let b: u32 = iter
            .next()
            .expect("expect a number")
            .trim()
            .parse()
            .unwrap();
        let n: u32 = iter
            .next()
            .expect("expect a number")
            .trim()
            .parse()
            .unwrap();
        let c: u32 = a ^ b;
        let res = match n % 3 {
            0 => a,
            1 => b,
            2 => c,
            _ => unreachable!(),
        };
        println!("{}", res);
    }
}


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

int solution() {
  char save[6][20] = {"Power", "Time", "Space", "Soul", "Reality", "Mind"};
  char s[20];
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%s", s);
    if (*s == 'p') {
      memset(save[0], 0, sizeof(save[0]));
    }
    if (*s == 'g') {
      memset(save[1], 0, sizeof(save[0]));
    }
    if (*s == 'b') {
      memset(save[2], 0, sizeof(save[0]));
    }
    if (*s == 'o') {
      memset(save[3], 0, sizeof(save[0]));
    }
    if (*s == 'r') {
      memset(save[4], 0, sizeof(save[0]));
    }
    if (*s == 'y') {
      memset(save[5], 0, sizeof(save[0]));
    }
  }
  printf("%d\n", 6 - n);
  for (int i = 0; i < 6; i++) {
    if (*save[i] == 0) {
      continue;
    }
    printf("%s\n", save[i]);
  }
}

fn solution() {
    let mut visited = HashMap::new();
    visited.insert("purple", ("Power", false));
    visited.insert("green", ("Time", false));
    visited.insert("blue", ("Space", false));
    visited.insert("orange", ("Soul", false));
    visited.insert("red", ("Reality", false));
    visited.insert("yellow", ("Mind", false));

    let mut mut_line = String::new();
    io::stdin().read_line(&mut mut_line).unwrap();
    let n: u8 = mut_line.trim().parse().unwrap();

    println!("{}", 6 - n);
    for _ in 0..n {
        mut_line = String::new();
        io::stdin().read_line(&mut mut_line).unwrap();
        if let Some(tuple) = visited.get_mut(mut_line.trim()) {
            tuple.1 = true;
        }
    }

    for (_color, (name, v)) in visited {
        if !v {
            println!("{}", name);
        }
    }
}


Score : <var>100</var> points

Problem Statement

We have <var>A</var> apples and <var>P</var> pieces of apple.

We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.

Find the maximum number of apple pies we can make with what we have now.

Constraints

All values in input are integers.

<var>0 \leq A, P \leq 100</var>

Input

Input is given from Standard Input in the following format:

<var>A</var> <var>P</var>

Output

Print the maximum number of apple pies we can make with what we have.

Sample Input 1

1 3

Sample Output 1

3

We can first make one apple pie by simmering two of the three pieces of apple. Then, we can make two more by simmering the remaining piece and three more pieces obtained by cutting the whole apple.

Sample Input 2

0 1

Sample Output 2

0

We cannot make an apple pie in this case, unfortunately.

Sample Input 3

32 21

Sample Output 3

58

int solution(void) {
  int a = 0;
  int p = 0;
  int ans = 0;

  scanf("%d%d", &a, &p);

  ans = (a * 3 + p) / 2;

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

fn solution() {
    let mut ap = String::new();
    stdin().read_line(&mut ap).unwrap();
    let a: usize = ap.split_whitespace().collect::<Vec<&str>>()[0]
        .parse()
        .unwrap();
    let p: usize = ap.split_whitespace().collect::<Vec<&str>>()[1]
        .parse()
        .unwrap();
    let k = a * 3 + p;
    println!("{}", k / 2);
}


Let's say string $$$s$$$ has period $$$k$$$ if $$$s_i = s_{i + k}$$$ for all $$$i$$$ from $$$1$$$ to $$$|s| - k$$$ ($$$|s|$$$ means length of string $$$s$$$) and $$$k$$$ is the minimum positive integer with this property.Some examples of a period: for $$$s$$$="0101" the period is $$$k=2$$$, for $$$s$$$="0000" the period is $$$k=1$$$, for $$$s$$$="010" the period is $$$k=2$$$, for $$$s$$$="0011" the period is $$$k=4$$$.You are given string $$$t$$$ consisting only of 0's and 1's and you need to find such string $$$s$$$ that:  String $$$s$$$ consists only of 0's and 1's;  The length of $$$s$$$ doesn't exceed $$$2 \cdot |t|$$$;  String $$$t$$$ is a subsequence of string $$$s$$$;  String $$$s$$$ has smallest possible period among all strings that meet conditions 1—3. Let us recall that $$$t$$$ is a subsequence of $$$s$$$ if $$$t$$$ can be derived from $$$s$$$ by deleting zero or more elements (any) without changing the order of the remaining elements. For example, $$$t$$$="011" is a subsequence of $$$s$$$="10101".

int solution() {
  int t;
  scanf("%d", &t);
  while (t--) {
    char ch[100];
    scanf("%s", ch);
    int l = strlen(ch);
    int cnt1 = 0;
    int cnt0 = 0;
    int k = l;
    while (l) {
      l--;

      if (ch[l] == '1') {
        cnt1++;
      } else {
        cnt0++;
      }
    }

    if (cnt1 == 0 || cnt0 == 0) {
      printf("%s", ch);
    } else {
      for (int i = 0; i < k; i++) {
        printf("10");
      }
    }
    printf("\n");
  }
}

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 ones = str
            .trim()
            .chars()
            .fold(0, |x, c| if c == '1' { x + 1 } else { x });
        if ones == str.trim().len() || ones == 0 {
            println!("{}", str);
        } else {
            println!("{}", "01".repeat(str.trim().len()));
        }
    }
}


Score : <var>300</var> points

Problem Statement

Iroha is very particular about numbers. There are <var>K</var> digits that she dislikes: <var>D_1, D_2, ..., D_K</var>.

She is shopping, and now paying at the cashier.
Her total is <var>N</var> yen (the currency of Japan), thus she has to hand at least <var>N</var> yen to the cashier (and possibly receive the change).

However, as mentioned before, she is very particular about numbers. When she hands money to the cashier, the decimal notation of the amount must not contain any digits that she dislikes. Under this condition, she will hand the minimum amount of money.

Find the amount of money that she will hand to the cashier.

Constraints

<var> 1 ≦ N < 10000</var>

<var> 1 ≦ K < 10</var>

<var> 0 ≦ D_1 < D_2 < … < D_K≦9</var>

<var>\{D_1,D_2,...,D_K\} ≠ \{1,2,3,4,5,6,7,8,9\}</var>

Input

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

<var>N</var> <var>K</var>
<var>D_1</var> <var>D_2</var> … <var>D_K</var>

Output

Print the amount of money that Iroha will hand to the cashier.

Sample Input 1

1000 8
1 3 4 5 6 7 8 9

Sample Output 1

2000

She dislikes all digits except <var>0</var> and <var>2</var>.

The smallest integer equal to or greater than <var>N=1000</var> whose decimal notation contains only <var>0</var> and <var>2</var>, is <var>2000</var>.

Sample Input 2

9999 1
0

Sample Output 2

9999

fn solution() {
    input! {
        n: usize,
        k: usize,
        v: [usize; k]
    }
    let mut l = [false; 10];
    for i in 0..k {
        l[v[i]] = true;
    }
    'outer: for i in n..n * 10 {
        let mut m = i;
        while m > 0 {
            if l[m % 10] {
                continue 'outer;
            }
            m /= 10;
        }
        println!("{}", i);
        return;
    }
}


Score : <var>200</var> points

Problem Statement

We have a permutation <var>p</var> = {<var>p_1,\ p_2,\ ...,\ p_n</var>} of {<var>1,\ 2,\ ...,\ n</var>}.

Print the number of elements <var>p_i</var> (<var>1 < i < n</var>) that satisfy the following condition:

<var>p_i</var> is the second smallest number among the three numbers <var>p_{i - 1}</var>, <var>p_i</var>, and <var>p_{i + 1}</var>.

Constraints

All values in input are integers.

<var>3 \leq n \leq 20</var>

<var>p</var> is a permutation of {<var>1,\ 2,\ ...,\ n</var>}.

Input

Input is given from Standard Input in the following format:

<var>n</var>
<var>p_1</var> <var>p_2</var> <var>...</var> <var>p_n</var>

Output

Print the number of elements <var>p_i</var> (<var>1 < i < n</var>) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

<var>p_2 = 3</var> is the second smallest number among <var>p_1 = 1</var>, <var>p_2 = 3</var>, and <var>p_3 = 5</var>. Also, <var>p_4 = 4</var> is the second smallest number among <var>p_3 = 5</var>, <var>p_4 = 4</var>, and <var>p_5 = 2</var>. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5

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

    std::io::stdin().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();

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

    let items: Vec<i32> = (0..n)
        .map(|_| iter.next().unwrap().parse().unwrap())
        .collect();

    let zero = 0;
    let ordinality: Vec<i32> = (2..n)
        .map(|i| (items[i - 2] - items[i - 1]) * (items[i] - items[i - 1]))
        .filter(|v| v.lt(&zero))
        .collect();

    println!("{}", ordinality.len());
}