Score : <var>400</var> points

Problem Statement

You have <var>N</var> items and a bag of strength <var>W</var>.
The <var>i</var>-th item has a weight of <var>w_i</var> and a value of <var>v_i</var>.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most <var>W</var>.

Your objective is to maximize the total value of the selected items.

Constraints

<var>1 ≤ N ≤ 100</var>

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

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

For each <var>i = 2,3,...,N</var>, <var>w_1 ≤ w_i ≤ w_1 + 3</var>.

<var>1 ≤ v_i ≤ 10^7</var>

<var>W</var>, each <var>w_i</var> and <var>v_i</var> are integers.

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>W</var>
<var>w_1</var> <var>v_1</var>
<var>w_2</var> <var>v_2</var>
:
<var>w_N</var> <var>v_N</var>

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.


There are $$$n$$$ block towers in a row, where tower $$$i$$$ has a height of $$$a_i$$$. You're part of a building crew, and you want to make the buildings look as nice as possible. In a single day, you can perform the following operation:  Choose two indices $$$i$$$ and $$$j$$$ ($$$1 \leq i, j \leq n$$$; $$$i \neq j$$$), and move a block from tower $$$i$$$ to tower $$$j$$$. This essentially decreases $$$a_i$$$ by $$$1$$$ and increases $$$a_j$$$ by $$$1$$$. You think the ugliness of the buildings is the height difference between the tallest and shortest buildings. Formally, the ugliness is defined as $$$\max(a)-\min(a)$$$. What's the minimum possible ugliness you can achieve, after any number of days?

int solution() {
  int n;
  int x = 0;
  scanf("%d", &n);
  int arr_1[n];
  int result[n];
  for (int i = 0; i < n; i++) {
    scanf("%d", &arr_1[i]);
    int arr_2[arr_1[i]];
    for (int j = 0; j < arr_1[i]; j++) {
      scanf("%d", &arr_2[j]);
      x = x + arr_2[j];
    }
    if (x % arr_1[i] == 0) {
      result[i] = 0;
    } else {
      result[i] = 1;
    }
    x = 0;
  }
  for (int i = 0; i < n; i++) {
    printf("%d\n", result[i]);
  }

  return 0;
}

fn solution() {
    let stdin = stdin();
    let mut lines = stdin.lock().lines();
    let cases: u32 = lines.next().unwrap().unwrap().parse().unwrap();
    for _ in 0..cases {
        let buildings_count: u32 = lines.next().unwrap().unwrap().parse().unwrap();
        let buildings_line = lines.next().unwrap().unwrap();
        let buildings_line_split = buildings_line.split_ascii_whitespace();
        let mut block_sum: u32 = 0;
        for x in buildings_line_split {
            block_sum += x.parse::<u32>().unwrap();
        }
        println!(
            "{}",
            if block_sum.is_multiple_of(buildings_count) {
                0
            } else {
                1
            }
        );
    }
}


Score : <var>200</var> points

Problem Statement

Takahashi and Aoki will have a battle using their monsters.

The health and strength of Takahashi's monster are <var>A</var> and <var>B</var>, respectively, and those of Aoki's monster are <var>C</var> and <var>D</var>, respectively.

The two monsters will take turns attacking, in the order Takahashi's, Aoki's, Takahashi's, Aoki's, ...
Here, an attack decreases the opponent's health by the value equal to the attacker's strength.
The monsters keep attacking until the health of one monster becomes <var>0</var> or below. The person with the monster whose health becomes <var>0</var> or below loses, and the other person wins.

If Takahashi will win, print Yes; if he will lose, print No.

Constraints

<var>1 \leq A,B,C,D \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>C</var> <var>D</var>

Output

If Takahashi will win, print Yes; if he will lose, print No.

Sample Input 1

10 9 10 10

Sample Output 1

No

First, Takahashi's monster attacks Aoki's monster, whose health is now <var>10-9=1</var>.

Next, Aoki's monster attacks Takahashi's monster, whose health is now <var>10-10=0</var>.

Takahashi's monster is the first to have <var>0</var> or less health, so Takahashi loses.

Sample Input 2

46 4 40 5

Sample Output 2

Yes

int solution() {
  int A = 0;
  int B = 0;
  int C = 0;
  int D = 0;
  scanf("%d %d %d %d", &A, &B, &C, &D);
  while (1) {
    C = C - B;
    if (C <= 0) {
      printf("Yes\n");
      break;
    }
    A = A - D;
    if (A <= 0) {
      printf("No\n");
      break;
    }
  }
  return 0;
}

fn solution() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let s: Vec<i32> = s
        .trim()
        .split(' ')
        .map(|x| x.parse::<i32>().unwrap())
        .collect();
    let (a, b, c, d) = (s[0], s[1], s[2], s[3]);

    let tk = (c + (b - 1)) / b;
    let ao = (a + (d - 1)) / d;

    if tk <= ao {
        println!("Yes");
    } else {
        println!("No");
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> integers written on a blackboard. The <var>i</var>-th integer is <var>A_i</var>.

Takahashi will repeatedly perform the following operation on these numbers:

Select a pair of integers, <var>A_i</var> and <var>A_j</var>, that have the same parity (that is, both are even or both are odd) and erase them.

Then, write a new integer on the blackboard that is equal to the sum of those integers, <var>A_i+A_j</var>.

Determine whether it is possible to have only one integer on the blackboard.

Constraints

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

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

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

Input

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

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

Output

If it is possible to have only one integer on the blackboard, print YES. Otherwise, print NO.

Sample Input 1

3
1 2 3

Sample Output 1

YES

It is possible to have only one integer on the blackboard, as follows:

Erase <var>1</var> and <var>3</var> from the blackboard, then write <var>4</var>. Now, there are two integers on the blackboard: <var>2</var> and <var>4</var>.

Erase <var>2</var> and <var>4</var> from the blackboard, then write <var>6</var>. Now, there is only one integer on the blackboard: <var>6</var>.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

NO

int solution() {
  int N = 0;
  int count = 0;
  scanf("%d", &N);
  int a[N];
  for (int i = 0; i < N; i++) {
    scanf("%d", &a[i]);
  }
  for (int i = 0; i < N; i++) {
    count += a[i] % 2;
  }
  if (count % 2 == 0) {
    printf("YES");
  } else {
    printf("NO");
  }
  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");
    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");
    let mut vec: Vec<&str> = line.split_whitespace().collect();
    let n: u64 = vec.swap_remove(0).parse().expect("Failed to parse");
    let mut odd_cnt = 0;
    let mut i = 0;
    for s in vec {
        let n2: u64 = s.parse().expect("Failed to parse");
        if !n2.is_multiple_of(2) {
            odd_cnt += 1;
        }
        i += 1;
        if n <= i {
            break;
        }
    }
    println!("{}", if odd_cnt % 2 == 0 { "YES" } else { "NO" });
}


In a small restaurant there are a tables for one person and b tables for two persons. It it known that n groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater table. If there are none of them, it is seated at a two-seater table occupied by single person. If there are still none of them, the restaurant denies service to this group.If a group consist of two people, it is seated at a vacant two-seater table. If there are none of them, the restaurant denies service to this group.You are given a chronological order of groups coming. You are to determine the total number of people the restaurant denies service to.

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

    let t = {
        let mut input = String::new();
        stdin().read_line(&mut input).unwrap();
        input
            .split_whitespace()
            .map(|k| k.parse::<u8>().unwrap())
            .collect::<Vec<_>>()
    };

    let mut a = a;
    let mut b = b;
    let mut c = 0usize;

    let mut ans = 0usize;

    for t in t {
        if t == 1 {
            if a > 0 {
                a -= 1;
            } else if b > 0 {
                b -= 1;
                c += 1;
            } else if c > 0 {
                c -= 1;
            } else {
                ans += 1;
            }
        } else if t == 2 {
            if b > 0 {
                b -= 1;
            } else {
                ans += 2;
            }
        }
    }

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


Score : <var>200</var> points

Problem Statement

There are <var>N</var> cities and <var>M</var> roads.
The <var>i</var>-th road <var>(1≤i≤M)</var> connects two cities <var>a_i</var> and <var>b_i</var> <var>(1≤a_i,b_i≤N)</var> bidirectionally.
There may be more than one road that connects the same pair of two cities.
For each city, how many roads are connected to the city?

Constraints

<var>2≤N,M≤50</var>

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

<var>a_i ≠ b_i</var>

All input values are integers.

Input

Input is given from Standard Input in the following format:

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

Output

Print the answer in <var>N</var> lines.
In the <var>i</var>-th line <var>(1≤i≤N)</var>, print the number of roads connected to city <var>i</var>.

Sample Input 1

4 3
1 2
2 3
1 4

Sample Output 1

2
2
1
1

City <var>1</var> is connected to the <var>1</var>-st and <var>3</var>-rd roads.

City <var>2</var> is connected to the <var>1</var>-st and <var>2</var>-nd roads.

City <var>3</var> is connected to the <var>2</var>-nd road.

City <var>4</var> is connected to the <var>3</var>-rd road.

Sample Input 2

2 5
1 2
2 1
1 2
2 1
1 2

Sample Output 2

5
5

Sample Input 3

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

Sample Output 3

3
3
2
2
2
1
1
2

int solution(void) {
  int N;
  int M;
  scanf("%d", &N);
  scanf("%d", &M);
  int city[2 * M];
  int ans[N];

  for (int i = 0; i < N; i++) {
    ans[i] = 0;
  }

  for (int i = 0; i < 2 * M; i++) {
    scanf("%d", &city[i]);
  }

  for (int i = 0; i < 2 * M; i++) {
    ans[city[i] - 1]++;
  }
  for (int i = 0; i < N; i++) {
    printf("%d\n", ans[i]);
  }
  return 0;
}

fn solution() {
    let (n, m) = {
        let mut b = String::new();
        std::io::stdin().read_line(&mut b).unwrap();
        let vec = b
            .split_whitespace()
            .map(|i| i.parse().unwrap())
            .collect::<Vec<i32>>();
        (vec[0], vec[1])
    };
    let mut h = std::collections::HashMap::new();
    for i in 0..n {
        h.insert(i + 1, Vec::new());
    }
    for _ in 0..m {
        let (a, b): (i32, i32) = {
            let mut b = String::new();
            std::io::stdin().read_line(&mut b).unwrap();
            let vec = b
                .split_whitespace()
                .map(|i| i.parse().unwrap())
                .collect::<Vec<i32>>();
            (std::cmp::min(vec[0], vec[1]), std::cmp::max(vec[0], vec[1]))
        };
        h.get_mut(&a).unwrap().push(b);
        h.get_mut(&b).unwrap().push(a);
    }
    for i in 0..n {
        println!("{}", h[&(i + 1)].len());
    }
}


Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types:  Replace $$$i$$$-th element in the array with integer $$$x$$$.  Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.

int solution() {
  long long m;
  long long n;
  long long flag;
  long long k;
  long long x;
  long long sum = 0;
  long long isFill = 0;
  long long last = 0;
  long long term = 0;
  scanf("%lld %lld", &m, &n);
  long long a[m];
  long long num[m];
  for (int i = 0; i < m; i++) {
    scanf("%lld", &a[i]);
    sum += a[i];
    num[i] = 0;
  }
  for (int i = 0; i < n; i++) {
    scanf("%lld", &flag);
    if (flag == 1) {
      scanf("%lld %lld", &k, &x);
      if (isFill) {
        if (num[k - 1] != term) {
          num[k - 1] = term;
          sum = sum - last + x;
          a[k - 1] = x;
          printf("%lld", sum);
        } else {
          sum = sum - a[k - 1] + x;
          printf("%lld", sum);
          a[k - 1] = x;
        }
      } else {
        sum = sum - a[k - 1] + x;
        printf("%lld", sum);
        a[k - 1] = x;
      }
    } else if (flag == 2) {
      scanf("%lld", &x);
      sum = m * x;
      printf("%lld", sum);
      last = x;
      term++;
      isFill = 1;
    }
    if (i != n - 1) {
      printf("\n");
    }
  }
}

fn solution() {
    let mut sin = String::new();
    io::stdin().read_line(&mut sin).unwrap();
    let mut iter = sin.split_whitespace();
    let n = iter.next().unwrap().trim().parse::<i32>().unwrap();
    let q = iter.next().unwrap().trim().parse::<i32>().unwrap();

    sin.clear();
    io::stdin().read_line(&mut sin).unwrap();
    let mut a: Vec<i64> = sin
        .split_whitespace()
        .map(|x| x.trim().parse::<i64>().unwrap())
        .collect();
    let mut last_update_time = vec![0; n as usize];
    let mut last_refresh_time = 0;
    let mut last_refresh_value: i64 = 0;
    let mut sum: i64 = a.iter().sum();

    for t in 1..(q + 1) {
        sin.clear();
        io::stdin().read_line(&mut sin).unwrap();
        iter = sin.split_whitespace();
        let x = iter.next().unwrap().trim().parse::<i32>().unwrap();

        if x == 1 {
            let index = iter.next().unwrap().trim().parse::<usize>().unwrap() - 1;
            let y = iter.next().unwrap().trim().parse::<i64>().unwrap();

            let mut current_value = a[index];
            if last_update_time[index] < last_refresh_time {
                current_value = last_refresh_value;
            }

            sum += y - current_value;

            a[index] = y;
            last_update_time[index] = t;
        } else {
            let value = iter.next().unwrap().trim().parse::<i64>().unwrap();
            last_refresh_time = t;
            last_refresh_value = value;
            sum = value * (n as i64);
        }

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


Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents — $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$ — the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.

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

    let mut it = input.split_whitespace();

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

    let x: Vec<usize> = it
        .by_ref()
        .take(n + m)
        .map(|x| x.parse().unwrap())
        .collect();
    let t: Vec<bool> = it.take(n + m).map(|x| x == "1").collect();

    let residents: Vec<_> = x
        .into_iter()
        .zip(t)
        .map(|(xi, ti)| {
            let kind = if ti { Driver } else { Rider };
            Resident { kind, address: xi }
        })
        .collect();

    let mut left = Vec::with_capacity(n);
    let mut current = None;
    for resident in residents.iter() {
        match resident.kind {
            Driver => current = Some(current.map(|x| x + 1).unwrap_or(0)),
            Rider => left.push(current),
        }
    }

    let mut right = Vec::with_capacity(n);
    current = None;
    for resident in residents.iter().rev() {
        match resident.kind {
            Driver => current = Some(current.map(|x| x - 1).unwrap_or(m - 1)),
            Rider => right.push(current),
        }
    }
    right.reverse();

    let mut rider_addresses = Vec::with_capacity(n);
    let mut driver_addresses = Vec::with_capacity(m);

    for resident in residents {
        match resident.kind {
            Rider => rider_addresses.push(resident.address),
            Driver => driver_addresses.push(resident.address),
        }
    }

    let closest: Vec<_> = rider_addresses
        .into_iter()
        .zip(left.into_iter().zip(right))
        .map(|(address, (a, b))| match (a, b) {
            (Some(left), Some(right))
                if driver_addresses[right] - address < address - driver_addresses[left] =>
            {
                right
            }
            (Some(left), _) => left,
            (None, Some(right)) => right,
            _ => panic!("!"),
        })
        .collect();

    let answer = closest
        .into_iter()
        .fold(vec![0; m], |mut answer, driver_id| {
            answer[driver_id] += 1;
            answer
        });

    let stdout = io::stdout();
    let mut lock = stdout.lock();

    for a in answer {
        write!(&mut lock, "{} ", a).unwrap();
    }
}


Score : <var>300</var> points

Problem Statement

<var>1000000000000001</var> dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered <var>1</var> through <var>1000000000000001</var>, but he gave them new names, as follows:

the dogs numbered <var>1,2,\cdots,26</var> were respectively given the names a, b, ..., z;

the dogs numbered <var>27,28,29,\cdots,701,702 </var> were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered <var>703,704,705,\cdots,18277,18278 </var> were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered <var>18279,18280,18281,\cdots,475253,475254 </var> were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered <var>475255,475256,\cdots </var> were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered <var>1, 2, \cdots</var> were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered <var>N</var>?"

Constraints

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja

int solution(void) {
  long int dogn = 0;
  char name[16] = {0};
  int i = 0;

  scanf("%ld", &dogn);
  dogn--;

  while (dogn > -1) {
    name[i] = dogn % 26 + 'a';
    dogn = dogn / 26;
    i++;
    dogn--;
  }

  while (i--) {
    printf("%c", name[i]);
  }
  printf("\n");

  return 0;
}

fn solution() {
    let mut is = String::new();
    stdin().read_line(&mut is).ok();
    let mut n: usize = is.trim().parse::<usize>().unwrap();
    let mut ans = String::new();
    let a = (b'a'..=b'z').map(|e| e as char).collect::<Vec<char>>();

    while n > 0 {
        n -= 1;
        let t = n % 26;
        n /= 26;

        ans.push(a[t]);
    }

    println!("{}", ans.chars().rev().collect::<String>());
}


Search I

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

n ≤ 10000

 q ≤ 500

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
3 1 2
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes

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

  scanf("%d", &m);
  int b[m];
  for (i = 0; i < m; i++) {
    scanf("%d", &b[i]);
    for (j = 0; j < n; j++) {
      if (a[j] == b[i]) {
        count++;
        break;
      }
    }
  }
  printf("%d\n", count);

  return 0;
}

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

    let N = buf_it.next().unwrap().parse::<usize>().unwrap();
    let A = (0..N)
        .map(|_| buf_it.next().unwrap().parse::<isize>().unwrap())
        .collect::<HashSet<_>>();

    let M = buf_it.next().unwrap().parse::<usize>().unwrap();
    let B = (0..M)
        .map(|_| buf_it.next().unwrap().parse::<isize>().unwrap())
        .collect::<HashSet<_>>();

    let ans = A.intersection(&B).collect::<HashSet<_>>().len();
    println!("{}", ans);
}


Score : <var>500</var> points

Problem Statement

There is an integer sequence <var>A</var> of length <var>N</var>.

Find the number of the pairs of integers <var>l</var> and <var>r</var> (<var>1 \leq l \leq r \leq N</var>) that satisfy the following condition:

<var>A_l\ xor\ A_{l+1}\ xor\ ...\ xor\ A_r = A_l\ +\ A_{l+1}\ +\ ...\ +\ A_r</var>

Here, <var>xor</var> denotes the bitwise exclusive OR.

Definition of XOR

The XOR of integers <var>c_1, c_2, ..., c_m</var> is defined as follows:

Let the XOR be <var>X</var>. In the binary representation of <var>X</var>, the digit in the <var>2^k</var>'s place (<var>0 \leq k</var>; <var>k</var> is an integer) is <var>1</var> if there are an odd number of integers among <var>c_1, c_2, ...c_m</var> whose binary representation has <var>1</var> in the <var>2^k</var>'s place, and <var>0</var> if that number is even.

For example, let us compute the XOR of <var>3</var> and <var>5</var>. The binary representation of <var>3</var> is <var>011</var>, and the binary representation of <var>5</var> is <var>101</var>, thus the XOR has the binary representation <var>110</var>, that is, the XOR is <var>6</var>.

int solution() {
  int n;
  scanf("%d", &n);
  long a[n];
  long sum = 0;
  long xor = 0;
  long ans = 0;
  int k = 0;
  int cnt = 0;
  for (int i = 0; i < n; i++) {
    scanf("%ld", a + i);
  }
  for (int i = 0; i < n; i++) {
    while (k < n && (sum + a[k] == (xor^a[k]))) {
      sum += a[k];
      xor += a[k];
      k++;
      cnt++;
    }
    ans += cnt;
    cnt--;
    sum -= a[i];
    xor -= a[i];
  }
  printf("%ld\n", ans);
  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 a: Vec<usize> = (0..n)
        .map(|_| itr.next().unwrap().parse().unwrap())
        .collect();

    let mut ans: usize = 0;
    let mut xor: usize = 0;
    let mut sum: usize = 0;
    let mut r: usize = 0;
    for l in 0..n {
        while r < n && xor ^ a[r] == sum + a[r] {
            xor ^= a[r];
            sum += a[r];
            r += 1;
        }
        ans += r - l;
        xor ^= a[l];
        sum -= a[l];
    }
    println!("{}", ans);
}


Your company was appointed to lay new asphalt on the highway of length $$$n$$$. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are $$$g$$$ days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next $$$b$$$ days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again $$$g$$$ good days, $$$b$$$ bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days $$$1, 2, \dots, g$$$ are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the $$$n = 5$$$ then at least $$$3$$$ units of the highway should have high quality; if $$$n = 4$$$ then at least $$$2$$$ units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?

int solution() {
  int t;
  scanf("%d", &t);
  long long n;
  long long g;
  long long b;
  long long m;
  long long a;
  long long r;
  long long s[t];
  long long d;
  long long f;
  for (int i = 0; i < t; i++) {
    scanf("%lld %lld %lld", &n, &g, &b);
    if (n % 2 == 0) {
      r = n / 2;
    } else {
      r = (n + 1) / 2;
    }
    if (r <= g) {
      s[i] = n;
    } else {
      m = r / g;
      if (r % g == 0) {
        {
          f = (m - 1) * b;
          a = r + f;
        }

      } else {
        f = m * b;
        a = r + f;
      }
      d = n - r;
      if (f >= d) {
        s[i] = a;
      } else {
        s[i] = a + (d - f);
      }
    }
  }
  for (int i = 0; i < t; i++) {
    printf("%lld\n", s[i]);
  }
  return 0;
}

fn solution() {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let t: u32 = line.trim().parse().unwrap();
    for _ in 0..t {
        let mut line = String::new();
        io::stdin().read_line(&mut line).unwrap();
        let mut pieces = line.split_whitespace();
        let n: u64 = pieces.next().unwrap().parse().unwrap();
        let g: u64 = pieces.next().unwrap().parse().unwrap();
        let b: u64 = pieces.next().unwrap().parse().unwrap();

        let min_good = n / 2 + (n % 2);
        let (mut cycles, mut rem_good) = (min_good / g, min_good % g);
        if cycles > 0 && rem_good == 0 {
            cycles -= 1;
            rem_good += g;
        }
        let days = max(n, cycles * (g + b) + rem_good);
        println!("{}", days);
    }
}


Score : <var>200</var> points

Problem Statement

We ask you to select some number of positive integers, and calculate the sum of them.

It is allowed to select as many integers as you like, and as large integers as you wish.
You have to follow these, however: each selected integer needs to be a multiple of <var>A</var>, and you need to select at least one integer.

Your objective is to make the sum congruent to <var>C</var> modulo <var>B</var>.
Determine whether this is possible.

If the objective is achievable, print YES. Otherwise, print NO.

Constraints

<var>1 ≤ A ≤ 100</var>

<var>1 ≤ B ≤ 100</var>

<var>0 ≤ C < B</var>

Input

Input is given from Standard Input in the following format:

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

Output

Print YES or NO.

Sample Input 1

7 5 1

Sample Output 1

YES

For example, if you select <var>7</var> and <var>14</var>, the sum <var>21</var> is congruent to <var>1</var> modulo <var>5</var>.

Sample Input 2

2 2 1

Sample Output 2

NO

The sum of even numbers, no matter how many, is never odd.

Sample Input 3

1 100 97

Sample Output 3

YES

You can select <var>97</var>, since you may select multiples of <var>1</var>, that is, all integers.

Sample Input 4

40 98 58

Sample Output 4

YES

Sample Input 5

77 42 36

Sample Output 5

NO

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

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

  for (i = 1; i <= b; i++) {

    if (c == ((a * i) % b)) {
      printf("YES");
      x = a % b;
      break;
    }
  }
  if (x == 0) {
    printf("NO");
  }

  return 0;
}

fn solution() {
    use std::io;
    let mut input = String::new();
    let _ = io::stdin().read_line(&mut input);
    let input_nums = input
        .split_whitespace()
        .map(|x| x.parse::<usize>().unwrap())
        .collect::<Vec<_>>();
    let a = input_nums[0];
    let b = input_nums[1];
    let c = input_nums[2];

    let mut i = 0;

    loop {
        if (a * i) % b == c {
            println!("YES");
            break;
        }
        if i > 1000 {
            println!("NO");
            break;
        }
        i += 1;
    }
}


It is the middle of 2018 and Maria Stepanovna, who lives outside Krasnokamensk (a town in Zabaikalsky region), wants to rent three displays to highlight an important problem.There are $$$n$$$ displays placed along a road, and the $$$i$$$-th of them can display a text with font size $$$s_i$$$ only. Maria Stepanovna wants to rent such three displays with indices $$$i < j < k$$$ that the font size increases if you move along the road in a particular direction. Namely, the condition $$$s_i < s_j < s_k$$$ should be held.The rent cost is for the $$$i$$$-th display is $$$c_i$$$. Please determine the smallest cost Maria Stepanovna should pay.

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

    let mut it = input.split_whitespace();

    let n: usize = it.next().unwrap().parse().unwrap();
    let s: Vec<u64> = it.by_ref().take(n).map(|x| x.parse().unwrap()).collect();
    let c: Vec<u64> = it.by_ref().take(n).map(|x| x.parse().unwrap()).collect();

    let mut gll: Vec<Vec<_>> = (0..n)
        .map(|i| (i + 1..n).filter(|&j| s[i] < s[j]).collect())
        .collect();

    for gl in gll.iter_mut() {
        gl.sort_unstable_by_key(|&i| c[i]);
    }

    let mut ans = None;

    for i in 0..n {
        for &j in gll[i].iter() {
            if let Some(&k) = gll[j].first() {
                let c = c[i] + c[j] + c[k];
                match ans {
                    Some(cur) if cur <= c => (),
                    _ => ans = Some(c),
                }
            }
        }
    }

    match ans {
        Some(c) => println!("{}", c),
        None => println!("-1"),
    }
}


void solution(int array[], int len) {
  int i;
  int j;
  int gap;

  for (gap = len / 2; gap > 0; gap = gap / 2) {
    for (i = gap; i < len; i++) {
      for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j = j - gap) {
        int temp = array[j];
        array[j] = array[j + gap];
        array[j + gap] = temp;
      }
    }
  }
}

fn solution<T: Ord + Copy>(values: &mut [T]) {
    fn insertion<T: Ord + Copy>(values: &mut [T], start: usize, gap: usize) {
        for i in ((start + gap)..values.len()).step_by(gap) {
            let val_current = values[i];
            let mut pos = i;

            while pos >= gap && values[pos - gap] > val_current {
                values[pos] = values[pos - gap];
                pos -= gap;
            }
            values[pos] = val_current;
        }
    }

    let mut count_sublist = values.len() / 2;
    while count_sublist > 0 {
        for pos_start in 0..count_sublist {
            insertion(values, pos_start, count_sublist);
        }
        count_sublist /= 2;
    }
}


Prime Number

Write a program which reads an integer <var>n</var> and prints the number of prime numbers which are less than or equal to <var>n</var>. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Input

Input consists of several datasets. Each dataset has an integer <var>n</var> (1 ≤ <var>n</var> ≤ 999,999) in a line.

The number of datasets is less than or equal to 30.

Output

For each dataset, prints the number of prime numbers.

Sample Input

10
3
11

Output for the Sample Input

4
2
5

int solution() {
  while (1) {
    int n;
    int i;
    int cnt = 0;
    int sw = 1;
    int sosuu[100000];
    int t;
    if (scanf("%d", &n) == EOF) {
      break;
    }
    if (n <= 1) {
      cnt = 0;
    } else {
      sosuu[cnt] = 2;
      cnt++;
      for (i = 3; i <= n; i += 2) {
        sw = 1;
        for (t = 0; t < cnt && sosuu[t] * sosuu[t] <= i; t++) {
          if (i % sosuu[t] == 0) {
            sw = 0;
            break;
          }
        }
        if (sw == 1) {
          sosuu[cnt] = i;
          cnt++;
        }
      }
    }
    printf("%d\n", cnt);
  }
  return 0;
}

fn solution() {
    loop {
        let mut s = String::new();
        stdin().read_line(&mut s).unwrap();
        let end: i32 = match s.trim().parse() {
            Ok(end) => end,
            Err(_) => return,
        };
        if end < 2 {
            println!("{}", 0);
            continue;
        }

        let mut flags = vec![true; ((end + 1) / 2) as usize];
        let flags_len = flags.len();
        flags[0] = false;
        for i in 1..flags_len {
            if !flags[i] {
                continue;
            }
            let n = i * 2 + 1;
            let mut j = 3;
            let mut comp_index = (n * j - 1) / 2;
            while comp_index < flags_len {
                flags[comp_index] = false;
                j += 2;
                comp_index = (n * j - 1) / 2;
            }
        }

        println!("{}", flags.iter().filter(|x| **x).count() + 1);
    }
}


博士が愛した２進数

  「君の靴のサイズはいくつかね」

  初対面の私に、いきなり博士は尋ねました。

  「 23.5 です」

  「ほお、実にきりのいい数字だ。2 の 4 乗に 2 の 2 乗と 2 の 1 乗と 2 の 0 乗と 2 の  -1  乗を 加えた数だ」

  続けて博士は尋ねました。

  「君、身長はいくつかね」

  「はい、158.1 です」

  博士は腕組みをして目を閉じました。しばらくの沈黙の後、口を開きました。

  「ナァ~」

  その後一緒に過ごした時間の中で、博士の行動がだんだん理解できるようになりました。

  まず、 私が博士の求めに応じて実数を言います。実数が整数部 8 桁以内で小数部 4 桁以内の 2 進数で表される場合、博士は 2 進数への変換結果を満足げに語ります。そうでない場合、悲しげに「ナァ~」 と鳴きます。これは、私が負の実数を言うまで繰り返されるのです。

  さて、博士は年齢とともにだんだんに長い計算が難しくなってきました。そこで、みなさんが博士に代わって、実数を入力し 2 進数に変換・出力するプログラムを作ってあげてください。ただし、2 進表現が制限桁数 (整数部 8 桁以内 + 小数部 4 桁以内) に収まらない場合は、NA (半角英字) を出力してください。入力される実数は整数部 8 桁以内、小数部 4 桁以内に収まるものとし、出力する 2 進表現は整数部 8 桁、小数部 4 桁で出力してください。

Input

複数のデータセットの並びが入力として与えられます。入力の終わりは負の実数ひとつの行で示されます。
各データセットとして１つの実数 <var>n</var> が１行に与えられます。

データセットの数は 1200 を超えません。

Output

入力データセットごとに 2 進数への変換結果を出力します。

Sample Input

23.5
158.1
-1.0

Output for the Sample Input

00010111.1000
NA

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

    for line in lines {
        let n: f64 = line.unwrap().parse().unwrap();
        if n < 0. {
            return;
        }

        let nf = n * 16.;
        let ni = nf as u64;

        if ni > 0xfff || nf.fract() != 0. {
            println!("NA");
        } else {
            println!("{:08b}.{:04b}", ni >> 4, ni & 0b1111);
        }
    }
}


Score : <var>200</var> points

Problem Statement

There are <var>N</var> people numbered <var>1</var> to <var>N</var>. Each person wears a red hat or a blue hat.

You are given a string <var>s</var> representing the colors of the people. Person <var>i</var> wears a red hat if <var>s_i</var> is R, and a blue hat if <var>s_i</var> is B.

Determine if there are more people wearing a red hat than people wearing a blue hat.

Constraints

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

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

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

Input

Input is given from Standard Input in the following format:

<var>N</var>
<var>s</var>

Output

If there are more people wearing a red hat than there are people wearing a blue hat, print Yes; otherwise, print No.

Sample Input 1

4
RRBR

Sample Output 1

Yes

There are three people wearing a red hat, and one person wearing a blue hat.

Since there are more people wearing a red hat than people wearing a blue hat, the answer is Yes.

Sample Input 2

4
BRBR

Sample Output 2

No

There are two people wearing a red hat, and two people wearing a blue hat.

Since there are as many people wearing a red hat as people wearing a blue hat, the answer is No.

int solution() {
  int n = 0;
  scanf("%d", &n);
  char s[100];
  scanf("%s", s);
  int i = 0;
  int countR = 0;
  while (i < n) {
    if (s[i] == 'R') {
      countR++;
    }
    i++;
  }
  if (countR > n - countR) {
    printf("Yes");
  } else {
    printf("No");
  }
}

fn solution() {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();

    let (r, b) = buf.chars().fold((0, 0), |(mut r, mut b), c| {
        match c {
            'R' => r += 1,
            'B' => b += 1,
            _ => (),
        }

        (r, b)
    });

    if r > b {
        println!("Yes");
    } else {
        println!("No");
    }
}


Day of Week

  The 9th day of September 2017 is Saturday. Then, what day of the week is the X-th of September 2017?

  Given a day in September 2017, write a program to report what day of the week it is.

Input

  The input is given in the following format.

<var>X</var>

  The input line specifies a day <var>X</var> (1 ≤ <var>X</var> ≤ 30) in September 2017.

Output

Output what day of the week it is in a line. Use the following conventions in your output: "mon" for Monday, "tue" for Tuesday, "wed" for Wednesday, "thu" for Thursday, "fri" for Friday, "sat" for Saturday, and "sun" for Sunday.

Sample Input 1

1

Sample Output 1

fri

Sample Input 2

9

Sample Output 2

sat

Sample Input 3

30

Sample Output 3

sat

int solution(void) {
  char data[7][4] = {"thu", "fri", "sat", "sun", "mon", "tue", "wed"};
  int X = 0;
  scanf("%d", &X);
  printf("%s\n", data[X % 7]);
  return 0;
}

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

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

    let days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];

    let x = (a % 7 + 3) % 7;
    println!("{}", days[x]);
}


Score : <var>200</var> points

Problem Statement

We will call a string that can be obtained by concatenating two equal strings an even string.
For example, xyzxyz and aaaaaa are even, while ababab and xyzxy are not.

You are given an even string <var>S</var> consisting of lowercase English letters.
Find the length of the longest even string that can be obtained by deleting one or more characters from the end of <var>S</var>.
It is guaranteed that such a non-empty string exists for a given input.

Constraints

<var>2 \leq |S| \leq 200</var>

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

There exists a non-empty even string that can be obtained by deleting one or more characters from the end of <var>S</var>.

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Print the length of the longest even string that can be obtained.

Sample Input 1

abaababaab

Sample Output 1

6

abaababaab itself is even, but we need to delete at least one character.

abaababaa is not even.

abaababa is not even.

abaabab is not even.

abaaba is even. Thus, we should print its length, <var>6</var>.

Sample Input 2

xxxx

Sample Output 2

2

xxx is not even.

xx is even.

Sample Input 3

abcabcabcabc

Sample Output 3

6

The longest even string that can be obtained is abcabc, whose length is <var>6</var>.

Sample Input 4

akasakaakasakasakaakas

Sample Output 4

14

The longest even string that can be obtained is akasakaakasaka, whose length is <var>14</var>.

int solution() {
  char str[200] = {0};
  int len = 0;

  scanf("%s", str);
  len = strlen(str);

  while (1) {
    char tmp1[100] = {0};
    char tmp2[100] = {0};

    if ((strlen(str) % 2) != 0) {
      len -= 1;
    } else {
      len -= 2;
    }

    strncpy(tmp1, &str[0], len / 2);
    strncpy(tmp2, &str[len / 2], len / 2);

    if (strcmp(tmp1, tmp2) == 0) {
      break;
    }
  }

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

  return 0;
}

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

    let mut it = buf.split_whitespace().map(|n| String::from_str(n).unwrap());
    let mut s = it.next().unwrap();

    while !s.is_empty() {
        s = s[0..s.len() - 2].to_string();
        if s.len() % 2 == 1 {
            continue;
        }
        if s[0..s.len() / 2 - 1] == s[s.len() / 2..s.len() - 1] {
            println!("{}", s.len());
            return;
        }
    }
}


Score : <var>300</var> points

Problem Statement

There are <var>N</var> stones arranged in a row. Every stone is painted white or black.
A string <var>S</var> represents the color of the stones. The <var>i</var>-th stone from the left is white if the <var>i</var>-th character of <var>S</var> is ., and the stone is black if the character is #.

Takahashi wants to change the colors of some stones to black or white so that there will be no white stone immediately to the right of a black stone.
Find the minimum number of stones that needs to be recolored.

Constraints

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

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

Input

Input is given from Standard Input in the following format:

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

Output

Print the minimum number of stones that needs to be recolored.

Sample Input 1

3
#.#

Sample Output 1

1

It is enough to change the color of the first stone to white.

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0

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

    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let s = buf.trim();

    let mut nr_wb = Vec::<(usize, usize)>::with_capacity(n);

    for c in s.chars() {
        let (w, b) = *nr_wb.last().unwrap_or(&(0usize, 0usize));
        if c == '.' {
            nr_wb.push((w + 1, b));
        } else {
            nr_wb.push((w, b + 1));
        }
    }

    let mut ans_wb: usize = n;
    let (all_w, _) = *nr_wb.last().unwrap();
    for i in 0..(n - 1) {
        let (cur_w, cur_b) = nr_wb[i];
        let rem_w = all_w - cur_w;
        ans_wb = std::cmp::min(ans_wb, cur_b + rem_w);
    }

    let ans_w: usize = nr_wb.last().unwrap().1;
    let ans_b: usize = nr_wb.last().unwrap().0;

    println!("{}", std::cmp::min(std::cmp::min(ans_w, ans_b), ans_wb));
}


Polycarp found under the Christmas tree an array $$$a$$$ of $$$n$$$ elements and instructions for playing with it:   At first, choose index $$$i$$$ ($$$1 \leq i \leq n$$$) — starting position in the array. Put the chip at the index $$$i$$$ (on the value $$$a_i$$$).  While $$$i \leq n$$$, add $$$a_i$$$ to your score and move the chip $$$a_i$$$ positions to the right (i.e. replace $$$i$$$ with $$$i + a_i$$$).  If $$$i > n$$$, then Polycarp ends the game. For example, if $$$n = 5$$$ and $$$a = [7, 3, 1, 2, 3]$$$, then the following game options are possible:   Polycarp chooses $$$i = 1$$$. Game process: $$$i = 1 \overset{+7}{\longrightarrow} 8$$$. The score of the game is: $$$a_1 = 7$$$.  Polycarp chooses $$$i = 2$$$. Game process: $$$i = 2 \overset{+3}{\longrightarrow} 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_2 + a_5 = 6$$$.  Polycarp chooses $$$i = 3$$$. Game process: $$$i = 3 \overset{+1}{\longrightarrow} 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_3 + a_4 = 3$$$.  Polycarp chooses $$$i = 4$$$. Game process: $$$i = 4 \overset{+2}{\longrightarrow} 6$$$. The score of the game is: $$$a_4 = 2$$$.  Polycarp chooses $$$i = 5$$$. Game process: $$$i = 5 \overset{+3}{\longrightarrow} 8$$$. The score of the game is: $$$a_5 = 3$$$. Help Polycarp to find out the maximum score he can get if he chooses the starting index in an optimal way.

int solution(void) {

  int *arr = malloc(200000 * sizeof(int));
  int *a = arr;

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

  while (t--) {
    int n;
    scanf("%d", &n);

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

    unsigned long long maximum_score = 0;

    for (int i = 0; i < n; i++) {
      int j = i;
      unsigned long long current_score = 0;

      while ((j < n) && (a[j])) {
        current_score += a[j];

        int temp = a[j];
        a[j] = 0;
        j += temp;
      }

      if (current_score > maximum_score) {
        maximum_score = current_score;
      }
    }

    printf("%llu\n", maximum_score);

    a += n;
  }

  free(arr);

  return 0;
}

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

    let out = &mut BufWriter::new(stdout());

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

        let mut a = String::new();
        stdin().read_line(&mut a).unwrap();
        let mut a: Vec<u32> = a.split_whitespace().map(|x| x.parse().unwrap()).collect();

        for ith in (0..n).rev() {
            let jth = ith + a[ith] as usize;
            if jth < n {
                a[ith] += a[jth];
            }
        }
        a.sort();
        writeln!(out, "{}", a[n - 1]).ok();
    }
}


You are given a string $$$s$$$ consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'. Note that each of the characters '?' is replaced independently from the others.A string $$$t$$$ of length $$$n$$$ is called a palindrome if the equality $$$t[i] = t[n-i+1]$$$ is true for all $$$i$$$ ($$$1 \le i \le n$$$).For example, if $$$s=$$$"01?????0", $$$a=4$$$ and $$$b=4$$$, then you can replace the characters '?' in the following ways:   "01011010";  "01100110". For the given string $$$s$$$ and the numbers $$$a$$$ and $$$b$$$, replace all the characters with '?' in the string $$$s$$$ by '0' or '1' so that the string becomes a palindrome and has exactly $$$a$$$ characters '0' and exactly $$$b$$$ characters '1'.

int solution() {
  long long int t;
  scanf("%lld", &t);
  for (long long int i = 0; i < t; i++) {
    int isPal = 1;
    long long int nulls_ones[2];
    scanf("%lld%lld\n", &nulls_ones[0], &nulls_ones[1]);

    long long int len = nulls_ones[0] + nulls_ones[1];
    char str[200001];
    scanf("%s", str);

    long long int j = 0;
    long long int m = len - 1;
    while (j < m) {
      if (str[j] != str[m]) {
        if (str[j] == '?') {
          str[j] = str[m];
        } else if (str[m] == '?') {
          str[m] = str[j];
        } else {
          isPal = 0;
        }
        nulls_ones[str[m] - '0'] -= 2;
      } else if (str[j] != '?') {
        nulls_ones[str[m] - '0'] -= 2;
      }
      j++;
      m--;
    }

    if (j == m) {
      long long int k = len / 2;
      if (str[k] == '?') {
        if (nulls_ones[0] % 2 != 0) {
          str[k] = '0';
        } else if (nulls_ones[1] % 2 != 0) {
          str[k] = '1';
        }
      }
      nulls_ones[str[m] - '0']--;
    }

    j = 0;
    m = len - 1;
    while (j < m) {
      if (str[j] == '?') {
        if (nulls_ones[0] > 0) {
          str[j] = str[m] = '0';
          nulls_ones[str[m] - '0'] -= 2;
        } else if (nulls_ones[1] > 0) {
          str[j] = str[m] = '1';
          nulls_ones[str[m] - '0'] -= 2;
        }
      }
      j++;
      m--;
    }

    if ((nulls_ones[0] >= 0) && (nulls_ones[1] >= 0) && isPal) {
      for (j = 0; j < len; j++) {
        printf("%c", str[j]);
      }
      printf("\n");
    } else {
      printf("-1\n");
    }
  }
  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut inp = stdin.lock().lines();
    let t = inp.next().unwrap().unwrap().parse::<i64>().unwrap();
    'outer: for _ in 0..t {
        let line = inp.next().unwrap().unwrap();
        let (a, b): (i64, i64) = {
            let mut iter = line.split(' ').map(|x| x.parse().unwrap());
            (iter.next().unwrap(), iter.next().unwrap())
        };
        let mut res = inp.next().unwrap().unwrap().chars().collect::<Vec<char>>();
        let (mut aa, mut bb): (i64, i64) = (0, 0);
        let mid = res.len() / 2 + res.len() % 2;
        for &ch in res.iter() {
            match ch {
                '0' => {
                    aa += 1;
                }
                '1' => {
                    bb += 1;
                }
                _ => {}
            }
        }
        for id1 in 0..mid {
            let ch1 = res[id1];
            let id2 = res.len() - id1 - 1;
            let ch2 = res[id2];
            if (ch1 == '?' && ch2 != '?') || (ch2 == '?' && ch1 != '?') {
                if ch1 == '0' || ch2 == '0' {
                    aa += 1;
                    res[id1] = '0';
                    res[id2] = '0';
                } else if ch1 == '1' || ch2 == '1' {
                    bb += 1;
                    res[id1] = '1';
                    res[id2] = '1';
                }
            }
        }
        for id1 in 0..mid {
            let ch1 = res[id1];
            let id2 = res.len() - id1 - 1;
            let ch2 = res[id2];
            if id1 == id2 {
                if ch1 == '?' {
                    if a % 2 > 0 {
                        aa += 1;
                        res[id1] = '0';
                    } else if b % 2 > 0 {
                        bb += 1;
                        res[id1] = '1';
                    } else {
                        println!("-1");
                        continue 'outer;
                    }
                }
                continue;
            }
            if ch1 != '?' && ch2 != '?' {
                if ch1 != ch2 {
                    println!("-1");
                    continue 'outer;
                }
                continue;
            }
            if ch1 == '?' && ch2 == '?' {
                if aa + 2 <= a {
                    aa += 2;
                    res[id1] = '0';
                    res[id2] = '0';
                } else if bb + 2 <= b {
                    bb += 2;
                    res[id1] = '1';
                    res[id2] = '1';
                } else {
                    println!("-1");
                    continue 'outer;
                }
            } else {
                if ch1 == '0' || ch2 == '0' {
                    aa += 1;
                    res[id1] = '0';
                    res[id2] = '0';
                } else if ch1 == '1' || ch2 == '1' {
                    bb += 1;
                    res[id1] = '1';
                    res[id2] = '1';
                }
            }
        }
        if aa == a && bb == b {
            for &ch in res.iter() {
                print!("{}", ch);
            }
            println!();
        } else {
            println!("-1");
        }
    }
}


Score : <var>200</var> points

Problem Statement

Iroha has a sequence of <var>N</var> strings <var>S_1, S_2, ..., S_N</var>. The length of each string is <var>L</var>.

She will concatenate all of the strings in some order, to produce a long string.

Among all strings that she can produce in this way, find the lexicographically smallest one.

Here, a string <var>s=s_1s_2s_3</var>...<var>s_n</var> is lexicographically smaller than another string <var>t=t_1t_2t_3</var>...<var>t_m</var> if and only if one of the following holds:

There exists an index <var>i(1≦i≦min(n,m))</var>, such that <var>s_j = t_j</var> for all indices <var>j(1≦j<i)</var>, and <var>s_i<t_i</var>.

<var>s_i = t_i</var> for all integers <var>i(1≦i≦min(n,m))</var>, and <var>n<m</var>.

Constraints

<var>1 ≦ N, L ≦ 100</var>

For each <var>i</var>, the length of <var>S_i</var> equals <var>L</var>.

For each <var>i</var>, <var>S_i</var> consists of lowercase letters.

Input

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

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

Output

Print the lexicographically smallest string that Iroha can produce.

Sample Input 1

3 3
dxx
axx
cxx

Sample Output 1

axxcxxdxx

The following order should be used: axx, cxx, dxx.

int solution() {
  int n;
  int l;
  scanf("%d%d", &n, &l);
  char str[n][l + 1];
  char a[(l * n) + 1];
  int ids[n];
  for (int i = 0; i < n; i++) {
    scanf("%s", &str[i][0]);
    ids[i] = i;
  }
  for (int i = n - 1; i > 0; i--) {
    for (int j = 0; j < i; j++) {
      if (strcmp(&str[ids[j]][0], &str[ids[j + 1]][0]) > 0) {
        int buf = ids[j];
        ids[j] = ids[j + 1];
        ids[j + 1] = buf;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    printf("%s", &str[ids[i]][0]);
  }

  return 0;
}

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

    let mut iter = buf.split_whitespace();

    iter.next();
    iter.next();
    let mut strings: Vec<&str> = iter.collect();

    strings.sort();
    println!("{}", strings.concat());
}


Score : <var>200</var> points

Problem Statement

There is a grid of squares with <var>H</var> horizontal rows and <var>W</var> vertical columns.
The square at the <var>i</var>-th row from the top and the <var>j</var>-th column from the left is represented as <var>(i, j)</var>.
Each square is black or white.
The color of the square is given as an <var>H</var>-by-<var>W</var> matrix <var>(a_{i, j})</var>.
If <var>a_{i, j}</var> is ., the square <var>(i, j)</var> is white; if <var>a_{i, j}</var> is #, the square <var>(i, j)</var> is black.

Snuke is compressing this grid.
He will do so by repeatedly performing the following operation while there is a row or column that consists only of white squares:

Operation: choose any one row or column that consists only of white squares, remove it and delete the space between the rows or columns.

It can be shown that the final state of the grid is uniquely determined regardless of what row or column is chosen in each operation.
Find the final state of the grid.

Constraints

<var>1 \leq H, W \leq 100</var>

<var>a_{i, j}</var> is . or #.

There is at least one black square in the whole grid.

Input

Input is given from Standard Input in the following format:

<var>H</var> <var>W</var>
<var>a_{1, 1}...a_{1, W}</var>
<var>:</var>
<var>a_{H, 1}...a_{H, W}</var>

Output

Print the final state of the grid in the same format as input (without the numbers of rows and columns); see the samples for clarity.

Sample Input 1

4 4
##.#
....
##.#
.#.#

Sample Output 1

###
###
.##

The second row and the third column in the original grid will be removed.

Sample Input 2

3 3
#..
.#.
..#

Sample Output 2

#..
.#.
..#

As there is no row or column that consists only of white squares, no operation will be performed.

Sample Input 3

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

Sample Output 3

#

Sample Input 4

7 6
......
....#.
.#....
..#...
..#...
......
.#..#.

Sample Output 4

..#
#..
.#.
.#.
#.#

int solution(void) {
  int h;
  int w;
  scanf("%d %d", &h, &w);
  char gazou[h][w + 1];

  for (int i = 0; i < h; i++) {
    scanf("%s", gazou[i]);
  }

  for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
      for (int k = 0; k < h; k++) {
        if (strstr(gazou[i], "#") != NULL && gazou[k][j] != '.') {
          printf("%c", gazou[i][j]);
          break;
        }
      }
      if (j == w - 1 && strstr(gazou[i], "#") != NULL) {
        printf("\n");
      }
    }
  }
}

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

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

    let mut iter = buf.split_whitespace();
    let h: usize = iter.next().unwrap().parse().unwrap();
    let w: usize = iter.next().unwrap().parse().unwrap();
    let a: Vec<Vec<char>> = (0..h)
        .map(|_| iter.next().unwrap().chars().collect())
        .collect();
    let mut rows = vec![false; h];
    let mut cols = vec![false; w];
    for i in 0..h {
        for j in 0..w {
            if a[i][j] == '#' {
                rows[i] = true;
                cols[j] = true;
            }
        }
    }
    for i in 0..h {
        if !rows[i] {
            continue;
        }
        for j in 0..w {
            if !cols[j] {
                continue;
            }
            print!("{}", a[i][j]);
        }
        println!();
    }
}


Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w":   "vvvv"  "vvvv"  "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows:  "vvvovvv"  "vvvovvv"  "vvvovvv"  "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov".

int solution() {
  char s[1000001];
  scanf("%s", s);
  long long int c = 0;
  long long int temp = 0;
  long long int i = 0;
  long long int sum = 0;
  while (s[i + 1] != '\0') {
    if ((s[i] == 'v') && s[i + 1] == 'v') {
      c = c + 1;
    }
    i = i + 1;
  }
  i = 0;
  while (s[i + 1] != '\0') {
    if (s[i] == 'o') {
      sum = sum + (temp * (c - temp));
    } else {
      if (s[i + 1] == 'v') {
        temp = temp + 1;
      }
    }
    i = i + 1;
  }
  printf("%lld", sum);
}

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 s = get().as_bytes();

    let mut ans = 0_u128;
    let mut ac = 0;
    let mut vc = 0;
    let mut oc = 0;
    let mut wc = 0;
    for i in 0..s.len() {
        if s[i] == b'o' {
            if vc > 0 {
                vc -= 1;
                ans += ac * vc;
                wc += vc;
                vc = 0;
            }
            oc += 1;
        } else {
            if oc > 0 {
                ac += wc * oc;
                oc = 0;
            }
            vc += 1;
        }
    }
    if vc > 0 {
        vc -= 1;
        ans += ac * vc;
    }
    println!("{}", ans);
}


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

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

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

    let arr: Vec<_> = buffer.split_whitespace().collect();

    let n = arr[0].parse::<usize>().unwrap();

    let mut comb = vec![];

    for _i in 0..2 * 2 * 2 {
        comb.push(1_000_000_000);
    }

    use std::cmp;

    for i in 0..n {
        let c = arr[1 + i * 2].parse::<u32>().unwrap();
        let ss = arr[1 + i * 2 + 1].chars();
        let mut id = 0;
        for j in ss {
            if j == 'A' {
                id |= 1;
            }
            if j == 'B' {
                id |= 2;
            }
            if j == 'C' {
                id |= 4;
            }
        }

        comb[id] = cmp::min(comb[id], c);
    }

    let mut ans = comb[7];

    for i in 1..8 {
        for j in i + 1..8 {
            let b = i | j;
            if b == 7 {
                ans = cmp::min(ans, comb[i] + comb[j]);
            }
        }
    }

    for i in 1..8 {
        for j in i + 1..8 {
            for k in j + 1..8 {
                let b = i | j | k;
                if b == 7 {
                    ans = cmp::min(ans, comb[i] + comb[j] + comb[k]);
                }
            }
        }
    }

    if ans >= 1_000_000_000 {
        println!("-1");
    } else {
        println!("{}", ans);
    }
}


$$$n$$$ robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous!Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the location of each robot: the world you live in can be modeled as an infinite coordinate plane, and the $$$i$$$-th robot is currently located at the point having coordinates ($$$x_i$$$, $$$y_i$$$). Furthermore, you may send exactly one command to all of the robots. The command should contain two integer numbers $$$X$$$ and $$$Y$$$, and when each robot receives this command, it starts moving towards the point having coordinates ($$$X$$$, $$$Y$$$). The robot stops its movement in two cases:  either it reaches ($$$X$$$, $$$Y$$$);  or it cannot get any closer to ($$$X$$$, $$$Y$$$). Normally, all robots should be able to get from any point of the coordinate plane to any other point. Each robot usually can perform four actions to move. Let's denote the current coordinates of the robot as ($$$x_c$$$, $$$y_c$$$). Then the movement system allows it to move to any of the four adjacent points:  the first action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c - 1$$$, $$$y_c$$$);  the second action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c$$$, $$$y_c + 1$$$);  the third action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c + 1$$$, $$$y_c$$$);  the fourth action allows it to move from ($$$x_c$$$, $$$y_c$$$) to ($$$x_c$$$, $$$y_c - 1$$$). Unfortunately, it seems that some movement systems of some robots are malfunctioning. For each robot you know which actions it can perform, and which it cannot perform.You want to send a command so all robots gather at the same point. To do so, you have to choose a pair of integer numbers $$$X$$$ and $$$Y$$$ so that each robot can reach the point ($$$X$$$, $$$Y$$$). Is it possible to find such a point?

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

    for _ in 0..q {
        let n = {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            iter.next().unwrap().parse::<usize>().unwrap()
        };

        let mut min_x: i32 = -100000;
        let mut max_x: i32 = 100000;

        let mut min_y: i32 = -100000;
        let mut max_y: i32 = 100000;

        for _ in 0..n {
            let (x, y, f1, f2, f3, f4) = {
                let mut line = String::new();
                stdin().read_line(&mut line).unwrap();
                let mut iter = line.split_whitespace();
                (
                    iter.next().unwrap().parse::<i32>().unwrap(),
                    iter.next().unwrap().parse::<i32>().unwrap(),
                    iter.next().unwrap().parse::<usize>().unwrap(),
                    iter.next().unwrap().parse::<usize>().unwrap(),
                    iter.next().unwrap().parse::<usize>().unwrap(),
                    iter.next().unwrap().parse::<usize>().unwrap(),
                )
            };

            if f1 == 0 {
                min_x = min_x.max(x)
            }
            if f2 == 0 {
                max_y = max_y.min(y)
            }
            if f3 == 0 {
                max_x = max_x.min(x)
            }
            if f4 == 0 {
                min_y = min_y.max(y)
            }
        }
        if min_x <= max_x && min_y <= max_y {
            println!("1 {} {}", min_x, min_y);
        } else {
            println!("0")
        }
    }
}


Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.The park is a rectangular table with $$$n$$$ rows and $$$m$$$ columns, where the cells of the table are squares, and the boundaries between the cells are streets. External borders are also streets. Every street has length $$$1$$$. For example, park with $$$n=m=2$$$ has $$$12$$$ streets.You were assigned to develop a plan for lighting the park. You can put lanterns in the middle of the streets. The lamp lights two squares near it (or only one square if it stands on the border of the park).    The park sizes are: $$$n=4$$$, $$$m=5$$$. The lighted squares are marked yellow. Please note that all streets have length $$$1$$$. Lanterns are placed in the middle of the streets. In the picture not all the squares are lit. Semyon wants to spend the least possible amount of money on lighting but also wants people throughout the park to keep a social distance. So he asks you to find the minimum number of lanterns that are required to light all the squares.

fn solution() {
    let mut t = String::new();
    io::stdin().read_line(&mut t).expect("Failed to read line");

    let t: i32 = t.trim().parse().expect("Failed to cast to i32");

    for _ in 0..t {
        let mut buff = String::new();
        io::stdin()
            .read_line(&mut buff)
            .expect("Failed to read line");
        let dims: Vec<i32> = buff
            .trim()
            .split(" ")
            .map(|x| x.parse().expect("Failed to cast to i32"))
            .collect();

        let sequares_amount = dims[0] * dims[1];
        let mut sequares_amount = sequares_amount as f64 / 2.0;
        sequares_amount = sequares_amount.ceil();

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


A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.

int solution(void) {
  int n;
  scanf("%d", &n);
  long long int a[n + 5];
  for (int i = 0; i < n; i++) {
    scanf("%lld", &a[i]);
  }
  for (int i = 0; i < n; i++) {
    if (a[i] < 2050 || a[i] % 2050 != 0) {
      printf("%d\n", -1);
    } else {
      long long int d = a[i] / 2050;
      long int k = 0;
      while (d != 0) {
        long int v = 0;
        v = d % 10;
        k = k + v;
        d = d / 10;
      }
      printf("%ld\n", k);
    }
  }

  return 0;
}

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

    let t: i32 = scan.token();
    for _ in 0..t {
        let n: i64 = scan.token();
        if n % 2050 > 0 {
            writeln!(writer, "-1").unwrap();
        } else {
            let mut x = n / 2050;
            let mut ans = 0;
            while x > 0 {
                ans += x % 10;
                x /= 10;
            }
            writeln!(writer, "{}", ans).unwrap();
        }
    }
}


Let's call some square matrix with integer values in its cells palindromic if it doesn't change after the order of rows is reversed and it doesn't change after the order of columns is reversed.For example, the following matrices are palindromic:  The following matrices are not palindromic because they change after the order of rows is reversed:  The following matrices are not palindromic because they change after the order of columns is reversed:  You are given $$$n^2$$$ integers. Put them into a matrix of $$$n$$$ rows and $$$n$$$ columns so that each number is used exactly once, each cell contains exactly one number and the resulting matrix is palindromic. If there are multiple answers, print any. If there is no solution, print "NO".

fn solution() {
    let mut i = stdin();
    let mut li = BufReader::new(i.lock());

    let mut input = String::new();
    li.read_to_string(&mut input);

    let parsed: Vec<Vec<usize>> = input
        .lines()
        .map(|l| l.split_whitespace().map(|n| n.parse().unwrap()).collect())
        .collect();

    let n = parsed[0][0];
    let odd = (n % 2) == 1;
    let nums = {
        let mut r = parsed[1].clone();
        r.sort();
        r
    };
    let l = nums.len();

    let s = n / 2 + if odd { 1 } else { 0 };
    let mut matrix: Vec<Vec<usize>> = (0..=s).map(|_| (0..s).map(|_| 0).collect()).collect();

    let mut fourth = ((0..s - if odd { 1 } else { 0 })
        .map(|n| (0..s - if odd { 1 } else { 0 }).map(move |m| (n, m))))
    .flatten();
    let mut twice = (0..s - 1)
        .map(|m| (s - 1, m))
        .chain((0..s - 1).map(|m| (m, s - 1)));
    let mut single = (0..1).map(|_| (s - 1, s - 1));
    let mut i = 0usize;

    while i < l {
        if i + 3 < l && nums[i] == nums[i + 3] {
            match fourth.next() {
                Some((x, y)) => {
                    matrix[x][y] = nums[i];
                    i += 4;
                }
                _ if odd => {
                    let o1 = twice.next();
                    let o2 = twice.next();
                    match (o1, o2) {
                        (Some((x1, y1)), Some((x2, y2))) => {
                            matrix[x1][y1] = nums[i];
                            matrix[x2][y2] = nums[i];
                            i += 4;
                        }
                        _ => {
                            println!("NO");
                            return;
                        }
                    }
                }
                _ => {
                    println!("NO");
                    return;
                }
            }
        } else if odd && i + 1 < l && nums[i] == nums[i + 1] {
            match twice.next() {
                Some((x, y)) => {
                    matrix[x][y] = nums[i];
                    i += 2;
                }
                None => {
                    println!("NO");
                    return;
                }
            }
        } else if odd {
            match single.next() {
                Some((x, y)) => {
                    matrix[x][y] = nums[i];
                    i += 1;
                }
                None => {
                    println!("NO");
                    return;
                }
            }
        } else {
            println!("NO");
            return;
        }
    }

    let mut res: Vec<Vec<usize>> = (0..n).map(|_| Vec::new()).collect();
    for i in 0usize..s {
        let mut r = matrix[i].clone();
        if odd {
            r.extend(matrix[i].iter().rev().skip(1));
        } else {
            r.extend(matrix[i].iter().rev());
        }
        res[i] = r.clone();
        if !odd || i != s - 1 {
            res[n - 1 - i] = r;
        }
    }

    println!("YES");
    for v in res {
        for i in v {
            print!("{} ", i);
        }
        println!();
    }
}


Score : <var>100</var> points

Problem Statement

On some day in January <var>2018</var>, Takaki is writing a document. The document has a column where the current date is written in yyyy/mm/dd format. For example, January <var>23</var>, <var>2018</var> should be written as 2018/01/23.

After finishing the document, she noticed that she had mistakenly wrote 2017 at the beginning of the date column. Write a program that, when the string that Takaki wrote in the date column, <var>S</var>, is given as input, modifies the first four characters in <var>S</var> to 2018 and prints it.

Constraints

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

The first eight characters in <var>S</var> are 2017/01/.

The last two characters in <var>S</var> are digits and represent an integer between <var>1</var> and <var>31</var> (inclusive).

Input

Input is given from Standard Input in the following format:

<var>S</var>

Output

Replace the first four characters in <var>S</var> with 2018 and print it.

Sample Input 1

2017/01/07

Sample Output 1

2018/01/07

Sample Input 2

2017/01/31

Sample Output 2

2018/01/31

int solution(void) {
  char s[11];
  scanf("%s", s);
  char *p = &s[4];
  printf("2018%s\n", p);
  return 0;
}

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

    println!("2018{}", &s[4..])
}


Score : <var>500</var> points

Problem Statement

There are <var>N</var> towns numbered <var>1</var> to <var>N</var> and <var>M</var> roads. The <var>i</var>-th road connects Town <var>A_i</var> and Town <var>B_i</var> bidirectionally and has a length of <var>C_i</var>.

Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most <var>L</var> liters of fuel, and one liter of fuel is consumed for each unit distance traveled. When visiting a town while traveling, he can full the tank (or choose not to do so). Travel that results in the tank becoming empty halfway on the road cannot be done.

Process the following <var>Q</var> queries:

The tank is now full. Find the minimum number of times he needs to full his tank while traveling from Town <var>s_i</var> to Town <var>t_i</var>. If Town <var>t_i</var> is unreachable, print <var>-1</var>.

Constraints

All values in input are integers.

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

<var>0 \leq M \leq \frac{N(N-1)}{2}</var>

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

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

<var>A_i \neq B_i</var>

<var>\left(A_i, B_i\right) \neq \left(A_j, B_j\right)</var> (if <var>i \neq j</var>)

<var>\left(A_i, B_i\right) \neq \left(B_j, A_j\right)</var> (if <var>i \neq j</var>)

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

<var>1 \leq Q \leq N\left(N-1\right)</var>

<var>1 \leq s_i, t_i \leq N</var>

<var>s_i \neq t_i</var>

<var>\left(s_i, t_i\right) \neq \left(s_j, t_j\right)</var> (if <var>i \neq j</var>)

Input

Input is given from Standard Input in the following format:

<var>N</var> <var>M</var> <var>L</var>
<var>A_1</var> <var>B_1</var> <var>C_1</var>
<var>:</var>
<var>A_M</var> <var>B_M</var> <var>C_M</var>
<var>Q</var>
<var>s_1</var> <var>t_1</var>
<var>:</var>
<var>s_Q</var> <var>t_Q</var>

Output

Print <var>Q</var> lines.

The <var>i</var>-th line should contain the minimum number of times the tank needs to be fulled while traveling from Town <var>s_i</var> to Town <var>t_i</var>. If Town <var>t_i</var> is unreachable, the line should contain <var>-1</var> instead.

Sample Input 1

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

Sample Output 1

0
1

To travel from Town <var>3</var> to Town <var>2</var>, we can use the second road to reach Town <var>2</var> without fueling the tank on the way.

To travel from Town <var>1</var> to Town <var>3</var>, we can first use the first road to get to Town <var>2</var>, full the tank, and use the second road to reach Town <var>3</var>.

Sample Input 2

4 0 1
1
2 1

Sample Output 2

-1

There may be no road at all.

Sample Input 3

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

Sample Output 3

0
0
1
2
0
0
1
2
0
0
0
1
1
1
0
0
2
2
1
0

fn solution() {
    let (N, M, L): (usize, usize, 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(),
        )
    };
    let (A, B, C): (Vec<usize>, Vec<usize>, Vec<i64>) = {
        let (mut A, mut B, mut C) = (vec![], vec![], vec![]);
        for _ in 0..M {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            A.push(iter.next().unwrap().parse().unwrap());
            B.push(iter.next().unwrap().parse().unwrap());
            C.push(iter.next().unwrap().parse().unwrap());
        }
        (A, B, C)
    };
    let Q: usize = {
        let mut line: String = String::new();
        std::io::stdin().read_line(&mut line).unwrap();
        line.trim().parse().unwrap()
    };
    let (s, t): (Vec<usize>, Vec<usize>) = {
        let (mut s, mut t) = (vec![], vec![]);
        for _ in 0..Q {
            let mut line: String = String::new();
            std::io::stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            s.push(iter.next().unwrap().parse().unwrap());
            t.push(iter.next().unwrap().parse().unwrap());
        }
        (s, t)
    };

    const INF: i64 = 1_000_000_000_000_000;
    let mut dp = vec![vec![INF; N + 1]; N + 1];
    for i in 0..M {
        dp[A[i]][B[i]] = C[i];
        dp[B[i]][A[i]] = C[i];
    }
    for k in 1..(N + 1) {
        for i in 1..(N + 1) {
            for j in 1..(N + 1) {
                dp[i][j] = std::cmp::min(dp[i][j], dp[i][k] + dp[k][j]);
            }
        }
    }
    let mut dp2 = (0..(N + 1))
        .map(|i| {
            (0..(N + 1))
                .map(|j| if dp[i][j] <= L { 1 } else { INF })
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();
    for k in 1..(N + 1) {
        for i in 1..(N + 1) {
            for j in 1..(N + 1) {
                dp2[i][j] = std::cmp::min(dp2[i][j], dp2[i][k] + dp2[k][j]);
            }
        }
    }

    let ans = (0..Q)
        .map(|i| {
            if dp2[s[i]][t[i]] == INF {
                -1
            } else {
                dp2[s[i]][t[i]] - 1
            }
        })
        .map(|res| res.to_string())
        .collect::<Vec<_>>()
        .join("\n");

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


Card Game

  Taro and Hanako are playing card games. They have <var>n</var> cards each, and they compete <var>n</var> turns. At each turn Taro and Hanako respectively puts out a card.
  The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner obtains 3 points. In the case of a draw, they obtain 1 point each.

  Write a program which reads a sequence of cards Taro and Hanako have and reports the final scores of the game.

Input

  In the first line, the number of cards <var>n</var> is given. In the following <var>n</var> lines, the cards for <var>n</var> turns are given respectively. For each line, the first string represents the Taro's card and the second one represents Hanako's card.

Constraints

<var>n</var> ≤ 1000

The length of the string ≤ 100

Output

  Print the final scores of Taro and Hanako respectively. Put a single space character between them.

Sample Input

3
cat dog
fish fish
lion tiger

Sample Output

1 7

int solution(void) {
#define WIN_POINT 3
#define DRAW_POINT 1

  int n = 0;
  char t_card[101];
  char h_card[101];
  int i = 0;
  int check = 0;
  int t_point = 0;
  int h_point = 0;

  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%s %s", t_card, h_card);
    check = strcmp(t_card, h_card);
    if (check < 0) {
      h_point += WIN_POINT;
    } else if (check > 0) {
      t_point += WIN_POINT;
    } else {
      t_point += DRAW_POINT;
      h_point += DRAW_POINT;
    }
  }
  printf("%d %d\n", t_point, h_point);

#undef WIN_POINT
#undef DRAW_POINT

  return 0;
}

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

    let score = stdin.lock().lines().take(n).fold((0, 0), |acc, line| {
        let line = line.unwrap();
        let mut ite = line.split_whitespace();
        let w1 = ite.next().unwrap();
        let w2 = ite.next().unwrap();

        match w1.cmp(w2) {
            Ordering::Less => (acc.0, acc.1 + 3),
            Ordering::Equal => (acc.0 + 1, acc.1 + 1),
            Ordering::Greater => (acc.0 + 3, acc.1),
        }
    });

    println!("{} {}", score.0, score.1);
}


Score : <var>100</var> points

Problem Statement

<var>X</var> and <var>A</var> are integers between <var>0</var> and <var>9</var> (inclusive).

If <var>X</var> is less than <var>A</var>, print <var>0</var>; if <var>X</var> is not less than <var>A</var>, print <var>10</var>.

Constraints

<var>0 \leq X, A \leq 9</var>

All values in input are integers.

Input

Input is given from Standard Input in the following format:

<var>X</var> <var>A</var>

Output

If <var>X</var> is less than <var>A</var>, print <var>0</var>; if <var>X</var> is not less than <var>A</var>, print <var>10</var>.

Sample Input 1

3 5

Sample Output 1

0

<var>3</var> is less than <var>5</var>, so we should print <var>0</var>.

Sample Input 2

7 5

Sample Output 2

10

<var>7</var> is not less than <var>5</var>, so we should print <var>10</var>.

Sample Input 3

6 6

Sample Output 3

10

<var>6</var> is not less than <var>6</var>, so we should print <var>10</var>.

int solution(void) {

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

  printf("%d", x < a ? 0 : 10);
}

fn solution() {
    let mut xa = String::new();
    stdin().read_line(&mut xa).unwrap();
    let xa: Vec<usize> = xa.split_whitespace().flat_map(str::parse).collect();
    println!("{}", if xa[0] >= xa[1] { 10 } else { 0 });
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.

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

  while (t--) {
    int n = 0;
    int r = 0;

    scanf("%d", &n);

    int arr[n];

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

    int j = 0;
    int k = 0;

    for (int i = 0; i < n; i++) {
      if (arr[i] == 0) {
        r++;
      } else if (arr[i] == 1) {
        j++;
      } else {
        k++;
      }
    }

    if (j >= k) {
      r += k + ((j - k) / 3);
    } else {
      r += j + ((k - j) / 3);
    }

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

  return 0;
}

fn solution() {
    let stdin = io::stdin();
    let mut str_in = String::new();
    stdin.lock().read_line(&mut str_in);
    let mut tc: i32 = str_in.trim().parse::<i32>().unwrap();
    while tc > 0 {
        str_in = String::new();
        stdin.lock().read_line(&mut str_in);
        let _nn = str_in.trim().parse::<i32>().unwrap();
        str_in = String::new();
        stdin.lock().read_line(&mut str_in);
        let nums: Vec<i32> = str_in
            .split(' ')
            .map(|s| s.trim())
            .map(|s| s.parse::<i32>().unwrap())
            .collect();
        let mut cc: [i32; 3] = [0, 0, 0];
        for n in nums {
            if n % 3 == 0 {
                cc[0] += 1;
            } else if n % 3 == 1 {
                cc[1] += 1;
            } else if n % 3 == 2 {
                cc[2] += 1;
            }
        }
        println!(
            "{:?}",
            cc[0] + cmp::min(cc[1], cc[2]) + (cmp::max(cc[1], cc[2]) - cmp::min(cc[1], cc[2])) / 3
        );
        tc -= 1;
    }
}


Cake Party

  I’m planning to have a party on my birthday. Many of my friends will come to the party. Some of them will come with one or more pieces of cakes, but it is not certain if the number of the cakes is a multiple of the number of people coming.

  I wish to enjoy the cakes equally among the partiers. So, I decided to apply the following rules. First, all the party attendants are given the same number of cakes. If some remainder occurs, a piece goes on a priority basis to the party host (that’s me!). How many pieces of cake can I enjoy?

  Given the number of my friends and cake information, make a program to calculate how many pieces of cake I can enjoy. Note that I am not counted in the number of my friends.

Input

The input is given in the following format.

$N$ $C$
$p_1$ $p_2$ ... $p_C$

The first line provides the number of my friends $N$ ($1 \leq N \leq 100$) and the number of those among them who brought one or more pieces of cake with them $C$ ($1 \leq C \leq N$). The second line provides an array of integers $p_i$ ($1 \leq p_i \leq100$), each of which shows the number of cakes of the $i$-th friend of mine who was willing to come up with one or more pieces of cake.

Output

  Output the number of cakes I can enjoy.

Sample Input 1

5 4
5 5 6 5

Sample Output 1

4

Sample Input 2

7 5
8 8 8 8 8

Sample Output 2

5

Sample Input 3

100 3
3 3 3

Sample Output 3

1

int solution(void) {

  int i = 0;

  int n = 0;

  int c = 0;

  int p[100];

  int total = 0;

  int count = 0;

  int Surplus = 0;

  for (i = 0; i < 100; i++) {
    p[i] = 0;
  }

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

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

  count = total / (n + 1);

  Surplus = total % (n + 1);

  if (Surplus == 0) {
    printf("%d\n", count);
  }

  else {
    printf("%d\n", count + 1);
  }
}

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

    let n: u32 = {
        let line = lines.next().unwrap();
        let mut iter = line.split_whitespace().map(|s| s.parse().unwrap());

        iter.next().unwrap()
    };

    let sum_p: u32 = {
        let line = lines.next().unwrap();
        line.split_whitespace()
            .map(|s| s.parse::<u32>().unwrap())
            .sum()
    };

    let got = (sum_p as f64 / (n + 1) as f64).ceil();

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


You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones and an integer $$$k$$$. In one operation you can do one of the following:  Select $$$2$$$ consecutive elements of $$$a$$$ and replace them with their minimum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \min(a_{i}, a_{i+1}), a_{i+2}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-1$$$). This operation decreases the size of $$$a$$$ by $$$1$$$.  Select $$$k$$$ consecutive elements of $$$a$$$ and replace them with their maximum (that is, let $$$a := [a_{1}, a_{2}, \ldots, a_{i-1}, \max(a_{i}, a_{i+1}, \ldots, a_{i+k-1}), a_{i+k}, \ldots, a_{n}]$$$ for some $$$1 \le i \le n-k+1$$$). This operation decreases the size of $$$a$$$ by $$$k-1$$$. Determine if it's possible to turn $$$a$$$ into $$$[1]$$$ after several (possibly zero) operations.

int solution() {
  int t;

  scanf("%d", &t);
  while (t--) {
    int n;
    int k;
    int count = 0;
    scanf("%d %d", &n, &k);
    int arr[n];
    for (int i = 0; i < n; i++) {
      scanf("%d", &arr[i]);
      if (arr[i] == 1) {
        count++;
      }
    }
    if (count > 0) {

      printf("YES\n");
    }

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

fn solution() {
    let stdin = std::io::stdin();
    let stdin_lock = stdin.lock();
    let mut line_iter = stdin_lock.lines();
    let t = line_iter
        .next()
        .unwrap()
        .unwrap()
        .as_str()
        .parse::<usize>()
        .unwrap();
    for _ in 0..t {
        let (_n_str, _k_str) = line_iter.next().unwrap().unwrap().split_once(' ').unwrap();

        let any_non_zero = line_iter
            .next()
            .unwrap()
            .unwrap()
            .split(' ')
            .any(|digit| digit == "1");
        let output = if any_non_zero { "YES" } else { "NO" };
        println!("{}", output);
    }
}


Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $$$n$$$ players arranged in a circle, so that for all $$$j$$$ such that $$$2 \leq j \leq n$$$, player $$$j - 1$$$ is to the left of the player $$$j$$$, and player $$$j$$$ is to the right of player $$$j - 1$$$. Additionally, player $$$n$$$ is to the left of player $$$1$$$, and player $$$1$$$ is to the right of player $$$n$$$.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $$$0$$$, $$$1$$$, or $$$2$$$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $$$1$$$ other player, then they should logically attack that player in response. If instead a player is being attacked by $$$0$$$ or $$$2$$$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $$$n$$$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.

int solution() {
  long long int a = 1;
  long long int i;
  long long int t;
  long long int n;
  long long int j;
  long long int k;
  long long int max = 0;
  long long int min = 0;
  long long int ans = 0;
  char ar[200010];
  scanf("%lld", &t);

  for (i = 0; i < t; i++) {
    scanf("%lld %s", &n, ar);

    for (j = 0; j < n; j++) {

      if (ar[j] != ar[j + 1] && j < (n - 1)) {
        if (a) {
          max = j + 1;
        }
        a = 0;
      }

      if (ar[j] == ar[j + 1] && ar[j + 1] == ar[j + 2]) {
        ans++;
        j += 2;
        if (ar[j] != ar[j + 1] && j < (n - 1)) {
          if (a) {
            max = j + 1;
          }
          a = 0;
        }
      }
    }

    if (a) {
      if (n % 3 == 0) {
        ans = n / 3;
      } else {
        ans = (n / 3) + 1;
      }
    } else {
      for (j = n - 1; j >= 0; j--) {
        if (ar[j] != ar[j - 1]) {
          break;
        }
      }

      j = n - j;

      j %= 3;
      max %= 3;
      if (ar[0] == ar[n - 1]) {
        ans += (j + max) / 3;
      }
    }

    printf("%lld\n", ans);
    ans = 0;
    a = 1;
  }
  return 0;
}

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

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

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

        if (0..(n - 1)).all(|i| s[i] == s[i + 1]) {
            println!("{}", n.div_ceil(3));
            continue;
        }

        while s.front().unwrap() == s.back().unwrap() {
            let c = s.pop_front().unwrap();
            s.push_back(c);
        }

        let mut ans = 0;
        let mut i = 0;
        while i < n {
            let mut j = i + 1;
            while j < n && s[i] == s[j] {
                j += 1;
            }
            ans += (j - i) / 3;
            i = j;
        }
        println!("{}", ans);
    }
}


Swapping Two Numbers

  Write a program which reads two integers <var>x</var> and <var>y</var>, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers <var>x</var> and <var>y</var> separated by a single space.

The input ends with two 0 (when both <var>x</var> and <var>y</var> are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print <var>x</var> and <var>y</var> in ascending order in a line. Put a single space between <var>x</var> and </var>y</var>.

Constraints

 0 ≤ <var>x</var>, <var>y</var> ≤ 10000

 the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5

int solution(void) {

  int i = 0;
  int x = 0;
  int y = 0;

  for (i = 1;; i++) {
    scanf("%d %d", &x, &y);

    if (x <= 0 && x > 10000 && y <= 0 && y > 10000) {

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

    if (x != 0 || y != 0) {
      if (x < y) {
        printf("%d %d\n", x, y);
      } else {
        printf("%d %d\n", y, x);
      }
    } else {
      break;
    }
  }

  return 0;
}

fn solution() {
    loop {
        let mut v: Vec<i32> = {
            let mut b = String::new();
            let s = std::io::stdin();
            s.read_line(&mut b).unwrap();
            b.split_whitespace().flat_map(str::parse).collect()
        };
        if v == [0, 0] {
            break;
        }
        v.sort();
        println!("{} {}", v[0], v[1]);
    }
}


Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.

int solution() {
  int n;
  scanf("%d", &n);
  char a[n + 1];
  scanf("%s", a);
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; i++) {
    int k;
    char c;
    scanf("%d", &k);
    scanf("%c", &c);
    scanf("%c", &c);
    int l = 0;
    int r = -1;
    int check = 0;
    int ans = 0;
    int max = 0;
    while (r + 1 < n) {
      r++;

      if (a[r] != c && check < k) {
        check++;
      } else if (a[r] != c && check == k) {
        r--;
        break;
      }
    }

    max = r - l + 1;
    while (r + 1 < n) {
      r++;
      while (a[l] == c) {
        l++;
      }
      l++;
      while (a[r + 1] == c && r + 1 < n) {
        r++;
      }
      ans = r - l + 1;

      if (ans > max) {
        max = ans;
      }
    }
    printf("%d\n", max);
  }
}

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

    let s = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().bytes().map(|b| b - b'a').collect::<Vec<u8>>()
    };

    let mut dp: Vec<Vec<usize>> =
        std::iter::repeat_n(std::iter::repeat_n(0, n + 1).collect(), 26).collect();

    for c in 0..26 {
        for i in 0..n {
            let mut replace_cnt = 0usize;
            for j in i..n {
                if s[j] != c {
                    replace_cnt += 1;
                }
                let c = c as usize;
                dp[c][replace_cnt] = cmp::max(dp[c][replace_cnt], j - i + 1);
            }
        }

        let c = c as usize;
        for i in 1..(n + 1) {
            dp[c][i] = cmp::max(dp[c][i], dp[c][i - 1]);
        }
    }

    let q = {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().parse::<usize>().unwrap()
    };

    for _ in 0..q {
        let (m, c) = {
            let mut input = String::new();
            io::stdin().read_line(&mut input).unwrap();
            let mut it = input.split_whitespace();
            (
                it.next().unwrap().parse::<usize>().unwrap(),
                it.next().unwrap().as_bytes()[0] - b'a',
            )
        };

        let ans = dp[c as usize][m];

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