const main = (input) => {
  var ip = input.trim().split("\n")[0].split(" ");
  var N = ip[0]-0;
  var K = ip[1]-0;
  if(N<=K/2){
    console.log(N);
    return;
  }
  var inputs = input.trim().split("\n")[1].split("");
  var ans = 0;
  for(var s=0;s<inputs.length;s++){
    var cnt = 0, zflg=false,zcnt=0, tans = 0;
    if(s == 0 || (inputs[s-1] == 0 && inputs[s] == 1)){
      for(var e=s;e<inputs.length;e++){
        if(inputs[e]==0 && zflg==false){
          zcnt++;
          zflg = true;
          if(K<zcnt) break;
        }else if(inputs[e] == 1){
          zflg = false;
        }
        tans++;
      }
      ans = Math.max(ans, tans);
    }
  }
  console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8'));

Score : 400 points

Problem Statement

N people are arranged in a row from left to right.

You are given a string S of length N consisting of 0 and 1, and a positive integer K.

The i-th person from the left is standing on feet if the i-th character of S is 0, and standing on hands if that character is 1.

You will give the following direction at most K times (possibly zero):

Direction: Choose integers l and r satisfying 1 \leq l \leq r \leq N, and flip the l-th, (l+1)-th, ..., and r-th persons. That is, for each i = l, l+1, ..., r, the i-th person from the left now stands on hands if he/she was standing on feet, and stands on feet if he/she was standing on hands.

Find the maximum possible number of consecutive people standing on hands after at most K directions.

Constraints

N is an integer satisfying 1 \leq N \leq 10^5.

K is an integer satisfying 1 \leq K \leq 10^5.

The length of the string S is N.

Each character of the string S is 0 or 1.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the maximum possible number of consecutive people standing on hands after at most K directions.

Sample Input 1

5 1
00010

Sample Output 1

4

We can have four consecutive people standing on hands, which is the maximum result, by giving the following direction:

Give the direction with l = 1, r = 3, which flips the first, second and third persons from the left.

Sample Input 2

14 2
11101010110011

Sample Output 2

8

Sample Input 3

1 1
1

Sample Output 3

1

No directions are necessary.


'use strict';
// inputに入力データ全体が入る
function Main(input) {
  input = input.split("\n");
  let modArr = input.map(function(val){
    val = parseInt(val);
    if(val%10===0){
      return 10;
    }else{
      return val%10;
    }
  });
  let min = modArr.indexOf(Math.min.apply(null, modArr));
  let last = parseInt(input[min]);

  input.splice(min, 1);
  let result =0;
  for(let i = 0 ; i< input.length; i++){
  	let x = Math.ceil(input[i] /10)*10;
    result += x;
  };
  result += last;
  console.log(parseInt(result));
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score: 100 points

Problem Statement

In AtCoder city, there are five antennas standing in a straight line. They are called Antenna A, B, C, D and E from west to east, and their coordinates are a, b, c, d and e, respectively.

Two antennas can communicate directly if the distance between them is k or less, and they cannot if the distance is greater than k.

Determine if there exists a pair of antennas that cannot communicate directly.

Here, assume that the distance between two antennas at coordinates p and q (p < q) is q - p.

Constraints

a, b, c, d, e and k are integers between 0 and 123 (inclusive).

a < b < c < d < e

Input

Input is given from Standard Input in the following format:

a
b
c
d
e
k

Output

Print :( if there exists a pair of antennas that cannot communicate directly, and print Yay! if there is no such pair.

Sample Input 1

1
2
4
8
9
15

Sample Output 1

Yay!

In this case, there is no pair of antennas that cannot communicate directly, because:

the distance between A and B is 2 - 1 = 1

the distance between A and C is 4 - 1 = 3

the distance between A and D is 8 - 1 = 7

the distance between A and E is 9 - 1 = 8

the distance between B and C is 4 - 2 = 2

the distance between B and D is 8 - 2 = 6

the distance between B and E is 9 - 2 = 7

the distance between C and D is 8 - 4 = 4

the distance between C and E is 9 - 4 = 5

the distance between D and E is 9 - 8 = 1

and none of them is greater than 15. Thus, the correct output is Yay!.

Sample Input 2

15
18
26
35
36
18

Sample Output 2

:(

In this case, the distance between antennas A and D is 35 - 15 = 20 and exceeds 18, so they cannot communicate directly.
Thus, the correct output is :(.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


function Main(input){
     inputs = input.split('\n');
     //console.log(inputs);
     if(inputs[4] - inputs[0] <=inputs[5]){
     console.log('Yay!');
     }else{
     console.log(':(');
     }
}

Main(require("fs").readFileSync("/dev/stdin","utf8"));


function main(args) {
	var input = args.split(/\n/);
  	console.log((input[4] * 1 - input[0] * 1 <= k) ? ":(" : "Yay!");
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


let main = (args) => {
	let input = args.split(/\n/);
  	console.log((input[4] - input[0] <= k) ? ":(" : "Yay!");
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


input = a.split('\n').map(Number);

k = input[input.length - 1];
flag = 0;

for (i = 0; i < 5; i++) {
    for (j = 0; j < 5; j++) {
        flag += Math.abs(input[i] - input[j]) > k;
    }
}

console.log(flag == 0 ? 'Yay!' : ':(');


'use strict';
function Main(input) {
    input = input.split("\n");
    let tmp = input[0].split(" ");
    console.log(input);
    for(let i=0;i<5;i++){
        for(let j = i;j<5;j++){
            //console.log(`A:${input[i]} vs B:${input[j]} = abs:${input[i]-input[j]}`)

            if (Math.abs(input[i]-input[j])>input[5]){
                console.log(":(");
                return;
            }
        }
    }
    console.log("Yay!");
    return;
}
/*
Main(`1
2
4
8
9
15`);
*/
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
	tmp = input.split("\n");

	var a = parseInt(tmp[0]);
	var b = parseInt(tmp[1]);
	var c = parseInt(tmp[2]);
	var d = parseInt(tmp[3]);
	var e = parseInt(tmp[4]);
	var k = parseInt(tmp[5]);
	var err = 0;

	if(b-a > k){ err++; }
	if(c-a > k){ err++; }
	if(d-a > k){ err++; }
	if(e-a > k){ err++; }
	if(c-b > k){ err++; }
	if(d-b > k){ err++; }
	if(e-b > k){ err++; }
	if(d-c > k){ err++; }
	if(e-c > k){ err++; }
	if(e-d > k){ err++; }

	if(err>=1){
		console.log(":(");
	}else{
		console.log("Yay!");
	}
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'
function Main(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  var r=input.map(x=>x%10);
  var M=Math.max.apply(null,r);
  var m=Math.min.apply(null,r);
  input=input.map(x=>x-x%10);
  var result=input.reduce((a,c)=>a+c,0)+r.map(x=>x?10:0).reduce((a,c)=>a+c,0)-(m?10:0)+m;
  console.log(result);
}

Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score: 200 points

Problem Statement

The restaurant AtCoder serves the following five dishes:

ABC Don (rice bowl): takes A minutes to serve.

ARC Curry: takes B minutes to serve.

AGC Pasta: takes C minutes to serve.

APC Ramen: takes D minutes to serve.

ATC Hanbagu (hamburger patty): takes E minutes to serve.

Here, the time to serve a dish is the time between when an order is placed and when the dish is delivered.

This restaurant has the following rules on orders:

An order can only be placed at a time that is a multiple of 10 (time 0, 10, 20, ...).

Only one dish can be ordered at a time.

No new order can be placed when an order is already placed and the dish is still not delivered, but a new order can be placed at the exact time when the dish is delivered.

E869120 arrives at this restaurant at time 0. He will order all five dishes. Find the earliest possible time for the last dish to be delivered.

Here, he can order the dishes in any order he likes, and he can place an order already at time 0.

Constraints

A, B, C, D and E are integers between 1 and 123 (inclusive).

Input

Input is given from Standard Input in the following format:

A
B
C
D
E

Output

Print the earliest possible time for the last dish to be delivered, as an integer.

Sample Input 1

29
20
7
35
120

Sample Output 1

215

If we decide to order the dishes in the order ABC Don, ARC Curry, AGC Pasta, ATC Hanbagu, APC Ramen, the earliest possible time for each order is as follows:

Order ABC Don at time 0, which will be delivered at time 29.

Order ARC Curry at time 30, which will be delivered at time 50.

Order AGC Pasta at time 50, which will be delivered at time 57.

Order ATC Hanbagu at time 60, which will be delivered at time 180.

Order APC Ramen at time 180, which will be delivered at time 215.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 2

101
86
119
108
57

Sample Output 2

481

If we decide to order the dishes in the order AGC Pasta, ARC Curry, ATC Hanbagu, APC Ramen, ABC Don, the earliest possible time for each order is as follows:

Order AGC Pasta at time 0, which will be delivered at time 119.

Order ARC Curry at time 120, which will be delivered at time 206.

Order ATC Hanbagu at time 210, which will be delivered at time 267.

Order APC Ramen at time 270, which will be delivered at time 378.

Order ABC Don at time 380, which will be delivered at time 481.

There is no way to order the dishes in which the last dish will be delivered earlier than this.

Sample Input 3

123
123
123
123
123

Sample Output 3

643

This is the largest valid case.


"use strict";

const main = arg => {
    arg = arg.split("\n");
    const times = arg.map(n=>parseInt(n));
    let timer   = 0;
    let min = 10;

    let sum = 0;

    for(let i in times) {
        let digitOne   = parseInt(String(times[i]).split("").pop());
        let digitMinus = 10 - digitOne;
        sum += parseInt(times[i]);

        if(digitMinus !== 10) {
            sum += digitMinus;
        }

        if(digitMinus !== 10 && digitOne < min) {
            min = digitOne;
        }
    }

    console.log(sum - (10 - min));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";
function main(input) {
    const args = input.split('\n');

    let ans_time = 0;
    let first = 9;
    let food_first;
    let flag = false

    for(var i = 0; i < args.length - 1; i++) {
        const food = parseInt(args[i]);
        ans_time += Math.ceil(food / 10) * 10;
        food_first = food % 10;
        if (food_first !== 0 && food_first <= first) {
            first = food_first;
            flag = true;
        }
    }
    if (!flag) { first = 10; }
    console.log(ans_time - 10 + first);

}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'
function Main(input) {
  const numP = input.split("\n").map(Number);
  numP.pop();
  let numG = numP[0];
  numP.shift();
  // console.log({ numG, numP });

  numP.sort((a, b) => a - b);
  // console.log({ numG, numP });

  let btlNeck = Math.ceil(numG / numP[0]);
  let Ans = btlNeck + 4;
  console.log(Ans);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score: 300 points

Problem Statement

In 2028 and after a continuous growth, AtCoder Inc. finally built an empire with six cities (City 1, 2, 3, 4, 5, 6)!

There are five means of transport in this empire:

Train: travels from City 1 to 2 in one minute. A train can occupy at most A people.

Bus: travels from City 2 to 3 in one minute. A bus can occupy at most B people.

Taxi: travels from City 3 to 4 in one minute. A taxi can occupy at most C people.

Airplane: travels from City 4 to 5 in one minute. An airplane can occupy at most D people.

Ship: travels from City 5 to 6 in one minute. A ship can occupy at most E people.

For each of them, one vehicle leaves the city at each integer time (time 0, 1, 2, ...).

There is a group of N people at City 1, and they all want to go to City 6.

At least how long does it take for all of them to reach there?
You can ignore the time needed to transfer.

Constraints

1 \leq N, A, B, C, D, E \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A
B
C
D
E

Output

Print the minimum time required for all of the people to reach City 6, in minutes.

Sample Input 1

5
3
2
4
3
5

Sample Output 1

7

One possible way to travel is as follows.
First, there are N = 5 people at City 1, as shown in the following image:

In the first minute, three people travels from City 1 to City 2 by train. Note that a train can only occupy at most three people.

In the second minute, the remaining two people travels from City 1 to City 2 by train, and two of the three people who were already at City 2 travels to City 3 by bus. Note that a bus can only occupy at most two people.

In the third minute, two people travels from City 2 to City 3 by train, and another two people travels from City 3 to City 4 by taxi.

From then on, if they continue traveling without stopping until they reach City 6, all of them can reach there in seven minutes.

There is no way for them to reach City 6 in 6 minutes or less.

Sample Input 2

10
123
123
123
123
123

Sample Output 2

5

All kinds of vehicles can occupy N = 10 people at a time.
Thus, if they continue traveling without stopping until they reach City 6, all of them can reach there in five minutes.

Sample Input 3

10000000007
2
3
5
7
11

Sample Output 3

5000000008

Note that the input or output may not fit into a 32-bit integer type.


function Main(input) {
  var list = input.split("\n").map(s => parseInt(s, 10));
  var min = list[1];
  var ans = 0;
  var last = 10;

  for (i = 1; i < 6; i++) {
    if (list[i] < min) min = list[i];
  }

  ans = Math.floor((list[0]-1)/min) + 5;

  console.log(ans);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
function Main(input) {
    let T = input.split("\n").map((v) => v - 0);
    let N = T[0];
    let min = Math.min(...T.slice(1, 6));
    let t = Math.ceil(N / min) + 4;
    console.log(t);
}
if (typeof window === 'undefined') Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var A = ~~input[1];
  var B = ~~input[2];
  var C = ~~input[3];
  var D = ~~input[4];
  var E = ~~input[5];

  var AtCoder = function(N,A,B,C,D,E){
    this.move = [A,B,C,D,E];
    this.memNum = N;
  };

  AtCoder.prototype = {
    procedure: function(){
      return Math.ceil(this.memNum/Math.min(...this.move))+4;
    }
  }
  var atcoder = new AtCoder(N,A,B,C,D,E);
  console.log(atcoder.procedure());
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(v)";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
function PriorityQueue(){
  this.heap = [];
}
PriorityQueue.prototype = {
  push : function(x){
    var i = this.heap.length++;
    while(i){
      var j = i - 1 >> 1;
      if(x >= this.heap[j])break;
      this.heap[i] = this.heap[j];
      i = j;
    }
    this.heap[i] = x;
  },
  pop : function(){
    var r = this.heap[0];
    var x = this.heap.pop();
    var i = 0;
    var k = this.heap.length >> 1;
    while (i < k) {
      var j = (i << 1) + 1;
      if(this.heap[j] > this.heap[j+1])++j;
      if(x <= this.heap[j])break;
      this.heap[i] = this.heap[j];
      i = j;
    }
    if(this.heap.length)this.heap[i] = x;
    return r;
  },
  size : function(){return this.heap.length;},
  top : function(){return this.heap[0];},
};

console.log(main());
function main(){
  var x = o.a();
  var y = o.a();
  var z = o.a();
  var k = o.a();
  var a = o.l().sort((a,b)=>b-a);
  var b = o.l().sort((a,b)=>b-a);
  var c = o.l().sort((a,b)=>b-a);
  var pq = new PriorityQueue();
  for(var i = 0; i < x; i++){
    for(var j = 0; j < y; j++){
      var p = a[i] + b[j];
      if(pq.size() === k){
        var t = pq.top();
        if(p <= t)break;
        pq.push(p);
        pq.pop();
      }else pq.push(p);
    }
  }
  var pq2 = new PriorityQueue();
  while(pq.size()){
    var q = pq.pop();
    for(var i = 0; i < z; i++){
      var p = q + c[i];
      if(pq2.size() === k){
        var t = pq.top();
        if(p <= t)break;
        pq2.push(p);
        pq2.pop();
      }else pq2.push(p);
    }
  }
  var ans = [];
  for(var i = 0; i < k; i++)ans.push(pq2.pop());
  return ans.reverse().join("\n");
}

Score: 400 points

Problem Statement

The Patisserie AtCoder sells cakes with number-shaped candles.
There are X, Y and Z kinds of cakes with 1-shaped, 2-shaped and 3-shaped candles, respectively.
Each cake has an integer value called deliciousness, as follows:

The deliciousness of the cakes with 1-shaped candles are A_1, A_2, ..., A_X.

The deliciousness of the cakes with 2-shaped candles are B_1, B_2, ..., B_Y.

The deliciousness of the cakes with 3-shaped candles are C_1, C_2, ..., C_Z.

Takahashi decides to buy three cakes, one for each of the three shapes of the candles, to celebrate ABC 123.

There are X \times Y \times Z such ways to choose three cakes.

We will arrange these X \times Y \times Z ways in descending order of the sum of the deliciousness of the cakes.

Print the sums of the deliciousness of the cakes for the first, second, ..., K-th ways in this list.

Constraints

1 \leq X \leq 1 \ 000

1 \leq Y \leq 1 \ 000

1 \leq Z \leq 1 \ 000

1 \leq K \leq \min(3 \ 000, X \times Y \times Z)

1 \leq A_i \leq 10 \ 000 \ 000 \ 000

1 \leq B_i \leq 10 \ 000 \ 000 \ 000

1 \leq C_i \leq 10 \ 000 \ 000 \ 000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y Z K
A_1 \ A_2 \ A_3 \ ... \ A_X
B_1 \ B_2 \ B_3 \ ... \ B_Y
C_1 \ C_2 \ C_3 \ ... \ C_Z

Output

Print K lines. The i-th line should contain the i-th value stated in the problem statement.

Sample Input 1

2 2 2 8
4 6
1 5
3 8

Sample Output 1

19
17
15
14
13
12
10
8

There are 2 \times 2 \times 2 = 8 ways to choose three cakes, as shown below in descending order of the sum of the deliciousness of the cakes:

(A_2, B_2, C_2): 6 + 5 + 8 = 19

(A_1, B_2, C_2): 4 + 5 + 8 = 17

(A_2, B_1, C_2): 6 + 1 + 8 = 15

(A_2, B_2, C_1): 6 + 5 + 3 = 14

(A_1, B_1, C_2): 4 + 1 + 8 = 13

(A_1, B_2, C_1): 4 + 5 + 3 = 12

(A_2, B_1, C_1): 6 + 1 + 3 = 10

(A_1, B_1, C_1): 4 + 1 + 3 = 8

Sample Input 2

3 3 3 5
1 10 100
2 20 200
1 10 100

Sample Output 2

400
310
310
301
301

There may be multiple combinations of cakes with the same sum of the deliciousness. For example, in this test case, the sum of A_1, B_3, C_3 and the sum of A_3, B_3, C_1 are both 301.
However, they are different ways of choosing cakes, so 301 occurs twice in the output.

Sample Input 3

10 10 10 20
7467038376 5724769290 292794712 2843504496 3381970101 8402252870 249131806 6310293640 6690322794 6082257488
1873977926 2576529623 1144842195 1379118507 6003234687 4925540914 3902539811 3326692703 484657758 2877436338
4975681328 8974383988 2882263257 7690203955 514305523 6679823484 4263279310 585966808 3752282379 620585736

Sample Output 3

23379871545
22444657051
22302177772
22095691512
21667941469
21366963278
21287912315
21279176669
21160477018
21085311041
21059876163
21017997739
20703329561
20702387965
20590247696
20383761436
20343962175
20254073196
20210218542
20150096547

Note that the input or output may not fit into a 32-bit integer type.


"use strict";
function I(s,f){this._s=s.split("\n");this._c=0;this._l=0;this._f=f||Number}I.prototype.a=function(){var l=this._s[this._l];if(!l)return;var t=l.trim().split(" ");var a=t[this._c];this._c++;if(t.length===this._c){this._c=0;this._l++}return this._f(a)};I.prototype.l=function(){var l=this._s[this._l];if(!l)return;this._c=0;this._l++;return l.split(" ").map(this._f)};

function main(input) {
  const o = new I(input);

  var x = o.a();
  var y = o.a();
  var z = o.a();
  var k = o.a();

  var a = o.l();
  var b = o.l();
  var c = o.l();

  a.sort((a,b) => b-a);
  b.sort((a,b) => b-a);
  c.sort((a,b) => b-a);

  var ta = a[0] - a[1];
  var tb = b[0] - b[1];
  var tc = c[0] - c[1];

  var ai = 1, bi = 1, ci = 1;
  var count = (ai + 1) * (bi + 1) * (ci + 1);

  while (count < k) {
    if ( ta <= tb && ta <= tc) {
      ai += 1;
    } else if ( tb <= tc) {
      bi += 1;
    } else {
      ci += 1;
    }

    ta = (ai === a.length - 1) ? Infinity : a[0] - a[ai];
    tb = (bi === b.length - 1) ? Infinity : b[0] - b[bi];
    tc = (ci === c.length - 1) ? Infinity : c[0] - c[ci];
    count = (ai + 1) * (bi + 1) * (ci + 1);
  }

  var tm = Math.max(ta + tb, tb + tc, tc + ta);

  while (a[0] - a[ai] <= tm && ai < a.length) {
    ai += 1;
  }
  if ( ai === a.length) ai -= 1;
  while (b[0] - b[bi] <= tm && bi < b.length) {
    bi += 1;
  }
  if ( bi === b.length) bi -= 1;

  while (c[0] - c[ci] <= tm  && ci < c.length) {
    ci += 1;
  }
  if ( ci === c.length) ci -= 1;

  var results = [];
  for(var ak = 0; ak <= ai; ak++){
    for(var bk = 0; bk <= bi; bk++){
      for(var ck = 0; ck <= ci; ck++){
        results.push(a[ak] + b[bk] + c[ck]);
      }
    }
  }

  results.sort((a,b)=> b - a);
  for(let i=0; i < k; i++) {
    console.log(results[i])
  }
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  var red=0;
  var text = input[1];
  for(var i = 0; i < text.length; i++){
    red += (text[i] == "R" ? 1:-1);
  }
  console.log(red > 0 ? "Yes": "No");
}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());

Score : 200 points

Problem Statement

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

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

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

Constraints

1 \leq N \leq 100

|s| = N

s_i is R or B.

Input

Input is given from Standard Input in the following format:

N
s

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.


function main(input) {
    const row = input.split("\n")
    const n = parseInt(row[0])
    const s = row[1]
    let r = 0
    let b = 0
    for (let i = 0; i < s.length; i++) {
        const c = s.slice(i, i+1)
        if (c === 'R') r++
        if (c === 'B') b++
    }

    if (r > b) {
        console.log("Yes")
    } else {
        console.log("No")
    }
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  var lines = input.split("\n");
  var N = Number(lines[0].split(" ")[0])
  var Q = Number(lines[0].split(" ")[1]);
  var str = lines[1];
  var table = [];
  var map = {};
  for(var i=0;i<=N+1;i++){
    if(i==0 || i==N+1){
      table[i]={count:0};
    }else{
      table[i]={count:1, i: i};
      if(!map[str[i-1]]) map[str[i-1]] = [];
      map[str[i-1]].push(table[i]);
    }
  }
  for(var j=2;j<Q+2;j++){
    var t = lines[j].split(" ")[0];
    var d = lines[j].split(" ")[1];
    var movet = map[t];
    if(!movet) continue;
    if(d=="R"){
      for(var i=movet.length-1;i>=0;i--){
        var ii = movet[i].i;
        var mvc = table[ii].count;
        table[ii+1].count+=mvc;
        table[ii].count=0;
      }
    }else{
      for(var i=0;i<movet.length;i++){
        var ii = movet[i].i;
        var mvc = table[ii].count;
        table[ii-1].count+=mvc;
        table[ii].count=0;
      }
    }
  }
  console.log(N-table[0].count-table[N+1].count);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))

Score : 500 points

Problem Statement

There are N squares numbered 1 to N from left to right.
Each square has a character written on it, and Square i has a letter s_i. Besides, there is initially one golem on each square.

Snuke cast Q spells to move the golems.

The i-th spell consisted of two characters t_i and d_i, where d_i is L or R.
When Snuke cast this spell, for each square with the character t_i, all golems on that square moved to the square adjacent to the left if d_i is L, and moved to the square adjacent to the right if d_i is R.

However, when a golem tried to move left from Square 1 or move right from Square N, it disappeared.

Find the number of golems remaining after Snuke cast the Q spells.

Constraints

1 \leq N,Q \leq 2 \times 10^{5}

|s| = N

s_i and t_i are uppercase English letters.

d_i is L or R.

Input

Input is given from Standard Input in the following format:

N Q
s
t_1 d_1
\vdots
t_{Q} d_Q

Output

Print the answer.

Sample Input 1

3 4
ABC
A L
B L
B R
A R

Sample Output 1

2

Initially, there is one golem on each square.

In the first spell, the golem on Square 1 tries to move left and disappears.

In the second spell, the golem on Square 2 moves left.

In the third spell, no golem moves.

In the fourth spell, the golem on Square 1 moves right.

After the four spells are cast, there is one golem on Square 2 and one golem on Square 3, for a total of two golems remaining.

Sample Input 2

8 3
AABCBDBA
A L
B R
A R

Sample Output 2

5

After the three spells are cast, there is one golem on Square 2, two golems on Square 4 and two golems on Square 6, for a total of five golems remaining.

Note that a single spell may move multiple golems.

Sample Input 3

10 15
SNCZWRCEWB
B R
R R
E R
W R
Z L
S R
Q L
W L
B R
C L
A L
N L
E R
Z L
S L

Sample Output 3

3


"use strict";

// read lines from stdin
const input = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .split("\n");

const firstLine = input[0].split(" ").map((val) => parseInt(val, 10));
const N = firstLine[0];
const Q = firstLine[1];

const S = input[1];
const golems = new Array(N).fill(1);

let left = 0;
let right = N - 1;

for (let i = Q + 1; i > 1; i--) {
  const spell = input[i].split(" ");
  const t = spell[0];
  const d = spell[1];

  if (S.charAt(left) === t && d === "L") {
    left++;
  } else if (S.charAt(right) === t && d === "R") {
    right--;
  }
}

console.log(left <= right ? N - (left + (N - 1 - right)) : 0);


var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(v)";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
var mod = 1e9+7;
function abmod(){for(var a=arguments,r=a[0],i=1;i<a.length;)r=((r>>16)*a[i]%mod*65536+(r&65535)*a[i++])%mod;return r;}

console.log(main());
function main(){
  var n = o.a();
  var x = o.a();
  var s = o.l().sort((a,b)=>b-a);
  var dp = Array(x+1).fill(0);
  dp[x] = 1;
  for(var i = 0; i < n; i++){
    var dp2 = Array(x+1).fill(0);
    for(var j = 0; j <= x; j++){
      dp2[j] += dp[j] * (n-i-1);
      dp2[j] %= mod;
      var m = j % s[i];
      dp2[m] += dp[j];
      dp2[m] %= mod;
    }
    dp = dp2;
  }
  var ans = 0;
  for(i = 0; i < s[n-1]; i++){
    ans += abmod(i,dp[i]);
  }
  return ans % mod;
}

Score : 600 points

Problem Statement

Snuke has a blackboard and a set S consisting of N integers.
The i-th element in S is S_i.

He wrote an integer X on the blackboard, then performed the following operation N times:

Choose one element from S and remove it.

Let x be the number written on the blackboard now, and y be the integer removed from S. Replace the number on the blackboard with x \bmod {y}.

There are N! possible orders in which the elements are removed from S.
For each of them, find the number that would be written on the blackboard after the N operations, and compute the sum of all those N! numbers modulo 10^{9}+7.

Constraints

All values in input are integers.

1 \leq N \leq 200

1 \leq S_i, X \leq 10^{5}

S_i are pairwise distinct.

Input

Input is given from Standard Input in the following format:

N X
S_1 S_2 \ldots S_{N}

Output

Print the answer.

Sample Input 1

2 19
3 7

Sample Output 1

3

There are two possible orders in which we remove the numbers from S.

If we remove 3 and 7 in this order, the number on the blackboard changes as follows: 19 \rightarrow 1 \rightarrow 1.

If we remove 7 and 3 in this order, the number on the blackboard changes as follows: 19 \rightarrow 5 \rightarrow 2.

The output should be the sum of these: 3.

Sample Input 2

5 82
22 11 6 5 13

Sample Output 2

288

Sample Input 3

10 100000
50000 50001 50002 50003 50004 50005 50006 50007 50008 50009

Sample Output 3

279669259

Be sure to compute the sum modulo 10^{9}+7.


"use strict";

// read lines from stdin
const input = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .split("\n");

const firstLine = input[0].split(" ").map((val) => parseInt(val, 10));
const N = firstLine[0];
const X = firstLine[1];

const S = input[1].split(" ").map((val) => parseInt(val, 10));

function sumMod(X, ary) {
  let sum = 0;

  if (ary.length === 1) {
    return X % ary[0];
  }

  for (let i = 0; i < ary.length; i++) {
    const num = ary[i];
    const nextX = X % num;

    sum += sumMod(nextX, ary.slice(0, i).concat(ary.slice(i + 1, ary.length)));
  }

  return sum %= 1000000000 + 7;
}

console.log(sumMod(X, S));


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
b = lines.shift()
s = {
    A: 'T',
    C: 'G',
    G: 'C',
    T: 'A'
}
console.log(s[b])

Score : 100 points

Problem Statement

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

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

Constraints

b is one of the letters A, C, G and T.

Input

Input is given from Standard Input in the following format:

b

Output

Print the letter representing the base that bonds with the base b.

Sample Input 1

A

Sample Output 1

T

Sample Input 2

G

Sample Output 2

C


// inputに入力データ全体が入る
function Main(input) {
  switch(input){
    case 'A':
      console.log('T');
    case 'T':
      console.log('A');
    case 'G':
      console.log('C');
    case 'C':
      console.log('G');
  }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
    var a = "";
  if("A" === input){
    a = "T";
  }else if("T" === input){
    a = "A";
  }else if("G" === input){
    a = "C";
  }else
    a = "G";
  }
	//出力
	console.log(a);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  var output = {
    A: 'T',
    T: 'A',
    C: 'G',
    G: 'C'
  };
  console.log(output[input]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


b = require('fs').readFileSync('/dev/stdin', 'utf8');

r =
b == 'A' ? 'T':
b == 'T' ? 'A':
b == 'C' ? 'G': 'C';

console.log(r);


function Main(input){
  S = input.trim().split('');
  count = 0;
  max_count = 0;
  S.forEach((ch)=>{
    if(ch === 'A' || ch === 'T' || ch === 'G' || ch === 'C'){
      count++;
    }else{
      max_count = count > max_count ? count : max_count;
      count = 0;
    }
  });
  console.log(count > max_count ? count : max_count);
}

Main(require("fs").readFileSync("/dev/stdin","utf-8"));

Score : 200 points

Problem Statement

You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.

Here, a ACGT string is a string that contains no characters other than A, C, G and T.

Notes

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

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

Constraints

S is a string of length between 1 and 10 (inclusive).

Each character in S is an uppercase English letter.

Input

Input is given from Standard Input in the following format:

S

Output

Print the length of the longest ACGT string that is a substring of S.

Sample Input 1

ATCODER

Sample Output 1

3

Among the ACGT strings that are substrings of ATCODER, the longest one is ATC.

Sample Input 2

HATAGAYA

Sample Output 2

5

Among the ACGT strings that are substrings of HATAGAYA, the longest one is ATAGA.

Sample Input 3

SHINJUKU

Sample Output 3

0

Among the ACGT strings that are substrings of SHINJUKU, the longest one is (the empty string).


function Main(input) {
    input = input.replace(/[^ACGT]/g,"_");
    input = input.split("_");
    var len = 0
    for(var i of input){
      if(len < i.length)len = i.length
    }
    console.log(len)
    return 0
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.split("\n");
var q=arr[0].split(" ").map(Number)[1];
var s = arr[1];
var a=[0,0];
var cnt=0;
for(var i=1;i<s.length;i++){
   if(s[i]=="C" && s[i-1]=="A")cnt++;
   a.push(cnt);
}
var ans=[];
while(ans.length < q) {
   var lr=arr[ans.length+2].split(" ");
   ans.push(a[parseInt(lr[1])]-a[parseInt(lr[0])]);
}
console.log(ans.join("\n"));

Score : 300 points

Problem Statement

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

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

Notes

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

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

Constraints

2 \leq N \leq 10^5

1 \leq Q \leq 10^5

S is a string of length N.

Each character in S is A, C, G or T.

1 \leq l_i < r_i \leq N

Input

Input is given from Standard Input in the following format:

N Q
S
l_1 r_1
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

8 3
ACACTACG
3 7
2 3
1 8

Sample Output 1

2
0
3

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

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

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


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.split("\n");
var nq=arr[0].split(" ").map(Number);
var str = arr[1];
var a=[0,0];
var cnt=0;
for(var i=1;i<str.length;i++){
   if(str[i]=="C" && str[i-1]=="A")cnt++;
   a.push(cnt);
}
var ans=[];
for(var i=2;i<nq[1]+2;i++){
   var lr=arr[i].split(" ");
   ans.push(a[lr[1]-0]-a[lr[0]-0]);
}
console.log(ans.join("\n"));


function Main(input){

  var str = input.trim().split("\n");
  var nq = str[0].split(" ");
  var n = nq[0];
  var q = nq[1];
  var s = str[1];
  var lr = str;
  lr.splice(0,2);

  //console.log("l:"+lr[0].split(" ")[0]);
  //console.log("l:"+lr[0].split(" ")[1]);

  var s = s.replace(/AC/g,"aC");

//console.log("S:"+s);

  for(i=0;i<q;i++){
      var kaisu = 0;
    var tmps = s.substring(lr[i].split(" ")[0]-1,lr[i].split(" ")[1]);
    var kaisu = str_count(tmps,"a");
    console.log(kaisu);

  }//for end

  function str_count(all, part) {
    return (all.match(new RegExp(part, "g")) || []).length;
}

}//function end

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {

  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var Q = parseInt(input[0].split(" ")[1]);
  var S = input[1];

  var l = Array(input.length-2);
  var r = Array(input.length-2);

  for(var i = 2; i < input.length; i ++){
    l[i-2] = parseInt(input[i].split(" ")[0]);
    r[i-2] = parseInt(input[i].split(" ")[1]);
  }

  var AtCoder = function(){
    this.dp = Array(N+1).fill(0);
  };

  AtCoder.prototype = {
    procedure: function(){
      for(let i = 0; i < N; i++){
        this.dp[i] = S.substring(0,i).split("AC").length -1;
      }
      this.dp[N] = this.dp[N-1];
      debugger;
      for(let i = 0; i < Q; i++){
        console.log(this.dp[r[i]]-this.dp[l[i]]);
      }
    }
  }
  var atcoder = new AtCoder();
  atcoder.procedure();
}
// try{
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// }catch(e){
//   var input=``
//   Main(input);
// }


function Main(input) {
    // console.log(input);

    const N = parseInt(input[0].split(" ")[0]);
    const Q = parseInt(input[0].split(" ")[1]);
    const S = input[1];

    var ctArr = new Array(N-1);

    for(var i = 0; i < N-1; i++) {
        if(S[i] == "A" && S[i+1] == "C") {
            ctArr[i]=true;
        }
    }

    for(var i = 2; i < input.length; i++) {
        var l = input[i].split(" ")[0];
        var r = input[i].split(" ")[1];
        console.log(ctArr.slice(l-1, r-1).filter(function(val){
            return val;
        }).length);
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n"));


"use strict";

const main = arg => {
    const N  = parseInt(arg.split("\n")[0].split(" ")[0]);
    const Q  = parseInt(arg.split("\n")[0].split(" ")[1]);
    const S  = arg.split("\n")[1].split("");
    //const lr = arg.split("\n").slice(2, N + 1);
    let dp = [0, 0];
    let cnt = 0;

    for(let i=2; i<=N; i++) {
        if(S[i-2] === "A" && S[i-1] === "C") {
            dp.push(dp[i-1] + 1);
        } else {
            dp.push(dp[i-1]);
        }
    }

    for(let i=0; i<Q; i++) {
        let lr = arg.split("\n")[i+2].split(" ");
        let l = lr[0];
        let r = lr[1];

        console.log(dp[r]-dp[l]);
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input) => {
  const inputs = input.trim().split("\n");
  const N = Number(inputs[0].split(" ")[0]);
  const Q = Number(inputs[0].split(" ")[1]);
  const S = inputs[1];

  for(var i=2;i<inputs.length;i++){
    var l = Number(inputs[i].split(" ")[0]);
    var r = Number(inputs[i].split(" ")[1]);
    var trg = S.substring(l-1,r);
    var ans = trg.match(/AC/g);
    if(ans){
      console.log(trg.match(/AC/g).length);
    }else{
      console.log(0);
    }
  }

}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8'));


function Main(input) {
    const inputs = input.split('\n');
    const whiteH = Number(inputs[0].split(' ')[0]);
    const whiteW = Number(inputs[0].split(' ')[1]);
    const blackH = Number(inputs[1].split(' ')[0]);
    const blackW = Number(inputs[1].split(' ')[1]);

    console.log(whiteH * whiteW - (blackH * whiteW + blackW * whiteH) + (blackW * blackH));
};

Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

There are H rows and W columns of white square cells.

You will choose h of the rows and w of the columns, and paint all of the cells contained in those rows or columns.

How many white cells will remain?

It can be proved that this count does not depend on what rows and columns are chosen.

Constraints

All values in input are integers.

1 \leq H, W \leq 20

1 \leq h \leq H

1 \leq w \leq W

Input

Input is given from Standard Input in the following format:

H W
h w

Output

Print the number of white cells that will remain.

Sample Input 1

3 2
2 1

Sample Output 1

1

There are 3 rows and 2 columns of cells. When two rows and one column are chosen and painted in black, there is always one white cell that remains.

Sample Input 2

5 5
2 3

Sample Output 2

6

Sample Input 3

2 4
2 4

Sample Output 3

0


'use strict'

class Main {
  solve() {
    const size = input.nextIntArr();
    const nums = input.nextIntArr();
    console.log((size[0] - nums[0]) * (size[1] - nums[1]));
  }
}

class Input {
  constructor() {
	this.cursor = 0;
	this.inputAll();
  }

  inputAll() {
	this.data = (require("fs").readFileSync("/dev/stdin", "utf8")).split('\n');
	return this.data;
  }

  nextLine(n) {
	if (n) {
	  const ret = this.data.slice(this.cursor, this.cursor + n);
	  this.cursor += n;
	  return ret;
	}
	return this.data[this.cursor++];
  }

  nextStrArr() {
	return this.nextLine().split(' ');
  }

  nextIntArr() {
	return this.nextStrArr().map((e) => parseInt(e));
  }

  nextFloatArr() {
	return this.nextStrArr().map((e) => parseFloat(e));
  }

  nextIntLine(n) {
	return this.nextLine(n).map((e) => parseInt(e))
  }

  nextFloatLine(n) {
	return this.nextLine(n).map((e) => parseFloat(e))
  }

  nextStrRange(n) {
	return this.nextLine(n).map((line) => line.split(' '));
  }

  nextIntRange(n) {
	return this.nextLine(n).map((line) => line.split(' ').map((e) => parseInt(e)));
  }

  nextFloatRange(n) {
	return this.nextLine(n).map((line) => line.split(' ').map((e) => parseFloat(e)));
  }
}

const input = new Input();
(new Main()).solve();


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
line = lines.shift().split(' ')
N = line[0] * 1
M = line[1] * 1
C = line[2] * 1
B = lines.shift().split(' ')
cnt = 0
for (i=0;i<N;i++) {
    line = lines[i].split(' ')
    sum = 0
    for (j=0;j<M;j++) {
        sum += line[j] * B[j]
    }
    if (sum + C > 0) {
        cnt++
    }
}
console.log(cnt)

Score : 200 points

Problem Statement

There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.

Additionally, you are given integers B_1, B_2, ..., B_M and C.

The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.

Among the N codes, find the number of codes that correctly solve this problem.

Constraints

All values in input are integers.

1 \leq N, M \leq 20

-100 \leq A_{ij} \leq 100

-100 \leq B_i \leq 100

-100 \leq C \leq 100

Input

Input is given from Standard Input in the following format:

N M C
B_1 B_2 ... B_M
A_{11} A_{12} ... A_{1M}
A_{21} A_{22} ... A_{2M}
\vdots
A_{N1} A_{N2} ... A_{NM}

Output

Print the number of codes among the given N codes that correctly solve this problem.

Sample Input 1

2 3 -10
1 2 3
3 2 1
1 2 2

Sample Output 1

1

Only the second code correctly solves this problem, as follows:

Since 3 \times 1 + 2 \times 2 + 1 \times 3 + (-10) = 0 \leq 0, the first code does not solve this problem.

1 \times 1 + 2 \times 2 + 2 \times 3 + (-10) = 1 > 0, the second code solves this problem.

Sample Input 2

5 2 -4
-2 5
100 41
100 40
-3 0
-6 -2
18 -13

Sample Output 2

2

Sample Input 3

3 3 0
100 -100 0
0 100 100
100 100 100
-100 100 100

Sample Output 3

0

All of them are Wrong Answer. Except yours.


Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.


'use strict'

function Main(input){
	let temp = input.trim().split("\n");
	let NM = temp[0].split(" ").map( (v)=>(parseInt(v)) );
	//let AB = new Array(NM[0]);
	//for(let i=0;i<NM[0];i++){
	//	AB[i] = temp[i+1].split(" ").map( (v)=>(parseInt(v)) );
	//}

	let AB = [];
	for(let i=0;i<NM[0];i++){
		let a = Number(temp[i+1].split(" ")[0]);
		let b = Number(temp[i+1].split(" ")[1]);
		AB.push([a,b]);
	}
	AB.sort((a,b)=>(a[0] < b[0]?-1:1));

	let money = 0;
	let count = NM[1];
	for(let i=0;count>0;i++){
		var num = Math.min(count,AB[i][1]);
		money += num*AB[i][0];
		count -= num;
	}
	console.log(money);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

function Main(input) {
    input = input.split("\n");

    input[0] = input[0].split(" ");
    const n = parseInt(input[0][0], 10);
    const m = parseInt(input[0][1], 10);

    let stores = input.slice(1, -1).map(x => x.split(" ").map(x => parseInt(x, 10)));

    stores.sort(function(a, b) {
        return a[0] - b[0];
    });

    let numDrink = 0;
    let totalPrice = 0;
    for (let i = 0; i < n; i++) {
        const store = stores[i];
        for (let j = 0; j < store[1]; j++) {
            if (numDrink === m) {
                console.log(totalPrice);
                return;
            }

            numDrink++;
            totalPrice += store[0];
        }
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
    const args = input.split('\n');
    var one = args[0].split(' ');

    var N = parseInt(one[0], 10);
    var M = parseInt(one[1], 10);
    var purchase_count = 0;
    var purchase_money = 0;

    // 店情報
    var shop_info = {
        Money: '',
        Max_count: ''
    };

    var shops_info = [];

    for (var i = 0; i < N; i++) {
        Drinks = args[i + 1].split(' ');
        shops_info[i] = { Money: parseInt(Drinks[0], 10), Max_count: parseInt(Drinks[1], 10)}
    }

    shops_info.sort((a, b) => { return (a.Money < b.Money) ? -1 : 1;})

    var target_shop;

    for (var i = 0; i < N; i++) {
        target_shop = shops_info[i]
        if(target_shop.Max_count + purchase_count <= M) {
            purchase_money += target_shop.Max_count * target_shop.Money;
            purchase_count += target_shop.Max_count;
        } else {
            target_count = M - purchase_count;
            purchase_money += target_shop.Money * target_count;
            break;
            }
        }

    console.log(purchase_money);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";

const main = arg => {
    const A = parseInt(arg.split("\n")[0].split(" ")[0]);
    const B = parseInt(arg.split("\n")[0].split(" ")[1]);
    const K = parseInt(arg.split("\n")[0].split(" ")[2]);
    const list = [];

    for(let i=1; i<=Math.min(A,B); i++) {
        if(A % i == 0 && B % i == 0) {
            list.push(i);
        }
    }

    console.log(list[list.length - K]);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

You are given positive integers A and B.

Find the K-th largest positive integer that divides both A and B.

The input guarantees that there exists such a number.

Constraints

All values in input are integers.

1 \leq A, B \leq 100

The K-th largest positive integer that divides both A and B exists.

K \geq 1

Input

Input is given from Standard Input in the following format:

A B K

Output

Print the K-th largest positive integer that divides both A and B.

Sample Input 1

8 12 2

Sample Output 1

2

Three positive integers divides both 8 and 12: 1, 2 and 4.
Among them, the second largest is 2.

Sample Input 2

100 50 4

Sample Output 2

5

Sample Input 3

1 1 1

Sample Output 3

1


input = require('fs').readFileSync('/dev/stdin', 'utf8')
lines = input.split('\n')
S = lines.shift()
cnt = 0
while(m = S.match(/(01|10)/g)) {
    cnt += m.length * 2
    S = S.replace(/(01|10)/g, '')
}
console.log(cnt)

Score : 300 points

Problem Statement

There are N cubes stacked vertically on a desk.

You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is 0, and blue if that character is 1.

You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent, and remove them. Here, the cubes that were stacked on the removed cubes will fall down onto the object below them.

At most how many cubes can be removed?

Constraints

1 \leq N \leq 10^5

|S| = N

Each character in S is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of cubes that can be removed.

Sample Input 1

0011

Sample Output 1

4

All four cubes can be removed, by performing the operation as follows:

Remove the second and third cubes from the bottom. Then, the fourth cube drops onto the first cube.

Remove the first and second cubes from the bottom.

Sample Input 2

11011010001011

Sample Output 2

12

Sample Input 3

0

Sample Output 3

0


// 配列に全部の島のデータを突っ込む
// 各島はparent,sizeから成る、自分がどの島かはインデックスで判断。

function UnionFind(n){
  this.islands = [];
  for(var i=0; i<n; i++){
    this.islands[i] = {
      parent: i,
      size: 1,
    }
  }
}

UnionFind.prototype.same_group = function(left_index, right_index){
  const right_root = this.root(right_index);
  const left_root = this.root(left_index);
  return (right_root == left_root);
}

UnionFind.prototype.merge_islands = function(left_index, right_index){
  if(this.same_group(left_index, right_index)){return;}
  const right_root = this.root(right_index);
  const left_root = this.root(left_index);
  left_root.size = left_root.size + right_root.size;
  right_root.parent = left_index;
}

UnionFind.prototype.root = function(index){

  if(this.islands[index] != index){
    var parent_node = this.root(this.islands[index].parent);
    this.islands[index].parent = parent_node.parent;
    return parent_node;
  }
  return this.islands[index];

//  var node = this.islands[index];

  if(this.islands[index].parent==index){return this.islands[index];}

  var root_node = this.root(this.islands[index].parent);
  this.islands[index].parent = root_node.parent;
  return root_node;
}

UnionFind.prototype.get_size = function(index){
  var root_node = this.root(index);
  return root_node.size;
}

function main(input) {
  const formatted_input = input.split('\n').map( x => x.split(' ').map( x => parseInt(x, 10) ) );
  const N = formatted_input[0][0];
  const M = formatted_input[0][1];
  var reverse_bridges = [];

  for(var i=0;i<M;i++){
    reverse_bridges.push(formatted_input[1+i]);
  }
  reverse_bridges = reverse_bridges.reverse();

  var uf = new UnionFind(N)

  var unconvinience = N*(N-1)/2;
  var results = [unconvinience];

  for(bridge of reverse_bridges){
    //console.log(bridge);

    left_index = bridge[0]-1
    right_index =  bridge[1]-1

    if(!uf.same_group(left_index, right_index)){
      var diff = uf.get_size((left_index)) * uf.get_size(right_index);
      unconvinience -= diff;
    }
    results.push(unconvinience);

    uf.merge_islands(left_index, right_index);
  }

  const reversed_result = results.reverse();

  for(var i = 1; i<=M ; i++){
    console.log(reversed_result[i]);
  }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

//02:05:00 >

Score : 400 points

Problem Statement

There are N islands and M bridges.

The i-th bridge connects the A_i-th and B_i-th islands bidirectionally.

Initially, we can travel between any two islands using some of these bridges.

However, the results of a survey show that these bridges will all collapse because of aging, in the order from the first bridge to the M-th bridge.

Let the inconvenience be the number of pairs of islands (a, b) (a < b) such that we are no longer able to travel between the a-th and b-th islands using some of the bridges remaining.

For each i (1 \leq i \leq M), find the inconvenience just after the i-th bridge collapses.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i < B_i \leq N

All pairs (A_i, B_i) are distinct.

The inconvenience is initially 0.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_M B_M

Output

In the order i = 1, 2, ..., M, print the inconvenience just after the i-th bridge collapses.
Note that the answer may not fit into a 32-bit integer type.

Sample Input 1

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

Sample Output 1

0
0
4
5
6

For example, when the first to third bridges have collapsed, the inconvenience is 4 since we can no longer travel between the pairs (1, 2), (1, 3), (2, 4) and (3, 4).

Sample Input 2

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

Sample Output 2

8
9
12
14
15

Sample Input 3

2 1
1 2

Sample Output 3

1


function Main(input) {
	input = new Date(input).getTime();
    var check = new Date("2019/04/30").getTime();
   console.log((input <= check) ? "Heisei" : "TBD");
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

You are given a string S as input. This represents a valid date in the year 2019 in the yyyy/mm/dd format. (For example, April 30, 2019 is represented as 2019/04/30.)

Write a program that prints Heisei if the date represented by S is not later than April 30, 2019, and prints TBD otherwise.

Constraints

S is a string that represents a valid date in the year 2019 in the yyyy/mm/dd format.

Input

Input is given from Standard Input in the following format:

S

Output

Print Heisei if the date represented by S is not later than April 30, 2019, and print TBD otherwise.

Sample Input 1

2019/04/30

Sample Output 1

Heisei

Sample Input 2

2019/11/01

Sample Output 2

TBD


function Main(input){
    var inputs = input.split(" ");
    var date = inputs.shift();
	if(date > "2019/04/30"){
    console.log("TBD");
    }else{
    console.log("Heisei");
    }
}

Main(require("fs").readFileSync("/dev/stdin","utf8"));


a = require("fs").readFileSync("/dev/stdin", "utf8").split('/').map(Number);
console.log(a[0] >= 2019 && a[1] >= 5 ? 'TBD' : 'Heisei');


let main = (standardInput) => {
  let date = standardInput.split('/').join('')
  if (Number(date) >= 20190430) console.log('TBD')
  else console.log('Heisei')
}

main(require('fs').readFileSync('/dev/stdin', 'UTF-8'))


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  const N = Number.parseInt(inputStr[0]);
  const A = Number.parseInt(inputStr[1]);
  const B = Number.parseInt(inputStr[2]);
  const C = Number.parseInt(inputStr[3]);
  var tg = [A,B,C];
  var bb = [];
  //N本の竹の長さを配列bbに格納する
  for( var i=0 ; i<N ; i++ ){
    bb.push(Number.parseInt(input[i+1].split(" ")));
  }
  bb.push(Number.MAX_VALUE);
  //竹を成長させる探索処理
  var MP = 0;

  //console.log("最初",bb);

  //長さが一致する竹を対象一覧(配列tg、bb)から排除する
  for(var i=0 ; i<tg.length ; i++){
    var tmp = bb.indexOf(tg[i]);
    if(tmp>0){
      tg.splice(i,1);
      bb.splice(tmp,1);
    }
  }

  //console.log("排除",tg);

  //育った要素から順にtgから削除していく。
  var iposi = 0;

  while( tg.length > 0){
    for(var i=0 ; i<tg.length ; i++ ){
      //最も近似する場所を求める
      var t1 = Number.MAX_VALUE;
      var pmemo = [0,0];
      for( var j=0 ; j<bb.length ; j++){
        var t2 = Math.abs(tg[i]-bb[j]);
        if( t1 > t2 ){
          t1 = t2;
          iposi = i;
          pmemo[0] = j;
        }
      }

      //2本の竹を足して再度考えてみる
      if(t1>10){
        var c_flg = false;
        for(var k=0 ; k<bb.length-1 ; k++){
          for(var r=k+1 ; r<bb.length ; r++){
            t2 = Math.abs(tg[i]-(bb[k]+bb[r]));
            if( t1 > t2 ){
              t1 = t2;
              pmemo[0] = k;
              pmemo[1] = r;
              iposi = i;
              c_flg = true;
            }
          }
        }
      }
    }

    //絶対値との差異(t1)をMPとして足しこみ、bbから要素を削除する
    if(c_flg === true){
      //console.log("2本を1本に");
      MP += 10;
      //最後の1つ手前に追加
      bb.splice(bb.length-1,0,bb[pmemo[0]]+bb[pmemo[1]]);
      //追加した元ねたの削除
      bb.splice(pmemo[1],1);
      bb.splice(pmemo[0],1);
    } else {
      MP += t1;
      tg.splice(iposi,1);
      //console.log("bbから消す値=",bb[pmemo[0]]);

      //console.log("bbの何処の値を消す",pmemo[0]);

      bb.splice(pmemo[0],1);
      i++;
    }
    //console.log("処理後tg",tg);
    //console.log("処理後bb",bb);
    c_flg = false;
    pmemo[0]=0;
    pmemo[1]=0;
    iposi = 0;
  }
  console.log(MP);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.

Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:

Extension Magic: Consumes 1 MP (magic point). Choose one bamboo and increase its length by 1.

Shortening Magic: Consumes 1 MP. Choose one bamboo of length at least 2 and decrease its length by 1.

Composition Magic: Consumes 10 MP. Choose two bamboos and combine them into one bamboo. The length of this new bamboo is equal to the sum of the lengths of the two bamboos combined. (Afterwards, further magics can be used on this bamboo.)

At least how much MP is needed to achieve the objective?

Constraints

3 \leq N \leq 8

1 \leq C < B < A \leq 1000

1 \leq l_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C
l_1
l_2
:
l_N

Output

Print the minimum amount of MP needed to achieve the objective.

Sample Input 1

5 100 90 80
98
40
30
21
80

Sample Output 1

23

We are obtaining three bamboos of lengths 100, 90, 80 from five bamboos 98, 40, 30, 21, 80. We already have a bamboo of length 80, and we can obtain bamboos of lengths 100, 90 by using the magics as follows at the total cost of 23 MP, which is optimal.

Use Extension Magic twice on the bamboo of length 98 to obtain a bamboo of length 100. (MP consumed: 2)

Use Composition Magic on the bamboos of lengths 40, 30 to obtain a bamboo of length 70. (MP consumed: 10)

Use Shortening Magic once on the bamboo of length 21 to obtain a bamboo of length 20. (MP consumed: 1)

Use Composition Magic on the bamboo of length 70 obtained in step 2 and the bamboo of length 20 obtained in step 3 to obtain a bamboo of length 90. (MP consumed: 10)

Sample Input 2

8 100 90 80
100
100
90
90
90
80
80
80

Sample Output 2

0

If we already have all bamboos of the desired lengths, the amount of MP needed is 0. As seen here, we do not necessarily need to use all the bamboos.

Sample Input 3

8 1000 800 100
300
333
400
444
500
555
600
666

Sample Output 3

243


"use strict";
function binarySearch(array, value) {
    let start = 0;
    let stop = array.length - 1;
    let middle = Math.floor((start + stop) / 2);
    while (array[middle] !== value && start < stop) {
        if (value < array[middle]) {
            stop = middle - 1;
        } else {
            start = middle + 1;
        }
        middle = Math.floor((start + stop) / 2);
    }
    if (array[middle] > value) return middle;
    if (array[middle] < value) return middle + 1;
    return (array[middle] !== value) ? middle + 1 : middle;
}
function Main(input) {
    const INF = Number.MAX_SAFE_INTEGER;
    let lines = input.split("\n");
    let ABQ = lines.shift().split(/\s/).map((v) => v - 0);
    let A = ABQ[0];
    let B = ABQ[1];
    let Q = ABQ[2];
    let s = [-INF];
    for (let a = 1; a <= A; a++) {
        s.push(lines.shift() - 0);
    }
    s.push(INF);
    let t = [-INF];
    for (let b = 1; b <= B; b++) {
        t.push(lines.shift() - 0);
    }
    t.push(INF);
    const min = (a, b, c) => {
        return Math.min(a, Math.min(b, c));
    }
    for (let q = 0; q < Q; q++) {
        let x = lines.shift() - 0;
        let b = binarySearch(s, x);
        let d = binarySearch(t, x);
        let res = INF;
        for (let S of [s[b - 1], s[b]]) {
            for (let T of [t[d - 1], t[d]]) {
                const d1 = Math.abs(S - x) + Math.abs(T - S);
                const d2 = Math.abs(T - x) + Math.abs(S - T);
                res = min(res, d1, d2);
            }
        }
        console.log(res);
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.


"use strict";
function I(s,f){this._s=s.split("\n");this._c=0;this._l=0;this._f=f||Number}I.prototype.a=function(){var l=this._s[this._l];if(!l)return;var t=l.trim().split(" ");var a=t[this._c];this._c++;if(t.length===this._c){this._c=0;this._l++}return this._f(a)};I.prototype.l=function(){var l=this._s[this._l];if(!l)return;this._c=0;this._l++;return l.split(" ").map(this._f)};module.exports=I;
var bigInt=function(undefined){"use strict";var BASE=1e7,LOG_BASE=7,MAX_INT=9007199254740992,MAX_INT_ARR=smallToArray(MAX_INT),DEFAULT_ALPHABET="0123456789abcdefghijklmnopqrstuvwxyz";var supportsNativeBigInt=typeof BigInt==="function";function Integer(v,radix,alphabet,caseSensitive){if(typeof v==="undefined")return Integer[0];if(typeof radix!=="undefined")return+radix===10&&!alphabet?parseValue(v):parseBase(v,radix,alphabet,caseSensitive);return parseValue(v)}function BigInteger(value,sign){this.value=value;this.sign=sign;this.isSmall=false}BigInteger.prototype=Object.create(Integer.prototype);function SmallInteger(value){this.value=value;this.sign=value<0;this.isSmall=true}SmallInteger.prototype=Object.create(Integer.prototype);function NativeBigInt(value){this.value=value}NativeBigInt.prototype=Object.create(Integer.prototype);function isPrecise(n){return-MAX_INT<n&&n<MAX_INT}function smallToArray(n){if(n<1e7)return[n];if(n<1e14)return[n%1e7,Math.floor(n/1e7)];return[n%1e7,Math.floor(n/1e7)%1e7,Math.floor(n/1e14)]}function arrayToSmall(arr){trim(arr);var length=arr.length;if(length<4&&compareAbs(arr,MAX_INT_ARR)<0){switch(length){case 0:return 0;case 1:return arr[0];case 2:return arr[0]+arr[1]*BASE;default:return arr[0]+(arr[1]+arr[2]*BASE)*BASE}}return arr}function trim(v){var i=v.length;while(v[--i]===0);v.length=i+1}function createArray(length){var x=new Array(length);var i=-1;while(++i<length){x[i]=0}return x}function truncate(n){if(n>0)return Math.floor(n);return Math.ceil(n)}function add(a,b){var l_a=a.length,l_b=b.length,r=new Array(l_a),carry=0,base=BASE,sum,i;for(i=0;i<l_b;i++){sum=a[i]+b[i]+carry;carry=sum>=base?1:0;r[i]=sum-carry*base}while(i<l_a){sum=a[i]+carry;carry=sum===base?1:0;r[i++]=sum-carry*base}if(carry>0)r.push(carry);return r}function addAny(a,b){if(a.length>=b.length)return add(a,b);return add(b,a)}function addSmall(a,carry){var l=a.length,r=new Array(l),base=BASE,sum,i;for(i=0;i<l;i++){sum=a[i]-base+carry;carry=Math.floor(sum/base);r[i]=sum-carry*base;carry+=1}while(carry>0){r[i++]=carry%base;carry=Math.floor(carry/base)}return r}BigInteger.prototype.add=function(v){var n=parseValue(v);if(this.sign!==n.sign){return this.subtract(n.negate())}var a=this.value,b=n.value;if(n.isSmall){return new BigInteger(addSmall(a,Math.abs(b)),this.sign)}return new BigInteger(addAny(a,b),this.sign)};BigInteger.prototype.plus=BigInteger.prototype.add;SmallInteger.prototype.add=function(v){var n=parseValue(v);var a=this.value;if(a<0!==n.sign){return this.subtract(n.negate())}var b=n.value;if(n.isSmall){if(isPrecise(a+b))return new SmallInteger(a+b);b=smallToArray(Math.abs(b))}return new BigInteger(addSmall(b,Math.abs(a)),a<0)};SmallInteger.prototype.plus=SmallInteger.prototype.add;NativeBigInt.prototype.add=function(v){return new NativeBigInt(this.value+parseValue(v).value)};NativeBigInt.prototype.plus=NativeBigInt.prototype.add;function subtract(a,b){var a_l=a.length,b_l=b.length,r=new Array(a_l),borrow=0,base=BASE,i,difference;for(i=0;i<b_l;i++){difference=a[i]-borrow-b[i];if(difference<0){difference+=base;borrow=1}else borrow=0;r[i]=difference}for(i=b_l;i<a_l;i++){difference=a[i]-borrow;if(difference<0)difference+=base;else{r[i++]=difference;break}r[i]=difference}for(;i<a_l;i++){r[i]=a[i]}trim(r);return r}function subtractAny(a,b,sign){var value;if(compareAbs(a,b)>=0){value=subtract(a,b)}else{value=subtract(b,a);sign=!sign}value=arrayToSmall(value);if(typeof value==="number"){if(sign)value=-value;return new SmallInteger(value)}return new BigInteger(value,sign)}function subtractSmall(a,b,sign){var l=a.length,r=new Array(l),carry=-b,base=BASE,i,difference;for(i=0;i<l;i++){difference=a[i]+carry;carry=Math.floor(difference/base);difference%=base;r[i]=difference<0?difference+base:difference}r=arrayToSmall(r);if(typeof r==="number"){if(sign)r=-r;return new SmallInteger(r)}return new BigInteger(r,sign)}BigInteger.prototype.subtract=function(v){var n=parseValue(v);if(this.sign!==n.sign){return this.add(n.negate())}var a=this.value,b=n.value;if(n.isSmall)return subtractSmall(a,Math.abs(b),this.sign);return subtractAny(a,b,this.sign)};BigInteger.prototype.minus=BigInteger.prototype.subtract;SmallInteger.prototype.subtract=function(v){var n=parseValue(v);var a=this.value;if(a<0!==n.sign){return this.add(n.negate())}var b=n.value;if(n.isSmall){return new SmallInteger(a-b)}return subtractSmall(b,Math.abs(a),a>=0)};SmallInteger.prototype.minus=SmallInteger.prototype.subtract;NativeBigInt.prototype.subtract=function(v){return new NativeBigInt(this.value-parseValue(v).value)};NativeBigInt.prototype.minus=NativeBigInt.prototype.subtract;BigInteger.prototype.negate=function(){return new BigInteger(this.value,!this.sign)};SmallInteger.prototype.negate=function(){var sign=this.sign;var small=new SmallInteger(-this.value);small.sign=!sign;return small};NativeBigInt.prototype.negate=function(){return new NativeBigInt(-this.value)};BigInteger.prototype.abs=function(){return new BigInteger(this.value,false)};SmallInteger.prototype.abs=function(){return new SmallInteger(Math.abs(this.value))};NativeBigInt.prototype.abs=function(){return new NativeBigInt(this.value>=0?this.value:-this.value)};function multiplyLong(a,b){var a_l=a.length,b_l=b.length,l=a_l+b_l,r=createArray(l),base=BASE,product,carry,i,a_i,b_j;for(i=0;i<a_l;++i){a_i=a[i];for(var j=0;j<b_l;++j){b_j=b[j];product=a_i*b_j+r[i+j];carry=Math.floor(product/base);r[i+j]=product-carry*base;r[i+j+1]+=carry}}trim(r);return r}function multiplySmall(a,b){var l=a.length,r=new Array(l),base=BASE,carry=0,product,i;for(i=0;i<l;i++){product=a[i]*b+carry;carry=Math.floor(product/base);r[i]=product-carry*base}while(carry>0){r[i++]=carry%base;carry=Math.floor(carry/base)}return r}function shiftLeft(x,n){var r=[];while(n-- >0)r.push(0);return r.concat(x)}function multiplyKaratsuba(x,y){var n=Math.max(x.length,y.length);if(n<=30)return multiplyLong(x,y);n=Math.ceil(n/2);var b=x.slice(n),a=x.slice(0,n),d=y.slice(n),c=y.slice(0,n);var ac=multiplyKaratsuba(a,c),bd=multiplyKaratsuba(b,d),abcd=multiplyKaratsuba(addAny(a,b),addAny(c,d));var product=addAny(addAny(ac,shiftLeft(subtract(subtract(abcd,ac),bd),n)),shiftLeft(bd,2*n));trim(product);return product}function useKaratsuba(l1,l2){return-.012*l1-.012*l2+15e-6*l1*l2>0}BigInteger.prototype.multiply=function(v){var n=parseValue(v),a=this.value,b=n.value,sign=this.sign!==n.sign,abs;if(n.isSmall){if(b===0)return Integer[0];if(b===1)return this;if(b===-1)return this.negate();abs=Math.abs(b);if(abs<BASE){return new BigInteger(multiplySmall(a,abs),sign)}b=smallToArray(abs)}if(useKaratsuba(a.length,b.length))return new BigInteger(multiplyKaratsuba(a,b),sign);return new BigInteger(multiplyLong(a,b),sign)};BigInteger.prototype.times=BigInteger.prototype.multiply;function multiplySmallAndArray(a,b,sign){if(a<BASE){return new BigInteger(multiplySmall(b,a),sign)}return new BigInteger(multiplyLong(b,smallToArray(a)),sign)}SmallInteger.prototype._multiplyBySmall=function(a){if(isPrecise(a.value*this.value)){return new SmallInteger(a.value*this.value)}return multiplySmallAndArray(Math.abs(a.value),smallToArray(Math.abs(this.value)),this.sign!==a.sign)};BigInteger.prototype._multiplyBySmall=function(a){if(a.value===0)return Integer[0];if(a.value===1)return this;if(a.value===-1)return this.negate();return multiplySmallAndArray(Math.abs(a.value),this.value,this.sign!==a.sign)};SmallInteger.prototype.multiply=function(v){return parseValue(v)._multiplyBySmall(this)};SmallInteger.prototype.times=SmallInteger.prototype.multiply;NativeBigInt.prototype.multiply=function(v){return new NativeBigInt(this.value*parseValue(v).value)};NativeBigInt.prototype.times=NativeBigInt.prototype.multiply;function square(a){var l=a.length,r=createArray(l+l),base=BASE,product,carry,i,a_i,a_j;for(i=0;i<l;i++){a_i=a[i];carry=0-a_i*a_i;for(var j=i;j<l;j++){a_j=a[j];product=2*(a_i*a_j)+r[i+j]+carry;carry=Math.floor(product/base);r[i+j]=product-carry*base}r[i+l]=carry}trim(r);return r}BigInteger.prototype.square=function(){return new BigInteger(square(this.value),false)};SmallInteger.prototype.square=function(){var value=this.value*this.value;if(isPrecise(value))return new SmallInteger(value);return new BigInteger(square(smallToArray(Math.abs(this.value))),false)};NativeBigInt.prototype.square=function(v){return new NativeBigInt(this.value*this.value)};function divMod1(a,b){var a_l=a.length,b_l=b.length,base=BASE,result=createArray(b.length),divisorMostSignificantDigit=b[b_l-1],lambda=Math.ceil(base/(2*divisorMostSignificantDigit)),remainder=multiplySmall(a,lambda),divisor=multiplySmall(b,lambda),quotientDigit,shift,carry,borrow,i,l,q;if(remainder.length<=a_l)remainder.push(0);divisor.push(0);divisorMostSignificantDigit=divisor[b_l-1];for(shift=a_l-b_l;shift>=0;shift--){quotientDigit=base-1;if(remainder[shift+b_l]!==divisorMostSignificantDigit){quotientDigit=Math.floor((remainder[shift+b_l]*base+remainder[shift+b_l-1])/divisorMostSignificantDigit)}carry=0;borrow=0;l=divisor.length;for(i=0;i<l;i++){carry+=quotientDigit*divisor[i];q=Math.floor(carry/base);borrow+=remainder[shift+i]-(carry-q*base);carry=q;if(borrow<0){remainder[shift+i]=borrow+base;borrow=-1}else{remainder[shift+i]=borrow;borrow=0}}while(borrow!==0){quotientDigit-=1;carry=0;for(i=0;i<l;i++){carry+=remainder[shift+i]-base+divisor[i];if(carry<0){remainder[shift+i]=carry+base;carry=0}else{remainder[shift+i]=carry;carry=1}}borrow+=carry}result[shift]=quotientDigit}remainder=divModSmall(remainder,lambda)[0];return[arrayToSmall(result),arrayToSmall(remainder)]}function divMod2(a,b){var a_l=a.length,b_l=b.length,result=[],part=[],base=BASE,guess,xlen,highx,highy,check;while(a_l){part.unshift(a[--a_l]);trim(part);if(compareAbs(part,b)<0){result.push(0);continue}xlen=part.length;highx=part[xlen-1]*base+part[xlen-2];highy=b[b_l-1]*base+b[b_l-2];if(xlen>b_l){highx=(highx+1)*base}guess=Math.ceil(highx/highy);do{check=multiplySmall(b,guess);if(compareAbs(check,part)<=0)break;guess--}while(guess);result.push(guess);part=subtract(part,check)}result.reverse();return[arrayToSmall(result),arrayToSmall(part)]}function divModSmall(value,lambda){var length=value.length,quotient=createArray(length),base=BASE,i,q,remainder,divisor;remainder=0;for(i=length-1;i>=0;--i){divisor=remainder*base+value[i];q=truncate(divisor/lambda);remainder=divisor-q*lambda;quotient[i]=q|0}return[quotient,remainder|0]}function divModAny(self,v){var value,n=parseValue(v);if(supportsNativeBigInt){return[new NativeBigInt(self.value/n.value),new NativeBigInt(self.value%n.value)]}var a=self.value,b=n.value;var quotient;if(b===0)throw new Error("Cannot divide by zero");if(self.isSmall){if(n.isSmall){return[new SmallInteger(truncate(a/b)),new SmallInteger(a%b)]}return[Integer[0],self]}if(n.isSmall){if(b===1)return[self,Integer[0]];if(b==-1)return[self.negate(),Integer[0]];var abs=Math.abs(b);if(abs<BASE){value=divModSmall(a,abs);quotient=arrayToSmall(value[0]);var remainder=value[1];if(self.sign)remainder=-remainder;if(typeof quotient==="number"){if(self.sign!==n.sign)quotient=-quotient;return[new SmallInteger(quotient),new SmallInteger(remainder)]}return[new BigInteger(quotient,self.sign!==n.sign),new SmallInteger(remainder)]}b=smallToArray(abs)}var comparison=compareAbs(a,b);if(comparison===-1)return[Integer[0],self];if(comparison===0)return[Integer[self.sign===n.sign?1:-1],Integer[0]];if(a.length+b.length<=200)value=divMod1(a,b);else value=divMod2(a,b);quotient=value[0];var qSign=self.sign!==n.sign,mod=value[1],mSign=self.sign;if(typeof quotient==="number"){if(qSign)quotient=-quotient;quotient=new SmallInteger(quotient)}else quotient=new BigInteger(quotient,qSign);if(typeof mod==="number"){if(mSign)mod=-mod;mod=new SmallInteger(mod)}else mod=new BigInteger(mod,mSign);return[quotient,mod]}BigInteger.prototype.divmod=function(v){var result=divModAny(this,v);return{quotient:result[0],remainder:result[1]}};NativeBigInt.prototype.divmod=SmallInteger.prototype.divmod=BigInteger.prototype.divmod;BigInteger.prototype.divide=function(v){return divModAny(this,v)[0]};NativeBigInt.prototype.over=NativeBigInt.prototype.divide=SmallInteger.prototype.over=SmallInteger.prototype.divide=BigInteger.prototype.over=BigInteger.prototype.divide;BigInteger.prototype.mod=function(v){return divModAny(this,v)[1]};NativeBigInt.prototype.mod=NativeBigInt.prototype.remainder=SmallInteger.prototype.remainder=SmallInteger.prototype.mod=BigInteger.prototype.remainder=BigInteger.prototype.mod;BigInteger.prototype.pow=function(v){var n=parseValue(v),a=this.value,b=n.value,value,x,y;if(b===0)return Integer[1];if(a===0)return Integer[0];if(a===1)return Integer[1];if(a===-1)return n.isEven()?Integer[1]:Integer[-1];if(n.sign){return Integer[0]}if(!n.isSmall)throw new Error("The exponent "+n.toString()+" is too large.");if(this.isSmall){if(isPrecise(value=Math.pow(a,b)))return new SmallInteger(truncate(value))}x=this;y=Integer[1];while(true){if(b&1===1){y=y.times(x);--b}if(b===0)break;b/=2;x=x.square()}return y};SmallInteger.prototype.pow=BigInteger.prototype.pow;var pow;if(supportsNativeBigInt){pow=eval("(a,b)=>a**b")}NativeBigInt.prototype.pow=function(v){var n=parseValue(v);var a=this.value,b=n.value;if(b===BigInt(0))return Integer[1];if(a===BigInt(0))return Integer[0];if(a===BigInt(1))return Integer[1];if(a===BigInt(-1))return n.isEven()?Integer[1]:Integer[-1];if(n.isNegative())return new NativeBigInt(BigInt(0));return new NativeBigInt(pow(a,b))};BigInteger.prototype.modPow=function(exp,mod){exp=parseValue(exp);mod=parseValue(mod);if(mod.isZero())throw new Error("Cannot take modPow with modulus 0");var r=Integer[1],base=this.mod(mod);while(exp.isPositive()){if(base.isZero())return Integer[0];if(exp.isOdd())r=r.multiply(base).mod(mod);exp=exp.divide(2);base=base.square().mod(mod)}return r};NativeBigInt.prototype.modPow=SmallInteger.prototype.modPow=BigInteger.prototype.modPow;function compareAbs(a,b){if(a.length!==b.length){return a.length>b.length?1:-1}for(var i=a.length-1;i>=0;i--){if(a[i]!==b[i])return a[i]>b[i]?1:-1}return 0}BigInteger.prototype.compareAbs=function(v){var n=parseValue(v),a=this.value,b=n.value;if(n.isSmall)return 1;return compareAbs(a,b)};SmallInteger.prototype.compareAbs=function(v){var n=parseValue(v),a=Math.abs(this.value),b=n.value;if(n.isSmall){b=Math.abs(b);return a===b?0:a>b?1:-1}return-1};NativeBigInt.prototype.compareAbs=function(v){var a=this.value;var b=parseValue(v).value;a=a>=0?a:-a;b=b>=0?b:-b;return a===b?0:a>b?1:-1};BigInteger.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var n=parseValue(v),a=this.value,b=n.value;if(this.sign!==n.sign){return n.sign?1:-1}if(n.isSmall){return this.sign?-1:1}return compareAbs(a,b)*(this.sign?-1:1)};BigInteger.prototype.compareTo=BigInteger.prototype.compare;SmallInteger.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var n=parseValue(v),a=this.value,b=n.value;if(n.isSmall){return a==b?0:a>b?1:-1}if(a<0!==n.sign){return a<0?-1:1}return a<0?1:-1};SmallInteger.prototype.compareTo=SmallInteger.prototype.compare;NativeBigInt.prototype.compare=function(v){if(v===Infinity){return-1}if(v===-Infinity){return 1}var a=this.value;var b=parseValue(v).value;return a===b?0:a>b?1:-1};NativeBigInt.prototype.compareTo=NativeBigInt.prototype.compare;BigInteger.prototype.equals=function(v){return this.compare(v)===0};NativeBigInt.prototype.eq=NativeBigInt.prototype.equals=SmallInteger.prototype.eq=SmallInteger.prototype.equals=BigInteger.prototype.eq=BigInteger.prototype.equals;BigInteger.prototype.notEquals=function(v){return this.compare(v)!==0};NativeBigInt.prototype.neq=NativeBigInt.prototype.notEquals=SmallInteger.prototype.neq=SmallInteger.prototype.notEquals=BigInteger.prototype.neq=BigInteger.prototype.notEquals;BigInteger.prototype.greater=function(v){return this.compare(v)>0};NativeBigInt.prototype.gt=NativeBigInt.prototype.greater=SmallInteger.prototype.gt=SmallInteger.prototype.greater=BigInteger.prototype.gt=BigInteger.prototype.greater;BigInteger.prototype.lesser=function(v){return this.compare(v)<0};NativeBigInt.prototype.lt=NativeBigInt.prototype.lesser=SmallInteger.prototype.lt=SmallInteger.prototype.lesser=BigInteger.prototype.lt=BigInteger.prototype.lesser;BigInteger.prototype.greaterOrEquals=function(v){return this.compare(v)>=0};NativeBigInt.prototype.geq=NativeBigInt.prototype.greaterOrEquals=SmallInteger.prototype.geq=SmallInteger.prototype.greaterOrEquals=BigInteger.prototype.geq=BigInteger.prototype.greaterOrEquals;BigInteger.prototype.lesserOrEquals=function(v){return this.compare(v)<=0};NativeBigInt.prototype.leq=NativeBigInt.prototype.lesserOrEquals=SmallInteger.prototype.leq=SmallInteger.prototype.lesserOrEquals=BigInteger.prototype.leq=BigInteger.prototype.lesserOrEquals;BigInteger.prototype.isEven=function(){return(this.value[0]&1)===0};SmallInteger.prototype.isEven=function(){return(this.value&1)===0};NativeBigInt.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)};BigInteger.prototype.isOdd=function(){return(this.value[0]&1)===1};SmallInteger.prototype.isOdd=function(){return(this.value&1)===1};NativeBigInt.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)};BigInteger.prototype.isPositive=function(){return!this.sign};SmallInteger.prototype.isPositive=function(){return this.value>0};NativeBigInt.prototype.isPositive=SmallInteger.prototype.isPositive;BigInteger.prototype.isNegative=function(){return this.sign};SmallInteger.prototype.isNegative=function(){return this.value<0};NativeBigInt.prototype.isNegative=SmallInteger.prototype.isNegative;BigInteger.prototype.isUnit=function(){return false};SmallInteger.prototype.isUnit=function(){return Math.abs(this.value)===1};NativeBigInt.prototype.isUnit=function(){return this.abs().value===BigInt(1)};BigInteger.prototype.isZero=function(){return false};SmallInteger.prototype.isZero=function(){return this.value===0};NativeBigInt.prototype.isZero=function(){return this.value===BigInt(0)};BigInteger.prototype.isDivisibleBy=function(v){var n=parseValue(v);if(n.isZero())return false;if(n.isUnit())return true;if(n.compareAbs(2)===0)return this.isEven();return this.mod(n).isZero()};NativeBigInt.prototype.isDivisibleBy=SmallInteger.prototype.isDivisibleBy=BigInteger.prototype.isDivisibleBy;function isBasicPrime(v){var n=v.abs();if(n.isUnit())return false;if(n.equals(2)||n.equals(3)||n.equals(5))return true;if(n.isEven()||n.isDivisibleBy(3)||n.isDivisibleBy(5))return false;if(n.lesser(49))return true}function millerRabinTest(n,a){var nPrev=n.prev(),b=nPrev,r=0,d,t,i,x;while(b.isEven())b=b.divide(2),r++;next:for(i=0;i<a.length;i++){if(n.lesser(a[i]))continue;x=bigInt(a[i]).modPow(b,n);if(x.isUnit()||x.equals(nPrev))continue;for(d=r-1;d!=0;d--){x=x.square().mod(n);if(x.isUnit())return false;if(x.equals(nPrev))continue next}return false}return true}BigInteger.prototype.isPrime=function(strict){var isPrime=isBasicPrime(this);if(isPrime!==undefined)return isPrime;var n=this.abs();var bits=n.bitLength();if(bits<=64)return millerRabinTest(n,[2,325,9375,28178,450775,9780504,1795265022]);var logN=Math.log(2)*bits.toJSNumber();var t=Math.ceil(strict===true?2*Math.pow(logN,2):logN);for(var a=[],i=0;i<t;i++){a.push(bigInt(i+2))}return millerRabinTest(n,a)};NativeBigInt.prototype.isPrime=SmallInteger.prototype.isPrime=BigInteger.prototype.isPrime;BigInteger.prototype.isProbablePrime=function(iterations){var isPrime=isBasicPrime(this);if(isPrime!==undefined)return isPrime;var n=this.abs();var t=iterations===undefined?5:iterations;for(var a=[],i=0;i<t;i++){a.push(bigInt.randBetween(2,n.minus(2)))}return millerRabinTest(n,a)};NativeBigInt.prototype.isProbablePrime=SmallInteger.prototype.isProbablePrime=BigInteger.prototype.isProbablePrime;BigInteger.prototype.modInv=function(n){var t=bigInt.zero,newT=bigInt.one,r=parseValue(n),newR=this.abs(),q,lastT,lastR;while(!newR.isZero()){q=r.divide(newR);lastT=t;lastR=r;t=newT;r=newR;newT=lastT.subtract(q.multiply(newT));newR=lastR.subtract(q.multiply(newR))}if(!r.isUnit())throw new Error(this.toString()+" and "+n.toString()+" are not co-prime");if(t.compare(0)===-1){t=t.add(n)}if(this.isNegative()){return t.negate()}return t};NativeBigInt.prototype.modInv=SmallInteger.prototype.modInv=BigInteger.prototype.modInv;BigInteger.prototype.next=function(){var value=this.value;if(this.sign){return subtractSmall(value,1,this.sign)}return new BigInteger(addSmall(value,1),this.sign)};SmallInteger.prototype.next=function(){var value=this.value;if(value+1<MAX_INT)return new SmallInteger(value+1);return new BigInteger(MAX_INT_ARR,false)};NativeBigInt.prototype.next=function(){return new NativeBigInt(this.value+BigInt(1))};BigInteger.prototype.prev=function(){var value=this.value;if(this.sign){return new BigInteger(addSmall(value,1),true)}return subtractSmall(value,1,this.sign)};SmallInteger.prototype.prev=function(){var value=this.value;if(value-1>-MAX_INT)return new SmallInteger(value-1);return new BigInteger(MAX_INT_ARR,true)};NativeBigInt.prototype.prev=function(){return new NativeBigInt(this.value-BigInt(1))};var powersOfTwo=[1];while(2*powersOfTwo[powersOfTwo.length-1]<=BASE)powersOfTwo.push(2*powersOfTwo[powersOfTwo.length-1]);var powers2Length=powersOfTwo.length,highestPower2=powersOfTwo[powers2Length-1];function shift_isSmall(n){return Math.abs(n)<=BASE}BigInteger.prototype.shiftLeft=function(v){var n=parseValue(v).toJSNumber();if(!shift_isSmall(n)){throw new Error(String(n)+" is too large for shifting.")}if(n<0)return this.shiftRight(-n);var result=this;if(result.isZero())return result;while(n>=powers2Length){result=result.multiply(highestPower2);n-=powers2Length-1}return result.multiply(powersOfTwo[n])};NativeBigInt.prototype.shiftLeft=SmallInteger.prototype.shiftLeft=BigInteger.prototype.shiftLeft;BigInteger.prototype.shiftRight=function(v){var remQuo;var n=parseValue(v).toJSNumber();if(!shift_isSmall(n)){throw new Error(String(n)+" is too large for shifting.")}if(n<0)return this.shiftLeft(-n);var result=this;while(n>=powers2Length){if(result.isZero()||result.isNegative()&&result.isUnit())return result;remQuo=divModAny(result,highestPower2);result=remQuo[1].isNegative()?remQuo[0].prev():remQuo[0];n-=powers2Length-1}remQuo=divModAny(result,powersOfTwo[n]);return remQuo[1].isNegative()?remQuo[0].prev():remQuo[0]};NativeBigInt.prototype.shiftRight=SmallInteger.prototype.shiftRight=BigInteger.prototype.shiftRight;function bitwise(x,y,fn){y=parseValue(y);var xSign=x.isNegative(),ySign=y.isNegative();var xRem=xSign?x.not():x,yRem=ySign?y.not():y;var xDigit=0,yDigit=0;var xDivMod=null,yDivMod=null;var result=[];while(!xRem.isZero()||!yRem.isZero()){xDivMod=divModAny(xRem,highestPower2);xDigit=xDivMod[1].toJSNumber();if(xSign){xDigit=highestPower2-1-xDigit}yDivMod=divModAny(yRem,highestPower2);yDigit=yDivMod[1].toJSNumber();if(ySign){yDigit=highestPower2-1-yDigit}xRem=xDivMod[0];yRem=yDivMod[0];result.push(fn(xDigit,yDigit))}var sum=fn(xSign?1:0,ySign?1:0)!==0?bigInt(-1):bigInt(0);for(var i=result.length-1;i>=0;i-=1){sum=sum.multiply(highestPower2).add(bigInt(result[i]))}return sum}BigInteger.prototype.not=function(){return this.negate().prev()};NativeBigInt.prototype.not=SmallInteger.prototype.not=BigInteger.prototype.not;BigInteger.prototype.and=function(n){return bitwise(this,n,function(a,b){return a&b})};NativeBigInt.prototype.and=SmallInteger.prototype.and=BigInteger.prototype.and;BigInteger.prototype.or=function(n){return bitwise(this,n,function(a,b){return a|b})};NativeBigInt.prototype.or=SmallInteger.prototype.or=BigInteger.prototype.or;BigInteger.prototype.xor=function(n){return bitwise(this,n,function(a,b){return a^b})};NativeBigInt.prototype.xor=SmallInteger.prototype.xor=BigInteger.prototype.xor;var LOBMASK_I=1<<30,LOBMASK_BI=(BASE&-BASE)*(BASE&-BASE)|LOBMASK_I;function roughLOB(n){var v=n.value,x=typeof v==="number"?v|LOBMASK_I:typeof v==="bigint"?v|BigInt(LOBMASK_I):v[0]+v[1]*BASE|LOBMASK_BI;return x&-x}function integerLogarithm(value,base){if(base.compareTo(value)<=0){var tmp=integerLogarithm(value,base.square(base));var p=tmp.p;var e=tmp.e;var t=p.multiply(base);return t.compareTo(value)<=0?{p:t,e:e*2+1}:{p:p,e:e*2}}return{p:bigInt(1),e:0}}BigInteger.prototype.bitLength=function(){var n=this;if(n.compareTo(bigInt(0))<0){n=n.negate().subtract(bigInt(1))}if(n.compareTo(bigInt(0))===0){return bigInt(0)}return bigInt(integerLogarithm(n,bigInt(2)).e).add(bigInt(1))};NativeBigInt.prototype.bitLength=SmallInteger.prototype.bitLength=BigInteger.prototype.bitLength;function max(a,b){a=parseValue(a);b=parseValue(b);return a.greater(b)?a:b}function min(a,b){a=parseValue(a);b=parseValue(b);return a.lesser(b)?a:b}function gcd(a,b){a=parseValue(a).abs();b=parseValue(b).abs();if(a.equals(b))return a;if(a.isZero())return b;if(b.isZero())return a;var c=Integer[1],d,t;while(a.isEven()&&b.isEven()){d=min(roughLOB(a),roughLOB(b));a=a.divide(d);b=b.divide(d);c=c.multiply(d)}while(a.isEven()){a=a.divide(roughLOB(a))}do{while(b.isEven()){b=b.divide(roughLOB(b))}if(a.greater(b)){t=b;b=a;a=t}b=b.subtract(a)}while(!b.isZero());return c.isUnit()?a:a.multiply(c)}function lcm(a,b){a=parseValue(a).abs();b=parseValue(b).abs();return a.divide(gcd(a,b)).multiply(b)}function randBetween(a,b){a=parseValue(a);b=parseValue(b);var low=min(a,b),high=max(a,b);var range=high.subtract(low).add(1);if(range.isSmall)return low.add(Math.floor(Math.random()*range));var digits=toBase(range,BASE).value;var result=[],restricted=true;for(var i=0;i<digits.length;i++){var top=restricted?digits[i]:BASE;var digit=truncate(Math.random()*top);result.push(digit);if(digit<top)restricted=false}return low.add(Integer.fromArray(result,BASE,false))}var parseBase=function(text,base,alphabet,caseSensitive){alphabet=alphabet||DEFAULT_ALPHABET;text=String(text);if(!caseSensitive){text=text.toLowerCase();alphabet=alphabet.toLowerCase()}var length=text.length;var i;var absBase=Math.abs(base);var alphabetValues={};for(i=0;i<alphabet.length;i++){alphabetValues[alphabet[i]]=i}for(i=0;i<length;i++){var c=text[i];if(c==="-")continue;if(c in alphabetValues){if(alphabetValues[c]>=absBase){if(c==="1"&&absBase===1)continue;throw new Error(c+" is not a valid digit in base "+base+".")}}}base=parseValue(base);var digits=[];var isNegative=text[0]==="-";for(i=isNegative?1:0;i<text.length;i++){var c=text[i];if(c in alphabetValues)digits.push(parseValue(alphabetValues[c]));else if(c==="<"){var start=i;do{i++}while(text[i]!==">"&&i<text.length);digits.push(parseValue(text.slice(start+1,i)))}else throw new Error(c+" is not a valid character")}return parseBaseFromArray(digits,base,isNegative)};function parseBaseFromArray(digits,base,isNegative){var val=Integer[0],pow=Integer[1],i;for(i=digits.length-1;i>=0;i--){val=val.add(digits[i].times(pow));pow=pow.times(base)}return isNegative?val.negate():val}function stringify(digit,alphabet){alphabet=alphabet||DEFAULT_ALPHABET;if(digit<alphabet.length){return alphabet[digit]}return"<"+digit+">"}function toBase(n,base){base=bigInt(base);if(base.isZero()){if(n.isZero())return{value:[0],isNegative:false};throw new Error("Cannot convert nonzero numbers to base 0.")}if(base.equals(-1)){if(n.isZero())return{value:[0],isNegative:false};if(n.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-n.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:false};var arr=Array.apply(null,Array(n.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);arr.unshift([1]);return{value:[].concat.apply([],arr),isNegative:false}}var neg=false;if(n.isNegative()&&base.isPositive()){neg=true;n=n.abs()}if(base.isUnit()){if(n.isZero())return{value:[0],isNegative:false};return{value:Array.apply(null,Array(n.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:neg}}var out=[];var left=n,divmod;while(left.isNegative()||left.compareAbs(base)>=0){divmod=left.divmod(base);left=divmod.quotient;var digit=divmod.remainder;if(digit.isNegative()){digit=base.minus(digit).abs();left=left.next()}out.push(digit.toJSNumber())}out.push(left.toJSNumber());return{value:out.reverse(),isNegative:neg}}function toBaseString(n,base,alphabet){var arr=toBase(n,base);return(arr.isNegative?"-":"")+arr.value.map(function(x){return stringify(x,alphabet)}).join("")}BigInteger.prototype.toArray=function(radix){return toBase(this,radix)};SmallInteger.prototype.toArray=function(radix){return toBase(this,radix)};NativeBigInt.prototype.toArray=function(radix){return toBase(this,radix)};BigInteger.prototype.toString=function(radix,alphabet){if(radix===undefined)radix=10;if(radix!==10)return toBaseString(this,radix,alphabet);var v=this.value,l=v.length,str=String(v[--l]),zeros="0000000",digit;while(--l>=0){digit=String(v[l]);str+=zeros.slice(digit.length)+digit}var sign=this.sign?"-":"";return sign+str};SmallInteger.prototype.toString=function(radix,alphabet){if(radix===undefined)radix=10;if(radix!=10)return toBaseString(this,radix,alphabet);return String(this.value)};NativeBigInt.prototype.toString=SmallInteger.prototype.toString;NativeBigInt.prototype.toJSON=BigInteger.prototype.toJSON=SmallInteger.prototype.toJSON=function(){return this.toString()};BigInteger.prototype.valueOf=function(){return parseInt(this.toString(),10)};BigInteger.prototype.toJSNumber=BigInteger.prototype.valueOf;SmallInteger.prototype.valueOf=function(){return this.value};SmallInteger.prototype.toJSNumber=SmallInteger.prototype.valueOf;NativeBigInt.prototype.valueOf=NativeBigInt.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};function parseStringValue(v){if(isPrecise(+v)){var x=+v;if(x===truncate(x))return supportsNativeBigInt?new NativeBigInt(BigInt(x)):new SmallInteger(x);throw new Error("Invalid integer: "+v)}var sign=v[0]==="-";if(sign)v=v.slice(1);var split=v.split(/e/i);if(split.length>2)throw new Error("Invalid integer: "+split.join("e"));if(split.length===2){var exp=split[1];if(exp[0]==="+")exp=exp.slice(1);exp=+exp;if(exp!==truncate(exp)||!isPrecise(exp))throw new Error("Invalid integer: "+exp+" is not a valid exponent.");var text=split[0];var decimalPlace=text.indexOf(".");if(decimalPlace>=0){exp-=text.length-decimalPlace-1;text=text.slice(0,decimalPlace)+text.slice(decimalPlace+1)}if(exp<0)throw new Error("Cannot include negative exponent part for integers");text+=new Array(exp+1).join("0");v=text}var isValid=/^([0-9][0-9]*)$/.test(v);if(!isValid)throw new Error("Invalid integer: "+v);if(supportsNativeBigInt){return new NativeBigInt(BigInt(sign?"-"+v:v))}var r=[],max=v.length,l=LOG_BASE,min=max-l;while(max>0){r.push(+v.slice(min,max));min-=l;if(min<0)min=0;max-=l}trim(r);return new BigInteger(r,sign)}function parseNumberValue(v){if(supportsNativeBigInt){return new NativeBigInt(BigInt(v))}if(isPrecise(v)){if(v!==truncate(v))throw new Error(v+" is not an integer.");return new SmallInteger(v)}return parseStringValue(v.toString())}function parseValue(v){if(typeof v==="number"){return parseNumberValue(v)}if(typeof v==="string"){return parseStringValue(v)}if(typeof v==="bigint"){return new NativeBigInt(v)}return v}for(var i=0;i<1e3;i++){Integer[i]=parseValue(i);if(i>0)Integer[-i]=parseValue(-i)}Integer.one=Integer[1];Integer.zero=Integer[0];Integer.minusOne=Integer[-1];Integer.max=max;Integer.min=min;Integer.gcd=gcd;Integer.lcm=lcm;Integer.isInstance=function(x){return x instanceof BigInteger||x instanceof SmallInteger||x instanceof NativeBigInt};Integer.randBetween=randBetween;Integer.fromArray=function(digits,base,isNegative){return parseBaseFromArray(digits.map(parseValue),parseValue(base||10),isNegative)};return Integer}();if(typeof module!=="undefined"&&module.hasOwnProperty("exports")){module.exports=bigInt}if(typeof define==="function"&&define.amd){define("big-integer",[],function(){return bigInt})}

function binarySearch(arr, key, low, high) {
  if (low === high) {
    if (low === 0 && key < arr[0]) return -1;
    else return low;
  }

  const mid = Math.floor((low + high) / 2);
  if (arr[mid] < key && (!arr[mid + 1] || arr[mid + 1] > key) ) {
    return mid;
  }

  if (arr[mid] < key) {
    return binarySearch(arr, key, mid + 1, high);
  } else {
    return binarySearch(arr, key, low, mid);
  }
}

function main(input) {
  const o = new I(input);

  const A = o.a();
  const B = o.a();
  const Q = o.a();

  const s = [];
  const t = [];
  const x = [];

  for (let i=0;i<A;i++) s.push(o.a());
  for (let i=0;i<B;i++) t.push(o.a());
  for (let i=0;i<Q;i++) x.push(o.a());

  // console.log({ A, B, Q, s, t, x})

  for (let i=0;i<Q;i++) {
    let sI = binarySearch(s,x[i], 0, s.length - 1);
    let tI = binarySearch(t,x[i], 0, t.length - 1);

    let leftS = sI >= 0 ? bigInt(s[sI]) : null;
    let rightS = sI < s.length - 1 ? bigInt(s[sI + 1]) : null;
    let leftT = tI >= 0 ? bigInt(t[tI]) : null;
    let rightT = tI < t.length - 1 ? bigInt(t[tI + 1]) : null;

    let xi = bigInt(x[i]);
    // console.log({leftS: leftS && leftS.toString(), rightS: rightS && rightS.toString(), leftT: leftT && leftT.toString(), rightT:  rightT && rightT.toString()})
    let min = bigInt(999999999999);
    if (leftS && leftT) {
      let temp = xi.minus(leftS.lesser(leftT) ? leftS : leftT);
      if ( temp.compare(min) < 0 ) min = temp;
    }
    if (leftS && rightT) {
      let temp = xi.minus(leftS).plus(rightT.minus(leftS));
      if ( temp.compare(min) < 0 ) min = temp;
      temp = rightT.minus(xi).plus(rightT.minus(leftS));
      if ( temp.compare(min) < 0 ) min = temp;
    }

    if (rightS && leftT) {
      let temp = xi.minus(leftT).plus(rightS.minus(leftT));
      if ( temp.compare(min) < 0 ) min = temp;
      temp = rightS.minus(xi).plus(rightS.minus(leftT));

      if ( temp.compare(min) < 0 ) min = temp;
    }

    if (rightS && rightT) {
      let temp = rightS.greater(rightT) ? rightS : rightT;
      temp = temp.minus(xi);
      if ( temp.compare(min) < 0 ) min = temp;
    }

    console.log(min.toString());
  }

}

main(require("fs").readFileSync("/dev/stdin", "utf8"));