// inputに入力データ全体が入る
function Main(input) {
     input = input.split("\n");
  var n= parseInt(input[0], 10);
    var tmp = input[1].split(" ");
     var ar = [];
for (var i = 0; i < n ; i++){
  var r= parseInt(tmp[i], 10);
   ar[i] = r;}

 // console.log(ar);
//  console.log(n);
  if( n == 2){var z =ar[0]-ar[1];
            console.log(Math.abs(z));
            } else{

  sum = ar.reduce((a,x) => a+=x,0);
 var total = ar[0];
  var total2 = 0;
  for(i =0;i<=n;i++){  if (total < sum /2){  var total = total+ar[i+1];
                                         // console.log(total,ar[i+1]);
                                            } else{//console.log(total);
                                             var total2 = sum - total;
                                                       break;}
                    }
                    }
           //        console.log(total,total2);
  if (n = 3){z =total - total2;
                //  console.log (z);
                  console.log(Math.abs(z));}
                  else{

  P = total - total2;
                   x =( total +ar[i+2]);
                   console.log(i,ar[i]);
                   Q = x - (sum-x);
                   console.log(P,Q);
                   if (P < Q){console.log(P);}else{console.log(Q);}

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

Score : 200 points

Problem Statement

We have N weights indexed 1 to N. The mass of the weight indexed i is W_i.

We will divide these weights into two groups: the weights with indices not greater than T, and those with indices greater than T, for some integer 1 \leq T < N. Let S_1 be the sum of the masses of the weights in the former group, and S_2 be the sum of the masses of the weights in the latter group.

Consider all possible such divisions and find the minimum possible absolute difference of S_1 and S_2.

Constraints

2 \leq N \leq 100

1 \leq W_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
W_1 W_2 ... W_{N-1} W_N

Output

Print the minimum possible absolute difference of S_1 and S_2.

Sample Input 1

3
1 2 3

Sample Output 1

0

If T = 2, S_1 = 1 + 2 = 3 and S_2 = 3, with the absolute difference of 0.

Sample Input 2

4
1 3 1 1

Sample Output 2

2

If T = 2, S_1 = 1 + 3 = 4 and S_2 = 1 + 1 = 2, with the absolute difference of 2. We cannot have a smaller absolute difference.

Sample Input 3

8
27 23 76 2 3 5 62 52

Sample Output 3

2


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0]);
    const weights = arg[1].split(" ").map(n=>parseInt(n));

    let   right  = weights.reduce((m,n)=>m+n);
    let   left   = 0;
    let   answer = right;

    for(let i in weights) {
        left  += weights[i];
        right -= weights[i];
        answer = Math.min(answer, Math.abs(left - right));
    }

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

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

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.


const divider = 1e9+7;

var _fibs = [0, 1];
function fib(n) {
  for(var i = _fibs.length; i <= n; i++){
    _fibs[i] = (_fibs[i-1]%divider + _fibs[i-2]%divider)%divider;
  }
}

function fibs(n) {
  if(n<=0){return 1;}
  fib(n);
  return _fibs.slice(n, n + 1)[0];
}

function main(input){
  const lines = input.split('\n')
  const N_M = lines.shift().split(' ').map(x => parseInt(x));
  const N = N_M[0];
  const M = N_M[1];
  const A = []
  for(var i=0;i<M;i++){
    A.push(parseInt(lines.shift()));
  }

  if(M>1){
    for(var i=1;i<M;i++){
      if(A[i]-A[i-1]==1){
        console.log(0);
        return;
      }
    }
  }

  const diffs = [];
  A.unshift(-1);
  A.push(N+1);

  for(var i=1;i<M+2;i++){
    diffs.push(A[i]-A[i-1]-1)
  }

  var result = 1;

  for(diff of diffs){
//    console.log([result,diff,fibs(diff)]);
    result = (result * fibs(diff))%divider;
  }
  result = result%divider;

//  console.log(diffs);
  console.log(result);
}

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

Score : 300 points

Problem Statement

There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step.
He can climb up one or two steps at a time.

However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps.

How many are there to climb up to the top step, that is, the N-th step, without setting foot on the broken steps?
Find the count modulo 1\ 000\ 000\ 007.

Constraints

1 \leq N \leq 10^5

0 \leq M \leq N-1

1 \leq a_1 < a_2 < ... < a_M \leq N-1

Input

Input is given from Standard Input in the following format:

N M
a_1
a_2
.
.
.
a_M

Output

Print the number of ways to climb up the stairs under the condition, modulo 1\ 000\ 000\ 007.

Sample Input 1

6 1
3

Sample Output 1

4

There are four ways to climb up the stairs, as follows:

0 \to 1 \to 2 \to 4 \to 5 \to 6

0 \to 1 \to 2 \to 4 \to 6

0 \to 2 \to 4 \to 5 \to 6

0 \to 2 \to 4 \to 6

Sample Input 2

10 2
4
5

Sample Output 2

0

There may be no way to climb up the stairs without setting foot on the broken steps.

Sample Input 3

100 5
1
23
45
67
89

Sample Output 3

608200469

Be sure to print the count modulo 1\ 000\ 000\ 007.


'use strict'

function Main(input) {
  const N = Number(input.split("\n")[0].split(" ")[0])
  const M = Number(input.split("\n")[0].split(" ")[1])
  const a = input.split("\n").slice(1).map(x => Number(x))

  if (M === 0) {
    console.log(fib(N))
    return
  }

  if (M > 1) {
    for (let i=1; i<M; i++) {
        if(a[i] - a[i-1] === 1) {
            console.log(0)
            return
        }
    }
  }

  const list = []
  for(let i=0; i<=M; i++) {
    if(i === 0) {
        list.push(a[i] - 1)
        continue
    }
    if(i === M) {
        list.push(N - a[i-1] - 1)
        continue
    }
    list.push(a[i] - a[i-1] - 2)
  }

  let ans = 1
  for(let i=0; i<M+1; i++) {
      ans = (ans * fib(list[i])) % 1000000007
  }
  console.log(ans)
}

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

function fib(x) {
    if(x === 1 || x === 0) {
        return 1
    }
    if(x === 2) {
        return 2
    }
    let last = 2
    let second = 1
    for(let i=3; i<=x; i++) {
        let total = (last + second) % 1000000007
        second = last
        last = total
    }
    return last
}


Score : 400 points

Problem Statement

There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares.

Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it.
The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and right.
In each direction, the beam will continue traveling until it hits a square occupied by an obstacle or it hits the border of the grid. It will light all the squares on the way, including the square on which the lamp is placed, but not the square occupied by an obstacle.

Snuke wants to maximize the number of squares lighted by the lamp.

You are given H strings S_i (1 \leq i \leq H), each of length W. If the j-th character (1 \leq j \leq W) of S_i is #, there is an obstacle on the square at the i-th row from the top and the j-th column from the left; if that character is ., there is no obstacle on that square.

Find the maximum possible number of squares lighted by the lamp.

Constraints

1 \leq H \leq 2,000

1 \leq W \leq 2,000

S_i is a string of length W consisting of # and ..

. occurs at least once in one of the strings S_i (1 \leq i \leq H).

Input

Input is given from Standard Input in the following format:

H W
S_1
:
S_H

Output

Print the maximum possible number of squares lighted by the lamp.

Sample Input 1

4 6
#..#..
.....#
....#.
#.#...

Sample Output 1

8

If Snuke places the lamp on the square at the second row from the top and the second column from the left, it will light the following squares: the first through fifth squares from the left in the second row, and the first through fourth squares from the top in the second column, for a total of eight squares.

Sample Input 2

8 8
..#...#.
....#...
##......
..###..#
...#..#.
##....#.
#...#...
###.#..#

Sample Output 2

13


Score : 500 points

Problem Statement

Takahashi and Aoki will play a game. They will repeatedly play it until one of them have N wins in total.

When they play the game once, Takahashi wins with probability A %, Aoki wins with probability B %, and the game ends in a draw (that is, nobody wins) with probability C %.
Find the expected number of games that will be played, and print it as follows.

We can represent the expected value as P/Q with coprime integers P and Q.
Print the integer R between 0 and 10^9+6 (inclusive) such that R \times Q \equiv P\pmod {10^9+7}.
(Such an integer R always uniquely exists under the constraints of this problem.)

Constraints

1 \leq N \leq 100000

0 \leq A,B,C \leq 100

1 \leq A+B

A+B+C=100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N A B C

Output

Print the expected number of games that will be played, in the manner specified in the statement.

Sample Input 1

1 25 25 50

Sample Output 1

2

Since N=1, they will repeat the game until one of them wins.
The expected number of games played is 2.

Sample Input 2

4 50 50 0

Sample Output 2

312500008

C may be 0.

Sample Input 3

1 100 0 0

Sample Output 3

1

B may also be 0.

Sample Input 4

100000 31 41 28

Sample Output 4

104136146


'use strict'

function Main(input) {
  input = input.split(' ');
  let A = parseInt(input[0]);
  let P = parseInt(input[1]);
  console.log((3*A + P) / 2);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

We have A apples and P pieces of apple.

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

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

Constraints

All values in input are integers.

0 \leq A, P \leq 100

Input

Input is given from Standard Input in the following format:

A P

Output

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

Sample Input 1

1 3

Sample Output 1

3

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

Sample Input 2

0 1

Sample Output 2

0

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

Sample Input 3

32 21

Sample Output 3

58


'use strict'

function Main(input) {
  input = input.split(" ");
  const A = parseInt(input[0], 10);
  let P = parseInt(input[1], 10);

  if (A !== 0) {
    const cutA = A*3;
    P = P + cutA;
  }

  const result = parseInt(P/2);

  console.log(result);

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


"use strict"

function main(input) {
  let dataList = input.split("\n");
  dataList.shift();
  dataList.pop();
  let restaurants = dataList.map((data, index) => {
    const tmp = data.split(" ")
    return { index: index + 1, city: tmp[0], score: parseInt(tmp[1]) }
  });
  restaurants.sort(function (a, b) {
    if (a.city < b.city) return -1
    if (a.city > b.city) return 1
    if (a.score < b.score) return 1
    if (a.score > b.score) return -1
  });
  restaurants.forEach(restaurant => {
    console.log(restaurant.index);
  });
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 200 points

Problem Statement

You have decided to write a book introducing good restaurants.
There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i.
No two restaurants have the same score.

You want to introduce the restaurants in the following order:

The restaurants are arranged in lexicographical order of the names of their cities.

If there are multiple restaurants in the same city, they are arranged in descending order of score.

Print the identification numbers of the restaurants in the order they are introduced in the book.

Constraints

1 ≤ N ≤ 100

S is a string of length between 1 and 10 (inclusive) consisting of lowercase English letters.

0 ≤ P_i ≤ 100

P_i is an integer.

P_i ≠ P_j (1 ≤ i < j ≤ N)

Input

Input is given from Standard Input in the following format:

N
S_1 P_1
:
S_N P_N

Output

Print N lines. The i-th line (1 ≤ i ≤ N) should contain the identification number of the restaurant that is introduced i-th in the book.

Sample Input 1

6
khabarovsk 20
moscow 10
kazan 50
kazan 35
moscow 60
khabarovsk 40

Sample Output 1

3
4
6
1
5
2

The lexicographical order of the names of the three cities is kazan < khabarovsk < moscow. For each of these cities, the restaurants in it are introduced in descending order of score. Thus, the restaurants are introduced in the order 3,4,6,1,5,2.

Sample Input 2

10
yakutsk 10
yakutsk 20
yakutsk 30
yakutsk 40
yakutsk 50
yakutsk 60
yakutsk 70
yakutsk 80
yakutsk 90
yakutsk 100

Sample Output 2

10
9
8
7
6
5
4
3
2
1


"use strict"

function main(input) {
  var dataList = input.split("\n");
  dataList.shift();
  dataList.pop();
  var items = dataList.map((data, index) => {
    var tmp = data.split(" ")
    return { no: index + 1, name: tmp[0], point: parseInt(tmp[1]) }
  });
  items.sort( function (a,b) {
    if (a.name < b.name) return -1
    if (a.name > b.name) return 1
    if (a.point < b.point) return 1
    if (a.point > b.ponit) return -1
  })
  items.forEach(item => {
    console.log(item.no)
  })
}
main(require("fs").readFileSync("/dev/stdin", "utf8"))


function Main(input){
var tmp = input.split('\n');
var size = tmp[0];
var tmp3 = [];
 for(var i = 1; i < tmp.length; i++){

   tmp3.push({
   city: tmp[i].split(' ')[0],
   score: parseInt(tmp[i].split(' ')[1]),
   index: i
   });
 }
var tmp2 = tmp3.sort(function(a,b){
if(a.city < b.city){return -1};
if(a.city > b.city){return 1};
if(a.score < b.score){return 1};
if(a.score > b.score){return -1};
return 0;
});
tmp2.forEach(function(e){
console.log(e.index);
})
//console.log(tmp2);

}

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


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

  const n = parseInt(temp.shift(), 10);
  const arr = [];

  for(let i = 0; i < n; i++){
    arr.push(temp[i].split(" "));
    arr[i].push(i + 1);
    arr[i][1] = parseInt(arr[i][1],10)
  }

  arr.sort((a,b) => b[1] - a[1]);
  arr.sort((a,b) => {
    if(a[0] < b[0]) return -1;
    else if(a[0] > b[0]) return 1;
    else 0;
  });
  console.log(arr)

  arr.forEach(e => console.log(e[2]))
  // const ans = temp.map(e => e[2]);
  // console.log(ans.join("\n"));
  // return false;
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
    var args = input.trim().split(/\r\n|\n/).map((v, i) => {
        if (i === 0) {
            return parseInt(v,10);
        }
        const arr = v.trim().split(" ").map((v2, i) => {
            if (i % 2 === 0) {
                return v2
            }
            return parseInt(v2,10);
        });
        arr.push(i);
        return arr;
    });

    const limit = args[0];
    const values = args.splice(1, limit);
    values.sort((a, b) => {
        if(a[0] < b[0]) return -1;
        if(a[0] > b[0]) return 1;
        if(a[1] < b[1]) return 1;
        if(a[1] > b[1]) return -1;
    })
    console.log(values.map((v) => v[2]).join("\n"));
}

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


Score : 400 points

Problem Statement

Your friend gave you a dequeue D as a birthday present.

D is a horizontal cylinder that contains a row of N jewels.

The values of the jewels are V_1, V_2, ..., V_N from left to right. There may be jewels with negative values.

In the beginning, you have no jewel in your hands.

You can perform at most K operations on D, chosen from the following, at most K times (possibly zero):

Operation A: Take out the leftmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation B: Take out the rightmost jewel contained in D and have it in your hand. You cannot do this operation when D is empty.

Operation C: Choose a jewel in your hands and insert it to the left end of D. You cannot do this operation when you have no jewel in your hand.

Operation D: Choose a jewel in your hands and insert it to the right end of D. You cannot do this operation when you have no jewel in your hand.

Find the maximum possible sum of the values of jewels in your hands after the operations.

Constraints

All values in input are integers.

1 \leq N \leq 50

1 \leq K \leq 100

-10^7 \leq V_i \leq 10^7

Input

Input is given from Standard Input in the following format:

N K
V_1 V_2 ... V_N

Output

Print the maximum possible sum of the values of jewels in your hands after the operations.

Sample Input 1

6 4
-10 8 2 1 2 6

Sample Output 1

14

After the following sequence of operations, you have two jewels of values 8 and 6 in your hands for a total of 14, which is the maximum result.

Do operation A. You take out the jewel of value -10 from the left end of D.

Do operation B. You take out the jewel of value 6 from the right end of D.

Do operation A. You take out the jewel of value 8 from the left end of D.

Do operation D. You insert the jewel of value -10 to the right end of D.

Sample Input 2

6 4
-6 -100 50 -2 -5 -3

Sample Output 2

44

Sample Input 3

6 3
-6 -100 50 -2 -5 -3

Sample Output 3

0

It is optimal to do no operation.


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var K = parseInt(input[0].split(" ")[1]);
  var V = input[1].split(" ").map(i=>parseInt(i));
  var ans=0;
  var save=[];
  for(var i=0;i<Math.min(K,N);i++){
    var minus=[...save];
    if(i==0){
      rsub=0;
    }else{
      rsub+=V[i-1];
    }
    if(V[i-1]<0){
      minus.push(V[i-1]);
      minus.sort(function(a,b){return a-b});
    }
    var save = [...minus];
    for(var j=0;j<Math.min(K-i,N-i);j++){
      if(j==0){
        lsub=0;
      }else{
        lsub+=V[N-j];
      }
      if(V[N-j]<0){
        minus.push(V[N-j]);
        minus.sort(function(a,b){return a-b});
      }
      var asub=rsub+lsub;
      for(var k=0;k<Math.min(K-i-j,minus.length);k++){
        asub-=minus[k];
      }
      ans=Math.max(ans,asub);
    }
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
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(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}
function lower_bound(d,a,b,e){for(var c;1<b-a;)d[c=0|(a+b)/2]<e?a=c:b=c;return d[a]<e?b:a};
function segTree(n){
  var u = n-1, x = 2;
  while(u)u >>= 1, x <<= 1;
  this.seg = Array(x-1).fill(2e9);
  this.l = x >> 1;
}
segTree.prototype={
  get:function(x){
    x += this.l-1;
    var r = 2e9;
    while(x >= 0){
      if(this.seg[x] < r)r = this.seg[x];
      x = (x-1)>>1;
    }
    if(r === 2e9)r = -1;
    return r;
  },
  update:function(l,r,t){
    var v = this.seg;
    q(l,r,0,this.l,0);
    function q(l,r,x,y,i){
      if(l === x && r === y){v[i] = t;return;}
      var m = x+y >> 1;
      if(m < r)if(l < m){q(l,m,x,m,i+i+1);q(m,r,m,y,i+1<<1);}
      else q(l,r,m,y,i+1<<1);
      else q(l,r,x,m,i+i+1);
    }
  },
}
console.log(main());
function main(){
  var n = o.a();
  var q = o.a();
  var s = o.m(n);
  var d = o.r(q);
  var st = new segTree(q);
  s.sort((a,b)=>b[2]-a[2]);
  for(var i = 0; i < n; i++){
    if(s[i][1]-s[i][2]-1<d[0])continue;
    var l = lower_bound(d,0,q,s[i][0]-s[i][2]);
    var r = lower_bound(d,l,q,s[i][1]-s[i][2]);
    if(l<r)st.update(l,r,s[i][2]);
  }
  var ans = Array(q);
  for(var i = 0; i < q; i++){
    ans[i] = st.get(i);
  }
  return ans.join("\n");
}

Score : 500 points

Problem Statement

There is an infinitely long street that runs west to east, which we consider as a number line.

There are N roadworks scheduled on this street.
The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5.

Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point.

Find the distance each of the Q people will walk.

Constraints

All values in input are integers.

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

0 \leq S_i < T_i \leq 10^9

1 \leq X_i \leq 10^9

0 \leq D_1 < D_2 < ... < D_Q \leq 10^9

If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap.

Input

Input is given from Standard Input in the following format:

N Q
S_1 T_1 X_1
:
S_N T_N X_N
D_1
:
D_Q

Output

Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever.

Sample Input 1

4 6
1 3 2
7 13 10
18 20 13
3 4 2
0
1
2
3
5
8

Sample Output 1

2
2
10
-1
13
-1

The first person starts coordinate 0 at time 0 and stops walking at coordinate 2 when reaching a point blocked by the first roadwork at time 2.

The second person starts coordinate 0 at time 1 and reaches coordinate 2 at time 3. The first roadwork has ended, but the fourth roadwork has begun, so this person also stops walking at coordinate 2.

The fourth and sixth persons encounter no roadworks while walking, so they walk forever. The output for these cases is -1.


"use strict";

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }

function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

!function () {
  function splitNum(line) {
    return (Array.isArray(line) ? line : line.split(/\s+/)).map(function (n) {
      return parseInt(n);
    });
  }

  !function (input) {
    var lines = input.split("\n");

    var _splitNum = splitNum(lines[0]),
        _splitNum2 = _slicedToArray(_splitNum, 2),
        A = _splitNum2[0],
        B = _splitNum2[1];

    if (A <= 5) console.log(0);else if (A <= 16) console.log(B / 2);else console.log(B);
  }(require("fs").readFileSync("/dev/stdin", "utf8"));
}();

Score : 100 points

Problem Statement

Takahashi, who is A years old, is riding a Ferris wheel.

It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currency of Japan.)

Find the cost of the Ferris wheel for Takahashi.

Constraints

0 ≤ A ≤ 100

2 ≤ B ≤ 1000

B is an even number.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the cost of the Ferris wheel for Takahashi.

Sample Input 1

30 100

Sample Output 1

100

Takahashi is 30 years old now, and the cost of the Ferris wheel is 100 yen.

Sample Input 2

12 100

Sample Output 2

50

Takahashi is 12 years old, and the cost of the Ferris wheel is the half of 100 yen, that is, 50 yen.

Sample Input 3

0 100

Sample Output 3

0

Takahashi is 0 years old, and he can ride the Ferris wheel for free.


"use strict";

function main(input) {
  const args = input.trim().split("\n");
  const n = to_num(args[0].split(" ")[0]);
  const m = to_num(args[0].split(" ")[1]);
  let R = [];
  let L = [];
  args.map((line, index) => {
    if (index === 0) return;
    L.push(to_num(line.split(" ")[0]));
    R.push(to_num(line.split(" ")[1]));
  });

  let maxL = -1000;
  let minR = 1000000;
  for (let i = 0; i < m; i++) {
    maxL = Math.max(maxL, L[i]);
    minR = Math.min(minR, R[i]);
  }
  console.log(Math.max(0, minR - maxL + 1));
}

const to_num = (str) => {
  return parseInt(str, 10);
};
main(require("fs").readFileSync("./dev/stdin", "utf8"));

Score : 300 points

Problem Statement

We have N ID cards, and there are M gates.

We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards.

How many of the ID cards allow us to pass all the gates alone?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq L_i \leq R_i \leq N

Input

Input is given from Standard Input in the following format:

N M
L_1 R_1
L_2 R_2
\vdots
L_M R_M

Output

Print the number of ID cards that allow us to pass all the gates alone.

Sample Input 1

4 2
1 3
2 4

Sample Output 1

2

Two ID cards allow us to pass all the gates alone, as follows:

The first ID card does not allow us to pass the second gate.

The second ID card allows us to pass all the gates.

The third ID card allows us to pass all the gates.

The fourth ID card does not allow us to pass the first gate.

Sample Input 2

10 3
3 6
5 7
6 9

Sample Output 2

1

Sample Input 3

100000 1
1 100000

Sample Output 3

100000


// inputに入力データ全体が入る      ha
function Main(input) {             //   hma1080提出作品
	// 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.split("\n")
  tmp0 = input[0].split(" ")

  N = Number(tmp0[0])
  M = Number(tmp0[1])

    var tmp1 = input[1].split(" ")
    r = Number(tmp1[1]);
    var tmp1 = input[M].split(" ")
    l = Number(tmp1[0]);
 // console.log(r,l);
    if( l<=r ){console.log(r-l+1);}
    else{console.log('0');}

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


'use strict'
function Main(input) {
  	// 情報の切り分け
    let Nums = input.trim().split('\n').map(x => x.split(' '));
  	// 最初の情報を取り出す
  	let info = Nums.shift();

  	// 小さい方で一番大きな値を出す
  	let minNums = Nums.map(num => num[0]);
  	let minNumsTop = Math.max(...minNums);

    // 小さい方で一番大きな値を出す
  	let maxNums = Nums.map(num => num[1]);
  	let maxNumsBottom = Math.min(...maxNums);

  	let ans = maxNumsBottom - minNumsTop > 0 ?
        		maxNumsBottom - minNumsTop + 1:
    			1;
  	// 大きい方引く小さい方に一足したものが答え
    console.log(ans);
}

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


function main(input) {
  var inputArray = input.trim().split('\n');
  var cardNum = Number(inputArray[0].split('\s')[0]);
  var LList = [];
  var RList = [];
  inputArray.filter((item, index) => index !== 0).forEach(item => {
    LList.push(Number(item.split('\s')[0]));
    RList.push(Number(item.split('\s')[1]));
  });
  var maxL = Math.max.apply(null, LList);
  var minR = Math.min.apply(null, RList);
  if (maxL > minR) {
    console.log(0);
  } else {
    console.log(minR - maxL + 1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


'use strict'
function Main(input) {
    // 入力の取得・整形
    input = input.split("\n")
    input = input.map(elem => {
        // 'x y'といった文字列を配列[x, y]に変換する
        return elem.split(' ').map(str => parseInt(str))
    })
    const N = input[0][0]

    // 配列a,bの共通区間を求める関数
    const makeInterval = (a, b) => {
        const start = a[0] > b[0] ? a[0] : b[0]
        const end = a[1] > b[1] ? b[1] : a[1]
        return [start, end]
    }

    // 全区間の共通区間を求めていく
    const resultArr = input.reduce((accum, current, index) => {
        if (index === 0) {
            // 最初は[N, M]だからスキップする
            return accum
        }
        return makeInterval(accum, current)
    }, [1, N])

    // [6, 3]のように、開始のほうが大きくなってる場合は0を返す。そうでない場合区間に含まれる数の個数を返す
    const result = (resultArr[0] > resultArr[1]) ? 0 : resultArr[1] - resultArr[0] + 1

    console.log(result)
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"))


// inputに入力データ全体が入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    tmp0 = input[0].split(" ");
    N = Number(tmp0[0]);
    M = Number(tmp0[1]);

    lmin=1
    rmax=N
    for(var i=1; i<=M;i++){
        tmp1 = input[i].split(" ")
        L = Number(tmp1[0])
        R = Number(tmp1[1])
        lmin = Math.max(lmin, L)
        rmax = Math.min(rmax, R)
    }
    if(rmax-lmin+1 < 0){
        console.log(0)
    }else{
        console.log(rmax-lmin+1)
    }
  }
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//   Main("6 2\n3 6\n1 4\n");


var lines = [];

var readline = require('readline')
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', (x) => {
    lines.push(x)
});

rl.on('close', () => {
    var N = Number(lines[0].split(" ")[0])
    var M = Number(lines[0].split(" ")[1])
    lines.shift()

    var LR = lines.map(i => i.split(" ").map(i => Number(i)));
    var start = 0; var goal = Infinity;

    for (var i = 0; i < M; i++) {
        var l = LR[i][0]; var r = LR[i][1];
        if (start < l) { start = l; }
        if (r < goal) { goal = r; }
    }
    console.log(goal - start + 1)
});


var lines = [];

var readline = require('readline')
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', (x) => {
    lines.push(x)
});

var A;
rl.on('close', () => {
    var N = Number(lines[0].split(" ")[0])
    var M = Number(lines[0].split(" ")[1])
    A = lines[1].split(" ").map(i => Number(i));

    lines.shift(); lines.shift()

    var BC = lines.map(i => i.split(" ").map(i => Number(i)));

    A.sort((a, b) => a - b);
    BC.sort((a, b) => b[1] - a[1]);

    var k = 0; var ans = 0;
    for (var i = 0; i < M; i++) {
        var b = BC[i][0]; var c = BC[i][1];
        var cnt = 1;

        for (var j = k; j < N; j++) {
            if (b < cnt) { k = j; break; }

            if (A[j] < c) { ans += c; }
            else { for (var x = j; x < N; x++) { ans += A[x] } console.log(ans); return (0) }

            cnt++;
        }
    }
    for (var x = j; x < N; x++) { ans += A[x] } console.log(ans);

});

Score : 400 points

Problem Statement

You have N cards. On the i-th card, an integer A_i is written.

For each j = 1, 2, ..., M in this order, you will perform the following operation once:

Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.

Find the maximum possible sum of the integers written on the N cards after the M operations.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i, C_i \leq 10^9

1 \leq B_i \leq N

Input

Input is given from Standard Input in the following format:

N M
A_1 A_2 ... A_N
B_1 C_1
B_2 C_2
\vdots
B_M C_M

Output

Print the maximum possible sum of the integers written on the N cards after the M operations.

Sample Input 1

3 2
5 1 4
2 3
1 5

Sample Output 1

14

By replacing the integer on the second card with 5, the sum of the integers written on the three cards becomes 5 + 5 + 4 = 14, which is the maximum result.

Sample Input 2

10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4

Sample Output 2

338

Sample Input 3

3 2
100 100 100
3 99
3 99

Sample Output 3

300

Sample Input 4

11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000

Sample Output 4

10000000001

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


"use strict";
const Main = (input) => {
	let xs = input.trim().split(',').toString();
    let A = Number(xs[0] + xs[1]);
    let B = Number(xs[2] + xs[3]);

    if(A > 13 && B < 13 && A != 0 && B != 0){
       console.log('YYMM');
	}else if(A < 13 && B > 13 && A != 0 && B != 0){
       console.log('MMYY');
    }else if(A > 13 || B > 13 || A == 0 || B == 0){
       console.log('NA');
    }else if(A < 13 && B < 13 && A != 0 && B != 0){
       console.log('AMBIGUOUS');
    }
}
Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 100 points

Problem Statement

You are given a string S of length N consisting of A, B and C, and an integer K which is between 1 and N (inclusive).
Print the string S after lowercasing the K-th character in it.

Constraints

1 ≤ N ≤ 50

1 ≤ K ≤ N

S is a string of length N consisting of A, B and C.

Input

Input is given from Standard Input in the following format:

N K
S

Output

Print the string S after lowercasing the K-th character in it.

Sample Input 1

3 1
ABC

Sample Output 1

aBC

Sample Input 2

4 3
CABA

Sample Output 2

CAbA


"use strict";

const stringToIntDecimal = s => parseInt(s);

const readData = input => {
  const inputArray = input.split("\n");
  const numberArray = inputArray[0].split(" ").map(stringToIntDecimal);

  return {
    length: numberArray[0],
    operandNumber: numberArray[1],
    str: inputArray[1]
  };
};

function Main(input) {
  let data = readData(input);
  const index = data.operandNumber - 1;
  const inputString = data.str;
  let outputString =
    inputString.substring(0, index) +
    inputString.charAt(index).toLowerCase() +
    inputString.substring(index + 1, data.length);
  console.log(outputString);
}

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


function Main(input) {
    var N = parseInt(input[0], 10);
    var K = parseInt(input[1], 10);
    var S = input[2];

    var mozi = S.charAt(K - 1);
    var result = '';

    for (var i=0; i<N; i++) {
        if (i + 1 === K) {
            if (mozi === 'A') {
                result += 'a'
            } else if (mozi === 'B') {
                result += 'b'
            } else if (mozi === 'C') {
                result += 'c'
            }
        } else {
            result += S.charAt(i);
        }
    }

    console.log(result);
}

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


'use strict';
const p = s => console.log(s);
// let a,b,c,d;
// [a,b,c,d] = input[0].trim().split(" ").map(i => parseInt(i));

function main(input) {
  let S = input[0].trim().split("");

  let num = parseInt(S[0] + S[1]);
  let num2 = parseInt(S[2] + S[3]);

  if(num === 0 || num2 ===0) {
    p('NA');
    return;
  }

  if(num < 13 && num2 < 13) {
    p('AMBIGUOUS');
  } else if(num < 13 && num2 >= 13) {
    p('MMYY');
  } else if (num >= 13 && num2 < 13) {
    p('YYMM');
  } else {
    p('NA');
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));

Score : 200 points

Problem Statement

You have a digit sequence S of length 4. You are wondering which of the following formats S is in:

YYMM format: the last two digits of the year and the two-digit representation of the month (example: 01 for January), concatenated in this order

MMYY format: the two-digit representation of the month and the last two digits of the year, concatenated in this order

If S is valid in only YYMM format, print YYMM; if S is valid in only MMYY format, print MMYY; if S is valid in both formats, print AMBIGUOUS; if S is valid in neither format, print NA.

Constraints

S is a digit sequence of length 4.

Input

Input is given from Standard Input in the following format:

S

Output

Print the specified string: YYMM, MMYY, AMBIGUOUS or NA.

Sample Input 1

1905

Sample Output 1

YYMM

May XX19 is a valid date, but 19 is not valid as a month. Thus, this string is only valid in YYMM format.

Sample Input 2

0112

Sample Output 2

AMBIGUOUS

Both December XX01 and January XX12 are valid dates. Thus, this string is valid in both formats.

Sample Input 3

1700

Sample Output 3

NA

Neither 0 nor 17 is valid as a month. Thus, this string is valid in neither format.


function Main(input) {
	s = input
    a = s.slice(0, 2) * 1
    b = s.slice(-2) * 1
    c = d = false
    ans = ''
    if (1 <= a && a <= 12) {
      c = true
    }
    if (1 <= b && b <= 12) {
      d = true
    }
    if (c && d) {
      ans = 'AMBIGUOUS'
    } else if (c) {
      ans = 'MMYY'
    } else if (d) {
      ans = 'YYMM'
    } else {
      ans = 'NA'
    }
	console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
function main(input) {

  const checkM = (num) => {
      if (1 <= num && num <= 12) {
          return true;
        } else {
            return false;
        }
    };

  const checkY = (num) => {
      if (1 <= num && num <= 99) {
          return true;
        } else {
            return false;
        }
    };

  const args = input.split("\n");
  const S = args[0];

  const first = parseInt(S.slice(0, 2));
  const second = parseInt(S.slice(2,4));

  let firstIsM = checkM(first);
  let firstIsY = checkY(first);

  let secondIsM = checkM(second);
  let secondIsY = checkY(second);

  if((firstIsY && secondIsM) && (firstIsM && secondIsY)) {
      console.log("AMBIGUOUS");
  } else if(firstIsY && secondIsM) {
      console.log("YYMM");
  } else if(firstIsM && secondIsY) {
      console.log('MMYY');
  } else {
      console.log('NA');
  }

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


def resolve():
    S = input()

    # YY: 00<=YY<=99
    # MM: 01<=MM<=12

    f_canYY = lambda x: '00' <= x and x <= '99'
    f_canMM = lambda x: '01' <= x and x <= '12'

    a = S[0:2]
    b = S[2:4]

    yymm = f_canYY(a) and f_canMM(b)
    mmyy = f_canMM(a) and f_canYY(b)

    if yymm and mmyy:
        print('AMBIGUOUS')
    elif yymm and not mmyy:
        print('YYMM')
    elif not yymm and mmyy:
        print('MMYY')
    else:
        print('NA')

resolve()


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const K = parseInt(arg[0].split(" ")[1]);

    let answer = 0;

    for(let i=1; i<=N; i++) {
        let temp;

        if(i >= K) {
            answer += (1 / N);
        } else {
            for(let j=1; j<100000; j++) {
                if(i * Math.pow(2, j) > K) {
                    temp = j;
                    break;
                }
            }

            answer += (1 / N) * Math.pow((1 / 2), temp);
        }
    }

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

Score : 300 points

Problem Statement

Snuke has a fair N-sided die that shows the integers from 1 to N with equal probability and a fair coin. He will play the following game with them:

Throw the die. The current score is the result of the die.

As long as the score is between 1 and K-1 (inclusive), keep flipping the coin. The score is doubled each time the coin lands heads up, and the score becomes 0 if the coin lands tails up.

The game ends when the score becomes 0 or becomes K or above. Snuke wins if the score is K or above, and loses if the score is 0.

You are given N and K. Find the probability that Snuke wins the game.

Constraints

1 ≤ N ≤ 10^5

1 ≤ K ≤ 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the probability that Snuke wins the game. The output is considered correct when the absolute or relative error is at most 10^{-9}.

Sample Input 1

3 10

Sample Output 1

0.145833333333

If the die shows 1, Snuke needs to get four consecutive heads from four coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^4 = \frac{1}{48}.

If the die shows 2, Snuke needs to get three consecutive heads from three coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^3 = \frac{1}{24}.

If the die shows 3, Snuke needs to get two consecutive heads from two coin flips to obtain a score of 10 or above. The probability of this happening is \frac{1}{3} \times (\frac{1}{2})^2 = \frac{1}{12}.

Thus, the probability that Snuke wins is \frac{1}{48} + \frac{1}{24} + \frac{1}{12} = \frac{7}{48} \simeq 0.1458333333.

Sample Input 2

100000 5

Sample Output 2

0.999973749998


'use strict';
(function(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  const N=input[0];
  const K=input[1];
  var k=K-1;
  var e=[Infinity,K-1];
  while(k>0){
    k=Math.floor(k/2);
    e.push(k);
  }
  var p=new Array(N).fill(1/N);
  p[0]=0;
  var ans=0;
  p.forEach(function(x,i){
    for(let j=0;j<e.length;j++){
      if(e[j+1]<i&&i<=e[j]){
        ans+=x/Math.pow(2,j);
      }
    }
  });
  console.log(ans);
})(require('fs').readFileSync('/dev/stdin','utf8'));


'use strict'

let par;

function root(x){
    if(par[x]==x) return x;
    return par[x] = root(par[x]);
}
function unite(x,y){
    let rx = root(x);
    let ry = root(y);
    //console.log('unite',x,y,rx,ry)
    if(rx==ry) return;
    par[rx] = ry;
}
function same(x,y){
    let rx = root(x);
    let ry = root(y);
    return rx == ry;
}

function Main(input){
    let temp = input.trim().split('\n');
    let n = parseInt(temp[0]);

    par = new Array(n+1);

    for(let i=0;i<=n;i++){
        par[i] = i;
    }
    let temp2;
    let u,v,w;
    for(let i=1;i<n;i++){
        temp2 = temp[i].split(' ').map((v)=>parseInt(v));
        u = temp2[0];
        v = temp2[1];
        w = temp2[2];

        //console.log('---------------');
        //console.log(u,v,w);
        //console.log(par);
        if( (w%2) == 1 ){//奇数
            if(same(u,0)){
                unite(u,0);
            }else{
                unite(v,0);
            }
        }else{//偶数
            unite(u,v);
        }
        //console.log('↓');
        //console.log(par);
    }
    let ans='';
    for(let i=1;i<=n-1;i++){
        if(same(i,0)) ans+='0\n'
        else ans+='1\n';
    }
    if(same(n,0)) ans+='0\n'
    else ans+='1\n';
    console.log(ans);

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

Score : 400 points

Problem Statement

We have a tree with N vertices numbered 1 to N.
The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i.
Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:

For any two vertices painted in the same color, the distance between them is an even number.

Find a coloring of the vertices that satisfies the condition and print it. It can be proved that at least one such coloring exists under the constraints of this problem.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq u_i < v_i \leq N

1 \leq w_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
u_1 v_1 w_1
u_2 v_2 w_2
.
.
.
u_{N - 1} v_{N - 1} w_{N - 1}

Output

Print a coloring of the vertices that satisfies the condition, in N lines.
The i-th line should contain 0 if Vertex i is painted white and 1 if it is painted black.

If there are multiple colorings that satisfy the condition, any of them will be accepted.

Sample Input 1

3
1 2 2
2 3 1

Sample Output 1

0
0
1

Sample Input 2

5
2 5 2
2 3 10
1 3 8
3 4 2

Sample Output 2

1
0
1
0
1


'use strict'
function Main(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  var R=input[0],G=input[1],B=input[2],N=input[3];
  function rg(M){
    var counter=0;
    var r=Math.floor(M/R);
    var g=0;
    while(r>=0){
      while(r*R+g*G<M)g++;
      if(r*R+g*G===M)counter++;
      r--;
    }
    return counter;
  }
  var b=0;
  var ans=0;
  while(b*B<=N){
    ans+=rg(N-b*B);
  }
  console.log(ans);
}

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

Score : 200 points

Problem Statement

Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:

Red boxes, each containing R red balls

Green boxes, each containing G green balls

Blue boxes, each containing B blue balls

Snuke wants to get a total of exactly N balls by buying r red boxes, g green boxes and b blue boxes.
How many triples of non-negative integers (r,g,b) achieve this?

Constraints

All values in input are integers.

1 \leq R,G,B,N \leq 3000

Input

Input is given from Standard Input in the following format:

R G B N

Output

Print the answer.

Sample Input 1

1 2 3 4

Sample Output 1

4

Four triples achieve the objective, as follows:

(4,0,0)

(2,1,0)

(1,0,1)

(0,2,0)

Sample Input 2

13 1 4 3000

Sample Output 2

87058


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(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var n = o.a();
  var s = o.r(n,1);
  var a = 0;
  var b = 0;
  var c = 0;
  var ans = 0;
  for(var i = 0; i < n; i++){
    var x = s[i][0];
    for(var j = 1; j < s[i].length; j++){
      if(x === "A" && s[i][j] === "B")ans++;
      x = s[i][j];
    }
    if(s[i][0] === "B"){
      if(s[i][s[i].length-1] === "A")c++;
      else b++;
    }else if(s[i][s[i].length-1] === "A")a++;
  }
  var mn = Math.min(a,b);
  var mx = Math.max(a,b);
  if(mx){
    if(c)ans += mn+c;
    else ans += mn;
  }else if(c)ans += c-1;
  return ans;
}

Score : 400 points

Problem Statement

Snuke has N strings. The i-th string is s_i.

Let us concatenate these strings into one string after arranging them in some order.
Find the maximum possible number of occurrences of AB in the resulting string.

Constraints

1 \leq N \leq 10^{4}

2 \leq |s_i| \leq 10

s_i consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

N
s_1
\vdots
s_N

Output

Print the answer.

Sample Input 1

3
ABCA
XBAZ
BAD

Sample Output 1

2

For example, if we concatenate ABCA, BAD and XBAZ in this order, the resulting string ABCABADXBAZ has two occurrences of AB.

Sample Input 2

9
BEWPVCRWH
ZZNQYIJX
BAVREA
PA
HJMYITEOX
BCJHMRMNK
BP
QVFABZ
PRGKSPUNA

Sample Output 2

4

Sample Input 3

7
RABYBBE
JOZ
BMHQUVA
BPA
ISU
MCMABAOBHZ
SZMEHMA

Sample Output 3

4


"use strict";

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

const N = parseInt(input, 10);

if (N <= 2) {
  console.log(0);
  return;
}

let ans = 0;

for (let i = 1; i < N / i; i++) {
  if (N % i === 0) {
    ans += (N / i) - 1;
  }
}

console.log(ans);

Score : 500 points

Problem Statement

Snuke received a positive integer N from Takahashi.
A positive integer m is called a favorite number when the following condition is satisfied:

The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds.

Find all favorite numbers and print the sum of those.

Constraints

All values in input are integers.

1 \leq N \leq 10^{12}

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

8

Sample Output 1

10

There are two favorite numbers: 3 and 7. Print the sum of these, 10.

Sample Input 2

1000000000000

Sample Output 2

2499686339916

Watch out for overflow.


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(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

console.log(main());
function main(){
  var h = o.a();
  var w = o.a();
  var n = o.a();
  var sr = o.a();
  var sc = o.a();
  var s = o.a(1);
  var t = o.a(1);
  var gr = h-sr, gc = w-sc;
  sr--, sc--;
  var l1 = 0, r1 = 0, u1 = 0, d1 = 0;
  var l2 = 0, r2 = 0, u2 = 0, d2 = 0;
  var Y = "YES", N = "NO";
  for(var i = 0; i < n; i++){
    if(s[i] === "U")u1++;
    else if(s[i] === "R")r1++;
    else if(s[i] === "D")d1++;
    else l1++;
    if(l1-r2 > sc || u1-d2 > sr || r1-l2 > gc || d1-u2 > gr)return N;
    if(t[i] === "U" && sr+d1-u2 > 0)u2++;
    else if(t[i] === "R" && gc+l1-r2 > 0)r2++;
    else if(t[i] === "D" && gr+u1-d2 > 0)d2++;
    else if(t[i] === "L" && sc+r1-l2 > 0)l2++;
  }
  return Y;
}

Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

2 \leq H,W \leq 2 \times 10^5

2 \leq N \leq 2 \times 10^5

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO


'use strict';
(function(input){
  input=input.trim().split(/\s+/).max(x=>x-0);
  const N=input.shift();

  function Node(id){
    var t=this;
    t.index=id;
    t.connected=[];
    t.depth='not yet scanned';
    t.depth2='not yet scanned';
  }

  const nodes=new Array(N+1).fill(0).map((x,i)=>new Node(i));
  nodes[0]='zero';

  for(let i=0;i<N-1;i++){
    let u=nodes[input[2*i]];
    let v=nodes[input[2*i+1]];
    u.connected.push(v);
    v.connected.push(u);
  }

  const stack=[1];
  var parentsDepth=-1;
  var deepest=nodes[1];

  while(stack.length>0){
    let i=stack[stack.length-1];
    let n=nodes[i];
    if(n.depth='not yet scanned')
      n.depth=parentsDepth+1;
    parentsDepth=n.depth;
    if(n.depth>deepest.depth)
      deepest=n;
    if(n.connected>0){
      let c=n.connected[n.connected.length-1];
      if(c.depth!=='not yet scanned'){
        n.connected.pop();
        continue;
      }else{
        stack.push(c.index);
        continue;
      }
    }else stack.pop();
  }

  for(let i=0;i<N-1;i++){
    let u=nodes[input[2*i]];
    let v=nodes[input[2*i+1]];
    u.connected.push(v);
    v.connected.push(u);
  }

  stack.push(deepest.id);
  parentsDepth=-1;
  while(stack.length>0){
    let i=stack[stack.length-1];
    let n=nodes[i];
    if(n.depth2='not yet scanned')
      n.depth2=parentsDepth+1;
    parentsDepth=n.depth2;
    if(n.depth2>deepest.depth2)
      deepest=n;
    if(n.connected>0){
      let c=n.connected[n.connected.length-1];
      if(c.depth!=='not yet scanned'){
        n.connected.pop();
        continue;
      }else{
        stack.push(c.index);
        continue;
      }
    }else stack.pop();
  }

  if((deepest.depth+1)%3===0)
    console.log('Second');
  else console.log('First');
})(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 800 points

Problem Statement

Takahashi and Aoki will play a game on a tree.
The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i.

At the beginning of the game, each vertex contains a coin.
Starting from Takahashi, he and Aoki will alternately perform the following operation:

Choose a vertex v that contains one or more coins, and remove all the coins from v.

Then, move each coin remaining on the tree to the vertex that is nearest to v among the adjacent vertices of the coin's current vertex.

The player who becomes unable to play, loses the game.
That is, the player who takes his turn when there is no coin remaining on the tree, loses the game.
Determine the winner of the game when both players play optimally.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq a_i, b_i \leq N

a_i \neq b_i

The graph given as input is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
:
a_{N-1} b_{N-1}

Output

Print First if Takahashi will win, and print Second if Aoki will win.

Sample Input 1

3
1 2
2 3

Sample Output 1

First

Here is one possible progress of the game:

Takahashi removes the coin from Vertex 1. Now, Vertex 1 and Vertex 2 contain one coin each.

Aoki removes the coin from Vertex 2. Now, Vertex 2 contains one coin.

Takahashi removes the coin from Vertex 2. Now, there is no coin remaining on the tree.

Aoki takes his turn when there is no coin on the tree and loses.

Sample Input 2

6
1 2
2 3
2 4
4 6
5 6

Sample Output 2

Second

Sample Input 3

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

Sample Output 3

First


'use strict';

function Main(input) {
  const A = Number(input.split(" ")[0])
  const B = Number(input.split(" ")[1])
  const T = Number(input.split(" ")[2])

  const time = T + 0.5
  console.log(Math.floor(time / A) * B)

};

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

Score : 100 points

Problem Statement

A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation.

Find the total number of biscuits produced within T + 0.5 seconds after activation.

Constraints

All values in input are integers.

1 \leq A, B, T \leq 20

Input

Input is given from Standard Input in the following format:

A B T

Output

Print the total number of biscuits produced within T + 0.5 seconds after activation.

Sample Input 1

3 5 7

Sample Output 1

10

Five biscuits will be produced three seconds after activation.

Another five biscuits will be produced six seconds after activation.

Thus, a total of ten biscuits will be produced within 7.5 seconds after activation.

Sample Input 2

3 2 9

Sample Output 2

6

Sample Input 3

20 20 19

Sample Output 3

0


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	// input1 = input[0].split(' ').map((n) => (parseInt(n)))
	h = input[1].split(' ').map((n) => (parseInt(n)))
	c = input[2].split(' ').map((n) => (parseInt(n)))
	// ans = input.filter((n) => (s <= n)).length

	var ans = 0
	for (var i = 0;i  < h.length; i++) {
		var tmp = h[i] - c[i]
		if (tmp > 0 ) {
			ans += tmp
		}
	}

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

Score : 200 points

Problem Statement

There are N gems. The value of the i-th gem is V_i.

You will choose some of these gems, possibly all or none, and get them.

However, you need to pay a cost of C_i to get the i-th gem.

Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.

Find the maximum possible value of X-Y.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq C_i, V_i \leq 50

Input

Input is given from Standard Input in the following format:

N
V_1 V_2 ... V_N
C_1 C_2 ... C_N

Output

Print the maximum possible value of X-Y.

Sample Input 1

3
10 2 5
6 3 4

Sample Output 1

5

If we choose the first and third gems, X = 10 + 5 = 15 and Y = 6 + 4 = 10.
We have X-Y = 5 here, which is the maximum possible value.

Sample Input 2

4
13 21 6 19
11 30 6 15

Sample Output 2

6

Sample Input 3

1
1
50

Sample Output 3

0


function Main(input) {
    "use strict";
    const els = input.split('\n');
    const number = els[0];
    const values = els[1].split(' ');
    const costs = els[2].split(' ');
    let sum = 0;

    for (let i = 0; i < number; i++) {
        if(parseInt(values[i],10) >= parseInt(costs[i],10)){
            sum += parseInt(values[i],10) - parseInt(costs[i],10);
        }
    }

    console.log(sum);
}

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


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const A = arg[1].split(" ").map(n=>parseInt(n));

    const sum = A.reduce((m,n)=>Math.abs(m)+Math.abs(n));
    const minus = A.filter(n=>n < 0);
    const minAbs = A.map(n=>Math.abs(n)).sort((a,b)=>a-b)[0];

    // console.log(sum)

    if(minus.length % 2 !== 0) {
        console.log(sum - (minAbs * 2));
    } else {
        console.log(sum);
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 400 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, arranged in a row in this order.

You can perform the following operation on this integer sequence any number of times:

Operation: Choose an integer i satisfying 1 \leq i \leq N-1. Multiply both A_i and A_{i+1} by -1.

Let B_1, B_2, ..., B_N be the integer sequence after your operations.

Find the maximum possible value of B_1 + B_2 + ... + B_N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

-10^9 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible value of B_1 + B_2 + ... + B_N.

Sample Input 1

3
-10 5 -4

Sample Output 1

19

If we perform the operation as follows:

Choose 1 as i, which changes the sequence to 10, -5, -4.

Choose 2 as i, which changes the sequence to 10, 5, 4.

we have B_1 = 10, B_2 = 5, B_3 = 4. The sum here, B_1 + B_2 + B_3 = 10 + 5 + 4 = 19, is the maximum possible result.

Sample Input 2

5
10 -4 -8 -11 3

Sample Output 2

30

Sample Input 3

11
-1000000000 1000000000 -1000000000 1000000000 -1000000000 0 1000000000 -1000000000 1000000000 -1000000000 1000000000

Sample Output 3

10000000000

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


function Main(input){
 input = input.split("\n");
 inputStr = input[0].split(" ");
 var N = Number.parseInt(inputStr[0]);
 var A = input[1].split(" ");
 var i = 0;
 var out = 0;
 var sum = 0;
 var abssum = 0;
 var mainus_cnt = 0;

 //console.log(N);
 //console.log(A);

 //負の数が幾つあるか数える
 for ( i = 0 ; i < N; i++) {
   if ( Number.parseInt(A[i]) < 0 ) {
     mainus_cnt += 1;
     if ( i > 0 && Number.parseInt(A[i-1]) === 0 ) {
       mainus_cnt = 0;
     }
   }
   if ( Number.parseInt(A[i]) === 0 ) {
     mainus_cnt = 0;
   }
 }
 //console.log(mainus_cnt);

 //文字列Aの最後と、そのひとつ前のどちらが絶対値として大きいか判定
 if ( ( mainus_cnt % 2 ) !== 0 ) {
   if ( Math.abs(Number.parseInt(A[N-1])) >= Math.abs(Number.parseInt(A[N-2]))) {
     out = N-2;
   } else {
     out = N-1;
   }
 }
 //console.log(out);

 //forで回しながら絶対値を足しこむ。
 for ( i=0 ; i<N ; i++) {
   //console.log(i);
   if ( out === 0 ) {
     abssum = abssum + Math.abs(Number.parseInt(A[i]));
   } else {
     if ( i === out) {
       abssum = abssum - Math.abs(Number.parseInt(A[i]));
     } else {
       abssum = abssum + Math.abs(Number.parseInt(A[i]));
     }
   }
   //sum = sum + Math.abs(Number.parseInt(A[i]));
 }
 console.log(abssum);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  lines = input.split("\n")
  n = lines[0] * 1
  a = lines[1].split(' ').map(Number)
  ans = 0
  min = Math.abs(a[a.length-1])
  flgs = 0
  for (i=0; i<a.length;i++) {
    if (a[i] < 0) flgs++
    min = Math.min(Math.abs(a[i]), min)
    ans += a[i] >= 0 ? a[i] : a[i] * -1
  }
  if (flgs % 2 == 0) {
    console.log(ans);
  } else {
    console.log(ans-min*2);
  }
}

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


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    // 数値の配列を作る
    const numList0 = input[0].split(' ').map(x => parseInt(x, 10));
    const N = numList0[0];
    const AList = input[1].split(' ').map(x => parseInt(x, 10));

    var result = 0;

  	if (N === 2) {
		const Ai2 = AList[0];
        const Ainext2 = AList[1];

        if (Ai2 > 0 && Ainext2 > 0) {
            console.log(Ai2 + Ainext2);
        } else if (Ai2 < 0 && Ainext2 < 0) {
            console.log((Ai2 + Ainext2) * (-1));
        } else {
            console.log(Math.max(Math.abs(Ai2), Math.abs(Ainext2)));
        }

        return;
    }

    for (var i = 0; i < N - 1; i++) {
        var Ai = AList[i];
        var Ainext = AList[i + 1];
        // 両方負の時
        if (Ai < 0 && Ainext < 0) {
            // 反転する
            result += Ai * (-1);
            AList[i + 1] = Ainext * (-1);
        } else if (Ai < 0 && Math.abs(Ai) >= Math.abs(Ainext)) {
            // Aiの方が絶対値が大きい時
            // 反転する
            result += Ai * (-1);
            AList[i + 1] = Ainext * (-1);
        } else if (Ai > 0 && Ainext > 0) {
            // そのまま足す
            result += Ai;
        } else {
            result += Ai;
        }
    }
    // 最後はそのまま足す
    result += AList[N - 1];

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


function main(arg) {
    var args = args.split('¥n')
    var N = +args[0]
    var S = args[1]
    var K = args[2]

    var tg = S[N]

    var arr = []
    for(var i = 0; i < N; i++){
        if(S[i] !== tg){
            arr.push('*')
        }else{
            arr.push(S[i])
        }
    }
    console.log(arr.join(''))
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 200 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters, and an integer K.
Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Constraints

1 \leq K \leq N\leq 10

S is a string of length N consisting of lowercase English letters.

N and K are integers.

Input

Input is given from Standard Input in the following format:

N
S
K

Output

Print the string obtained by replacing every character in S that differs from the K-th character of S, with *.

Sample Input 1

5
error
2

Sample Output 1

*rr*r

The second character of S is r. When we replace every character in error that differs from r with *, we get the string *rr*r.

Sample Input 2

6
eleven
5

Sample Output 2

e*e*e*

Sample Input 3

9
education
7

Sample Output 3

******i**


parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"Focm":[function(require,module,exports) {
var n={};!function(n){"use strict";var t=function(n){this.compose=n},r=new t(function(n){return function(t){return function(r){return n(t(r))}}});n.compose=function(n){return n.compose},n.Semigroupoid=t,n.semigroupoidFn=r}(n["Control.Semigroupoid"]=n["Control.Semigroupoid"]||{}),function(t){"use strict";var r=n["Control.Semigroupoid"],a=function(n,t){this.Semigroupoid0=n,this.identity=t},e=new a(function(){return r.semigroupoidFn},function(n){return n});t.Category=a,t.identity=function(n){return n.identity},t.categoryFn=e}(n["Control.Category"]=n["Control.Category"]||{}),function(t){"use strict";(n["Data.Functor"]=n["Data.Functor"]||{}).arrayMap=function(n){return function(t){for(var r=t.length,a=new Array(r),e=0;e<r;e++)a[e]=n(t[e]);return a}}}(),function(t){"use strict";var r=n["Data.Functor"],a=(n["Control.Semigroupoid"],n["Data.Function"],n["Data.Unit"],function(n){this.map=n}),e=new a(r.arrayMap);t.Functor=a,t.map=function(n){return n.map},t.functorArray=e}(n["Data.Functor"]=n["Data.Functor"]||{}),function(t){"use strict";n["Control.Apply"],n["Control.Category"],n["Data.Function"],n["Data.Functor"];t.Apply=function(n,t){this.Functor0=n,this.apply=t},t.apply=function(n){return n.apply}}(n["Control.Apply"]=n["Control.Apply"]||{}),function(t){"use strict";n["Control.Apply"],n["Data.Functor"],n["Data.Unit"];t.Applicative=function(n,t){this.Apply0=n,this.pure=t},t.pure=function(n){return n.pure}}(n["Control.Applicative"]=n["Control.Applicative"]||{}),function(t){"use strict";n["Control.Bind"],n["Control.Applicative"],n["Control.Apply"],n["Control.Category"],n["Data.Function"],n["Data.Functor"],n["Data.Unit"];t.Bind=function(n,t){this.Apply0=n,this.bind=t},t.bind=function(n){return n.bind}}(n["Control.Bind"]=n["Control.Bind"]||{}),function(n){"use strict";n.length=function(n){return n.length},n.indexImpl=function(n){return function(t){return function(r){return function(a){return a<0||a>=r.length?t:n(r[a])}}}},n.slice=function(n){return function(t){return function(r){return r.slice(n,t)}}},n.drop=function(n){return function(t){return n<1?t:t.slice(n)}}}(n["Data.Array"]=n["Data.Array"]||{}),function(t){"use strict";n["Data.Show"],n["Data.Symbol"],n["Record.Unsafe"],n["Type.Data.RowList"];t.Show=function(n){this.show=n},t.show=function(n){return n.show}}(n["Data.Show"]=n["Data.Show"]||{}),function(t){"use strict";n["Control.Alt"],n["Control.Alternative"],n["Control.Applicative"];var r=n["Control.Apply"],a=n["Control.Bind"],e=(n["Control.Category"],n["Control.Extend"],n["Control.Monad"],n["Control.MonadZero"],n["Control.Plus"],n["Data.Bounded"],n["Data.Eq"],n["Data.Function"],n["Data.Functor"]),o=(n["Data.Functor.Invariant"],n["Data.Monoid"],n["Data.Ord"],n["Data.Ordering"],n["Data.Semigroup"],n["Data.Show"],n["Data.Unit"],n.Prelude,function(){function n(){}return n.value=new n,n}()),i=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),u=new e.Functor(function(n){return function(t){return t instanceof i?new i(n(t.value0)):o.value}}),c=new r.Apply(function(){return u},function(n){return function(t){if(n instanceof i)return e.map(u)(n.value0)(t);if(n instanceof o)return o.value;throw new Error("Failed pattern match at Data.Maybe (line 67, column 1 - line 67, column 35): "+[n.constructor.name,t.constructor.name])}}),f=new a.Bind(function(){return c},function(n){return function(t){if(n instanceof i)return t(n.value0);if(n instanceof o)return o.value;throw new Error("Failed pattern match at Data.Maybe (line 125, column 1 - line 125, column 33): "+[n.constructor.name,t.constructor.name])}});t.Nothing=o,t.Just=i,t.maybe=function(n){return function(t){return function(r){if(r instanceof o)return n;if(r instanceof i)return t(r.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[n.constructor.name,t.constructor.name,r.constructor.name])}}},t.functorMaybe=u,t.applyMaybe=c,t.bindMaybe=f}(n["Data.Maybe"]=n["Data.Maybe"]||{}),function(t){"use strict";(n["Partial.Unsafe"]=n["Partial.Unsafe"]||{}).unsafePartial=function(n){return n()}}(),function(t){"use strict";(n["Partial"]=n["Partial"]||{}).crashWith=function(){return function(n){throw new Error(n)}}}(),function(t){"use strict";var r=n.Partial;t.crashWith=r.crashWith}(n.Partial=n.Partial||{}),function(t){"use strict";var r=n["Partial.Unsafe"],a=n.Partial;t.unsafeCrashWith=function(n){return r.unsafePartial(function(t){return a.crashWith(t)(n)})}}(n["Partial.Unsafe"]=n["Partial.Unsafe"]||{}),function(t){"use strict";(n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{}).unsafeCoerce=function(n){return n}}(),function(t){"use strict";var r=n["Unsafe.Coerce"];t.unsafeCoerce=r.unsafeCoerce}(n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{}),function(t){"use strict";var r=n["Data.Array"],a=(n["Control.Alt"],n["Control.Alternative"],n["Control.Applicative"],n["Control.Apply"],n["Control.Bind"],n["Control.Category"],n["Control.Lazy"],n["Control.Monad.Rec.Class"],n["Control.Monad.ST"],n["Control.Monad.ST.Internal"],n["Control.Semigroupoid"],n["Data.Array.NonEmpty.Internal"],n["Data.Array.ST"],n["Data.Array.ST.Iterator"],n["Data.Boolean"],n["Data.Eq"],n["Data.Foldable"],n["Data.Function"],n["Data.Functor"],n["Data.HeytingAlgebra"],n["Data.Maybe"]),e=(n["Data.Ord"],n["Data.Ordering"],n["Data.Ring"],n["Data.Semigroup"],n["Data.Semiring"],n["Data.Traversable"],n["Data.Tuple"],n["Data.Unfoldable"],n["Partial.Unsafe"],n.Prelude,n["Unsafe.Coerce"],r.indexImpl(a.Just.create)(a.Nothing.value));t.head=function(n){return e(n)(0)},t.index=e,t.drop=r.drop}(n["Data.Array"]=n["Data.Array"]||{}),function(t){"use strict";n["Control.Alt"];var r=n["Control.Applicative"],a=n["Control.Apply"],e=n["Control.Bind"],o=(n["Control.Extend"],n["Control.Monad"],n["Control.Semigroupoid"],n["Data.Bifoldable"],n["Data.Bifunctor"],n["Data.Bitraversable"],n["Data.Bounded"],n["Data.Eq"],n["Data.Foldable"],n["Data.FoldableWithIndex"],n["Data.Function"],n["Data.Functor"]),i=(n["Data.Functor.Invariant"],n["Data.FunctorWithIndex"],n["Data.Maybe"]),u=(n["Data.Monoid"],n["Data.Ord"],n["Data.Ordering"],n["Data.Semigroup"],n["Data.Show"],n["Data.Traversable"],n["Data.TraversableWithIndex"],n["Data.Unit"],n.Prelude,function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}()),c=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),f=new o.Functor(function(n){return function(t){if(t instanceof u)return new u(t.value0);if(t instanceof c)return new c(n(t.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[t.constructor.name])}}),l=function(n){return function(t){return function(r){if(r instanceof u)return n(r.value0);if(r instanceof c)return t(r.value0);throw new Error("Failed pattern match at Data.Either (line 238, column 1 - line 238, column 64): "+[n.constructor.name,t.constructor.name,r.constructor.name])}}},s=new a.Apply(function(){return f},function(n){return function(t){if(n instanceof u)return new u(n.value0);if(n instanceof c)return o.map(f)(n.value0)(t);throw new Error("Failed pattern match at Data.Either (line 82, column 1 - line 82, column 41): "+[n.constructor.name,t.constructor.name])}}),d=new e.Bind(function(){return s},l(function(n){return function(t){return new u(n)}})(function(n){return function(t){return t(n)}})),D=new r.Applicative(function(){return s},c.create);t.Left=u,t.Right=c,t.either=l,t.note=function(n){return i.maybe(new u(n))(c.create)},t.functorEither=f,t.applyEither=s,t.applicativeEither=D,t.bindEither=d}(n["Data.Either"]=n["Data.Either"]||{}),function(t){"use strict";(n["Data.Int"]=n["Data.Int"]||{}).fromStringAsImpl=function(n){return function(t){return function(r){var a;a=r<11?"[0-"+(r-1).toString()+"]":11===r?"[0-9a]":"[0-9a-"+String.fromCharCode(86+r)+"]";var e=new RegExp("^[\\+\\-]?"+a+"+$","i");return function(a){if(e.test(a)){var o=parseInt(a,r);return(0|o)===o?n(o):t}return t}}}}}(),function(t){"use strict";var r=n["Data.Int"],a=(n["Control.Category"],n["Control.Semigroupoid"],n["Data.Boolean"],n["Data.Bounded"],n["Data.CommutativeRing"],n["Data.DivisionRing"],n["Data.Eq"],n["Data.EuclideanRing"],n["Data.HeytingAlgebra"],n["Data.Int.Bits"],n["Data.Maybe"]),e=(n["Data.Ord"],n["Data.Ordering"],n["Data.Ring"],n["Data.Semiring"],n["Data.Show"],n.Global,n.Math,n.Prelude,r.fromStringAsImpl(a.Just.create)(a.Nothing.value)),o=e(10);t.fromString=o,t.fromStringAs=e}(n["Data.Int"]=n["Data.Int"]||{}),function(n){"use strict";n.fromCharArray=function(n){return n.join("")},n.toCharArray=function(n){return n.split("")},n._charAt=function(n){return function(t){return function(r){return function(a){return r>=0&&r<a.length?n(a.charAt(r)):t}}}},n.length=function(n){return n.length}}(n["Data.String.CodeUnits"]=n["Data.String.CodeUnits"]||{}),function(t){"use strict";var r=n["Data.String.CodeUnits"],a=(n["Control.Semigroupoid"],n["Data.Boolean"],n["Data.Eq"],n["Data.Function"],n["Data.HeytingAlgebra"],n["Data.Maybe"]),e=(n["Data.Ord"],n["Data.Ring"],n["Data.Semiring"],n["Data.String.Pattern"],n["Data.String.Unsafe"],n.Prelude,r._charAt(a.Just.create)(a.Nothing.value));t.charAt=e,t.fromCharArray=r.fromCharArray,t.toCharArray=r.toCharArray}(n["Data.String.CodeUnits"]=n["Data.String.CodeUnits"]||{}),function(n){"use strict";n.split=function(n){return function(t){return t.split(n)}},n.trim=function(n){return n.trim()}}(n["Data.String.Common"]=n["Data.String.Common"]||{}),function(t){"use strict";var r=n["Data.String.Common"];n["Data.Eq"],n["Data.Ordering"],n["Data.String.Pattern"],n.Prelude;t.split=r.split,t.trim=r.trim}(n["Data.String.Common"]=n["Data.String.Common"]||{}),function(t){"use strict";var r=n["Control.Applicative"],a=n["Control.Bind"],e=n["Control.Category"],o=n["Data.Array"],i=n["Data.Either"],u=(n["Data.Eq"],n["Data.Functor"]),c=n["Data.Int"],f=n["Data.Maybe"],l=(n["Data.Ring"],n["Data.String"],n["Data.String.CodeUnits"]),s=n["Data.String.Common"],d=(n["Data.String.Pattern"],n["Partial.Unsafe"]);n.Prelude;t.solve=function(n){return i.either(function(n){return d.unsafeCrashWith(n)})(e.identity(e.categoryFn))((t=s.split("\n")(s.trim(n)),a.bind(i.bindEither)(i.note("n")(a.bind(f.bindMaybe)(o.head(t))(c.fromString)))(function(n){return a.bind(i.bindEither)(i.note("s")(o.head(o.drop(1)(t))))(function(n){return a.bind(i.bindEither)(i.note("k")(a.bind(f.bindMaybe)(o.head(o.drop(2)(t)))(c.fromString)))(function(t){return a.bind(i.bindEither)(i.note("x")(l.charAt(t-1|0)(n)))(function(t){return r.pure(i.applicativeEither)(l.fromCharArray(u.map(u.functorArray)(function(n){return n===t?n:"*"})(l.toCharArray(n))))})})})})));var t}}(n["AtCoder.Tenka12019Beginner.B"]=n["AtCoder.Tenka12019Beginner.B"]||{}),function(t){"use strict";(n["Effect.Console"]=n["Effect.Console"]||{}).log=function(n){return function(){return console.log(n),{}}}}(),function(t){"use strict";var r=n["Effect.Console"];n["Data.Show"],n["Data.Unit"],n.Effect;t.log=r.log}(n["Effect.Console"]=n["Effect.Console"]||{}),function(t){"use strict";n["Node.Encoding"];var r=n["Data.Show"],a=(n.Prelude,function(){function n(){}return n.value=new n,n}()),e=function(){function n(){}return n.value=new n,n}(),o=function(){function n(){}return n.value=new n,n}(),i=function(){function n(){}return n.value=new n,n}(),u=function(){function n(){}return n.value=new n,n}(),c=function(){function n(){}return n.value=new n,n}(),f=function(){function n(){}return n.value=new n,n}(),l=function(){function n(){}return n.value=new n,n}(),s=new r.Show(function(n){if(n instanceof a)return"ASCII";if(n instanceof e)return"UTF8";if(n instanceof o)return"UTF16LE";if(n instanceof i)return"UCS2";if(n instanceof u)return"Base64";if(n instanceof c)return"Latin1";if(n instanceof f)return"Binary";if(n instanceof l)return"Hex";throw new Error("Failed pattern match at Node.Encoding (line 19, column 1 - line 19, column 39): "+[n.constructor.name])});t.ASCII=a,t.UTF8=e,t.UTF16LE=o,t.UCS2=i,t.Base64=u,t.Latin1=c,t.Binary=f,t.Hex=l,t.showEncoding=s}(n["Node.Encoding"]=n["Node.Encoding"]||{}),function(t){"use strict";(n["Node.FS.Internal"]=n["Node.FS.Internal"]||{}).unsafeRequireFS=require("fs")}(),function(t){"use strict";var r=n["Node.FS.Internal"],a=(n.Effect,n.Prelude,n["Unsafe.Coerce"].unsafeCoerce);t.mkEffect=a,t.unsafeRequireFS=r.unsafeRequireFS}(n["Node.FS.Internal"]=n["Node.FS.Internal"]||{}),function(t){"use strict";n["Control.Bind"],n["Control.Semigroupoid"],n["Data.DateTime"],n["Data.DateTime.Instant"],n["Data.EuclideanRing"],n["Data.Function"],n["Data.Function.Uncurried"],n["Data.Functor"],n["Data.Int"],n["Data.Maybe"],n["Data.Nullable"];var r=n["Data.Show"],a=(n["Data.Time.Duration"],n.Effect,n["Node.Buffer"],n["Node.Encoding"]),e=(n["Node.FS"],n["Node.FS.Internal"]),o=(n["Node.FS.Perms"],n["Node.FS.Stats"],n["Node.Path"],n.Prelude,e.unsafeRequireFS);t.readTextFile=function(n){return function(t){return e.mkEffect(function(e){return o.readFileSync(t,{encoding:r.show(a.showEncoding)(n)})})}}}(n["Node.FS.Sync"]=n["Node.FS.Sync"]||{}),function(t){"use strict";var r=n["AtCoder.Tenka12019Beginner.B"],a=(n["Control.Applicative"],n["Control.Bind"],n.Effect,n["Effect.Console"]),e=n["Node.Encoding"],o=n["Node.FS.Sync"];n.Prelude;t.main=function(){var n=o.readTextFile(e.UTF8.value)("/dev/stdin")(),t=r.solve(n);return a.log(t)()}}(n.Main=n.Main||{}),n.Main.main();
},{}]},{},["Focm"], null)


parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"Focm":[function(require,module,exports) {
var t={};!function(t){"use strict";var n=function(t){this.compose=t},a=new n(function(t){return function(n){return function(a){return t(n(a))}}});t.compose=function(t){return t.compose},t.Semigroupoid=n,t.semigroupoidFn=a}(t["Control.Semigroupoid"]=t["Control.Semigroupoid"]||{}),function(n){"use strict";var a=t["Control.Semigroupoid"],r=function(t,n){this.Semigroupoid0=t,this.identity=n},e=new r(function(){return a.semigroupoidFn},function(t){return t});n.Category=r,n.identity=function(t){return t.identity},n.categoryFn=e}(t["Control.Category"]=t["Control.Category"]||{}),function(n){"use strict";(t["Data.Boolean"]=t["Data.Boolean"]||{}).otherwise=!0}(),function(n){"use strict";t["Control.Category"],t["Data.Boolean"],t["Data.Ord"],t["Data.Ring"];n.const=function(t){return function(n){return t}}}(t["Data.Function"]=t["Data.Function"]||{}),function(n){"use strict";t["Data.Functor"],t["Control.Semigroupoid"],t["Data.Function"],t["Data.Unit"];n.Functor=function(t){this.map=t},n.map=function(t){return t.map}}(t["Data.Functor"]=t["Data.Functor"]||{}),function(n){"use strict";t["Control.Apply"],t["Control.Category"],t["Data.Function"],t["Data.Functor"];n.Apply=function(t,n){this.Functor0=t,this.apply=n},n.apply=function(t){return t.apply}}(t["Control.Apply"]=t["Control.Apply"]||{}),function(n){"use strict";t["Control.Apply"],t["Data.Functor"],t["Data.Unit"];n.Applicative=function(t,n){this.Apply0=t,this.pure=n},n.pure=function(t){return t.pure}}(t["Control.Applicative"]=t["Control.Applicative"]||{}),function(n){"use strict";t["Control.Bind"],t["Control.Applicative"],t["Control.Apply"],t["Control.Category"],t["Data.Function"],t["Data.Functor"],t["Data.Unit"];n.Bind=function(t,n){this.Apply0=t,this.bind=n},n.bind=function(t){return t.bind}}(t["Control.Bind"]=t["Control.Bind"]||{}),function(n){"use strict";(t["Data.Eq"]=t["Data.Eq"]||{}).refEq=function(t){return function(n){return t===n}}}(),function(n){"use strict";var a=t["Data.Eq"],r=(t["Data.HeytingAlgebra"],t["Data.Symbol"],t["Data.Unit"],t["Data.Void"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t){this.eq=t}),e=new r(a.refEq);n.Eq=r,n.eq=function(t){return t.eq},n.eqChar=e}(t["Data.Eq"]=t["Data.Eq"]||{}),function(n){"use strict";(t["Data.Show"]=t["Data.Show"]||{}).showIntImpl=function(t){return t.toString()}}(),function(n){"use strict";var a=t["Data.Show"],r=(t["Data.Symbol"],t["Record.Unsafe"],t["Type.Data.RowList"],function(t){this.show=t}),e=new r(a.showIntImpl);n.Show=r,n.show=function(t){return t.show},n.showInt=e}(t["Data.Show"]=t["Data.Show"]||{}),function(n){"use strict";t["Control.Alt"],t["Control.Alternative"],t["Control.Applicative"];var a=t["Control.Apply"],r=t["Control.Bind"],e=(t["Control.Category"],t["Control.Extend"],t["Control.Monad"],t["Control.MonadZero"],t["Control.Plus"],t["Data.Bounded"],t["Data.Eq"],t["Data.Function"]),o=t["Data.Functor"],i=(t["Data.Functor.Invariant"],t["Data.Monoid"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"],t["Data.Show"],t["Data.Unit"],t.Prelude,function(){function t(){}return t.value=new t,t}()),u=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}(),c=function(t){return function(n){return function(a){if(a instanceof i)return t;if(a instanceof u)return n(a.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[t.constructor.name,n.constructor.name,a.constructor.name])}}},l=c(!0)(e.const(!1)),f=new o.Functor(function(t){return function(n){return n instanceof u?new u(t(n.value0)):i.value}}),s=new a.Apply(function(){return f},function(t){return function(n){if(t instanceof u)return o.map(f)(t.value0)(n);if(t instanceof i)return i.value;throw new Error("Failed pattern match at Data.Maybe (line 67, column 1 - line 67, column 35): "+[t.constructor.name,n.constructor.name])}}),D=new r.Bind(function(){return s},function(t){return function(n){if(t instanceof u)return n(t.value0);if(t instanceof i)return i.value;throw new Error("Failed pattern match at Data.Maybe (line 125, column 1 - line 125, column 33): "+[t.constructor.name,n.constructor.name])}});n.Nothing=i,n.Just=u,n.maybe=c,n.isNothing=l,n.fromJust=function(t){return function(t){if(t instanceof u)return t.value0;throw new Error("Failed pattern match at Data.Maybe (line 268, column 1 - line 268, column 46): "+[t.constructor.name])}},n.functorMaybe=f,n.applyMaybe=s,n.bindMaybe=D}(t["Data.Maybe"]=t["Data.Maybe"]||{}),function(n){"use strict";t["Control.Alt"];var a=t["Control.Applicative"],r=t["Control.Apply"],e=t["Control.Bind"],o=(t["Control.Extend"],t["Control.Monad"],t["Control.Semigroupoid"],t["Data.Bifoldable"],t["Data.Bifunctor"],t["Data.Bitraversable"],t["Data.Bounded"],t["Data.Eq"],t["Data.Foldable"],t["Data.FoldableWithIndex"],t["Data.Function"],t["Data.Functor"]),i=(t["Data.Functor.Invariant"],t["Data.FunctorWithIndex"],t["Data.Maybe"]),u=(t["Data.Monoid"],t["Data.Ord"],t["Data.Ordering"],t["Data.Semigroup"],t["Data.Show"],t["Data.Traversable"],t["Data.TraversableWithIndex"],t["Data.Unit"],t.Prelude,function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}()),c=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}(),l=new o.Functor(function(t){return function(n){if(n instanceof u)return new u(n.value0);if(n instanceof c)return new c(t(n.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[n.constructor.name])}}),f=function(t){return function(n){return function(a){if(a instanceof u)return t(a.value0);if(a instanceof c)return n(a.value0);throw new Error("Failed pattern match at Data.Either (line 238, column 1 - line 238, column 64): "+[t.constructor.name,n.constructor.name,a.constructor.name])}}},s=new r.Apply(function(){return l},function(t){return function(n){if(t instanceof u)return new u(t.value0);if(t instanceof c)return o.map(l)(t.value0)(n);throw new Error("Failed pattern match at Data.Either (line 82, column 1 - line 82, column 41): "+[t.constructor.name,n.constructor.name])}}),D=new e.Bind(function(){return s},f(function(t){return function(n){return new u(t)}})(function(t){return function(n){return n(t)}})),d=new a.Applicative(function(){return s},c.create);n.Left=u,n.Right=c,n.either=f,n.note=function(t){return i.maybe(new u(t))(c.create)},n.functorEither=l,n.applyEither=s,n.applicativeEither=d,n.bindEither=D}(t["Data.Either"]=t["Data.Either"]||{}),function(n){"use strict";(t["Partial.Unsafe"]=t["Partial.Unsafe"]||{}).unsafePartial=function(t){return t()}}(),function(n){"use strict";(t["Partial"]=t["Partial"]||{}).crashWith=function(){return function(t){throw new Error(t)}}}(),function(n){"use strict";var a=t.Partial;n.crashWith=a.crashWith}(t.Partial=t.Partial||{}),function(n){"use strict";var a=t["Partial.Unsafe"],r=t.Partial;n.unsafeCrashWith=function(t){return a.unsafePartial(function(n){return r.crashWith(n)(t)})}}(t["Partial.Unsafe"]=t["Partial.Unsafe"]||{}),function(n){"use strict";t["Control.Applicative"],t["Control.Bind"],t["Control.Monad"],t["Control.Semigroupoid"],t["Data.Bifunctor"],t["Data.Either"],t["Data.Functor"],t["Data.Identity"],t["Data.Maybe"],t["Data.Unit"],t.Effect,t["Effect.Ref"],t["Partial.Unsafe"],t.Prelude;var a=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}(),r=function(){function t(t){this.value0=t}return t.create=function(n){return new t(n)},t}();n.Loop=a,n.Done=r,n.tailRec=function(t){return function(n){return function(n){var e,o=!1;function i(e){if(!(e instanceof a)){if(e instanceof r)return o=!0,e.value0;throw new Error("Failed pattern match at Control.Monad.Rec.Class (line 91, column 3 - line 91, column 25): "+[e.constructor.name])}n=t(e.value0)}for(;!o;)e=i(n);return e}(t(n))}}}(t["Control.Monad.Rec.Class"]=t["Control.Monad.Rec.Class"]||{}),function(t){"use strict";t.length=function(t){return t.length},t.indexImpl=function(t){return function(n){return function(a){return function(r){return r<0||r>=a.length?n:t(a[r])}}}},t.filter=function(t){return function(n){return n.filter(t)}},t.slice=function(t){return function(n){return function(a){return a.slice(t,n)}}},t.drop=function(t){return function(n){return t<1?n:n.slice(t)}}}(t["Data.Array"]=t["Data.Array"]||{}),function(n){"use strict";t["Control.Applicative"],t["Control.Apply"],t["Control.Biapplicative"],t["Control.Biapply"],t["Control.Bind"],t["Control.Comonad"],t["Control.Extend"],t["Control.Lazy"],t["Control.Monad"],t["Control.Semigroupoid"],t["Data.Bifoldable"],t["Data.Bifunctor"],t["Data.Bitraversable"],t["Data.BooleanAlgebra"],t["Data.Bounded"],t["Data.CommutativeRing"],t["Data.Distributive"],t["Data.Eq"],t["Data.Foldable"],t["Data.FoldableWithIndex"],t["Data.Function"],t["Data.Functor"],t["Data.Functor.Invariant"],t["Data.FunctorWithIndex"],t["Data.HeytingAlgebra"],t["Data.Maybe"],t["Data.Maybe.First"],t["Data.Monoid"],t["Data.Newtype"],t["Data.Ord"],t["Data.Ordering"],t["Data.Ring"],t["Data.Semigroup"],t["Data.Semigroup.Foldable"],t["Data.Semigroup.Traversable"],t["Data.Semiring"],t["Data.Show"],t["Data.Traversable"],t["Data.TraversableWithIndex"],t["Data.Unit"],t.Prelude,t["Type.Equality"];var a=function(){function t(t,n){this.value0=t,this.value1=n}return t.create=function(n){return function(a){return new t(n,a)}},t}();n.Tuple=a}(t["Data.Tuple"]=t["Data.Tuple"]||{}),function(n){"use strict";(t["Unsafe.Coerce"]=t["Unsafe.Coerce"]||{}).unsafeCoerce=function(t){return t}}(),function(n){"use strict";var a=t["Unsafe.Coerce"];n.unsafeCoerce=a.unsafeCoerce}(t["Unsafe.Coerce"]=t["Unsafe.Coerce"]||{}),function(n){"use strict";var a=t["Data.Array"],r=(t["Control.Alt"],t["Control.Alternative"],t["Control.Applicative"],t["Control.Apply"],t["Control.Bind"],t["Control.Category"],t["Control.Lazy"],t["Control.Monad.Rec.Class"],t["Control.Monad.ST"],t["Control.Monad.ST.Internal"],t["Control.Semigroupoid"],t["Data.Array.NonEmpty.Internal"],t["Data.Array.ST"],t["Data.Array.ST.Iterator"],t["Data.Boolean"],t["Data.Eq"],t["Data.Foldable"],t["Data.Function"],t["Data.Functor"],t["Data.HeytingAlgebra"],t["Data.Maybe"]),e=(t["Data.Ord"],t["Data.Ordering"],t["Data.Ring"],t["Data.Semigroup"],t["Data.Semiring"],t["Data.Traversable"],t["Data.Tuple"],t["Data.Unfoldable"],t["Partial.Unsafe"],t.Prelude,t["Unsafe.Coerce"],a.indexImpl(r.Just.create)(r.Nothing.value));n.head=function(t){return e(t)(0)},n.index=e,n.length=a.length,n.filter=a.filter,n.drop=a.drop}(t["Data.Array"]=t["Data.Array"]||{}),function(n){"use strict";(t["Data.Int"]=t["Data.Int"]||{}).fromStringAsImpl=function(t){return function(n){return function(a){var r;r=a<11?"[0-"+(a-1).toString()+"]":11===a?"[0-9a]":"[0-9a-"+String.fromCharCode(86+a)+"]";var e=new RegExp("^[\\+\\-]?"+r+"+$","i");return function(r){if(e.test(r)){var o=parseInt(r,a);return(0|o)===o?t(o):n}return n}}}}}(),function(n){"use strict";var a=t["Data.Int"],r=(t["Control.Category"],t["Control.Semigroupoid"],t["Data.Boolean"],t["Data.Bounded"],t["Data.CommutativeRing"],t["Data.DivisionRing"],t["Data.Eq"],t["Data.EuclideanRing"],t["Data.HeytingAlgebra"],t["Data.Int.Bits"],t["Data.Maybe"]),e=(t["Data.Ord"],t["Data.Ordering"],t["Data.Ring"],t["Data.Semiring"],t["Data.Show"],t.Global,t.Math,t.Prelude,a.fromStringAsImpl(r.Just.create)(r.Nothing.value)),o=e(10);n.fromString=o,n.fromStringAs=e}(t["Data.Int"]=t["Data.Int"]||{}),function(t){"use strict";t.toCharArray=function(t){return t.split("")},t.length=function(t){return t.length},t["_indexOf'"]=function(t){return function(n){return function(a){return function(r){return function(e){if(r<0||r>e.length)return n;var o=e.indexOf(a,r);return-1===o?n:t(o)}}}}},t._slice=function(t){return function(n){return function(a){return a.slice(t,n)}}}}(t["Data.String.CodeUnits"]=t["Data.String.CodeUnits"]||{}),function(n){"use strict";var a=t["Data.String.CodeUnits"],r=(t["Control.Semigroupoid"],t["Data.Boolean"]),e=(t["Data.Eq"],t["Data.Function"],t["Data.HeytingAlgebra"],t["Data.Maybe"]),o=(t["Data.Ord"],t["Data.Ring"],t["Data.Semiring"],t["Data.String.Pattern"],t["Data.String.Unsafe"],t.Prelude,a["_indexOf'"](e.Just.create)(e.Nothing.value));n["indexOf'"]=o,n.slice=function(t){return function(n){return function(o){var i=a.length(o),u=function(t){if(t<0)return i+t|0;if(r.otherwise)return t;throw new Error("Failed pattern match at Data.String.CodeUnits (line 314, column 5 - line 315, column 27): "+[t.constructor.name])},c=u(n),l=u(t);return l<0||l>=i||c<0||c>i||l>c?e.Nothing.value:new e.Just(a._slice(t)(n)(o))}}},n.toCharArray=a.toCharArray,n.length=a.length}(t["Data.String.CodeUnits"]=t["Data.String.CodeUnits"]||{}),function(t){"use strict";t.split=function(t){return function(n){return n.split(t)}},t.trim=function(t){return t.trim()}}(t["Data.String.Common"]=t["Data.String.Common"]||{}),function(n){"use strict";var a=t["Data.String.Common"];t["Data.Eq"],t["Data.Ordering"],t["Data.String.Pattern"],t.Prelude;n.split=a.split,n.trim=a.trim}(t["Data.String.Common"]=t["Data.String.Common"]||{}),function(n){"use strict";var a=t["Control.Applicative"],r=t["Control.Bind"],e=t["Control.Category"],o=t["Control.Monad.Rec.Class"],i=t["Data.Array"],u=t["Data.Either"],c=t["Data.Eq"],l=t["Data.Int"],f=t["Data.Maybe"],s=(t["Data.Semiring"],t["Data.Show"]),D=(t["Data.String"],t["Data.String.CodeUnits"]),d=t["Data.String.Common"],p=(t["Data.String.Pattern"],t["Data.Tuple"]),C=t["Partial.Unsafe"];t.Prelude;n.solve=function(t){return u.either(function(t){return C.unsafeCrashWith(t)})(e.identity(e.categoryFn))((n=d.split("\n")(d.trim(t)),r.bind(u.bindEither)(u.note("n")(r.bind(f.bindMaybe)(i.head(n))(l.fromString)))(function(t){return r.bind(u.bindEither)(u.note("s")(i.head(i.drop(1)(n))))(function(t){return a.pure(u.applicativeEither)(s.show(s.showInt)((n=t,o.tailRec(function(t){var a=D["indexOf'"]("#.")(t.value0)(n);if(a instanceof f.Nothing)return new o.Done(t.value1);if(a instanceof f.Just)return f.isNothing(D["indexOf'"]("#.")(a.value0+2|0)(n))?new o.Loop(new p.Tuple(a.value0+1|0,t.value1+1|0)):new o.Done(t.value1+i.length(i.filter(c.eq(c.eqChar)("."))(D.toCharArray(f.fromJust()(D.slice(a.value0+1|0)(D.length(n))(n)))))|0);throw new Error("Failed pattern match at AtCoder.Tenka12019Beginner.C (line 30, column 7 - line 37, column 177): "+[a.constructor.name])})(new p.Tuple(0,0)))));var n})})));var n}}(t["AtCoder.Tenka12019Beginner.C"]=t["AtCoder.Tenka12019Beginner.C"]||{}),function(n){"use strict";(t["Effect.Console"]=t["Effect.Console"]||{}).log=function(t){return function(){return console.log(t),{}}}}(),function(n){"use strict";var a=t["Effect.Console"];t["Data.Show"],t["Data.Unit"],t.Effect;n.log=a.log}(t["Effect.Console"]=t["Effect.Console"]||{}),function(n){"use strict";t["Node.Encoding"];var a=t["Data.Show"],r=(t.Prelude,function(){function t(){}return t.value=new t,t}()),e=function(){function t(){}return t.value=new t,t}(),o=function(){function t(){}return t.value=new t,t}(),i=function(){function t(){}return t.value=new t,t}(),u=function(){function t(){}return t.value=new t,t}(),c=function(){function t(){}return t.value=new t,t}(),l=function(){function t(){}return t.value=new t,t}(),f=function(){function t(){}return t.value=new t,t}(),s=new a.Show(function(t){if(t instanceof r)return"ASCII";if(t instanceof e)return"UTF8";if(t instanceof o)return"UTF16LE";if(t instanceof i)return"UCS2";if(t instanceof u)return"Base64";if(t instanceof c)return"Latin1";if(t instanceof l)return"Binary";if(t instanceof f)return"Hex";throw new Error("Failed pattern match at Node.Encoding (line 19, column 1 - line 19, column 39): "+[t.constructor.name])});n.ASCII=r,n.UTF8=e,n.UTF16LE=o,n.UCS2=i,n.Base64=u,n.Latin1=c,n.Binary=l,n.Hex=f,n.showEncoding=s}(t["Node.Encoding"]=t["Node.Encoding"]||{}),function(n){"use strict";(t["Node.FS.Internal"]=t["Node.FS.Internal"]||{}).unsafeRequireFS=require("fs")}(),function(n){"use strict";var a=t["Node.FS.Internal"],r=(t.Effect,t.Prelude,t["Unsafe.Coerce"].unsafeCoerce);n.mkEffect=r,n.unsafeRequireFS=a.unsafeRequireFS}(t["Node.FS.Internal"]=t["Node.FS.Internal"]||{}),function(n){"use strict";t["Control.Bind"],t["Control.Semigroupoid"],t["Data.DateTime"],t["Data.DateTime.Instant"],t["Data.EuclideanRing"],t["Data.Function"],t["Data.Function.Uncurried"],t["Data.Functor"],t["Data.Int"],t["Data.Maybe"],t["Data.Nullable"];var a=t["Data.Show"],r=(t["Data.Time.Duration"],t.Effect,t["Node.Buffer"],t["Node.Encoding"]),e=(t["Node.FS"],t["Node.FS.Internal"]),o=(t["Node.FS.Perms"],t["Node.FS.Stats"],t["Node.Path"],t.Prelude,e.unsafeRequireFS);n.readTextFile=function(t){return function(n){return e.mkEffect(function(e){return o.readFileSync(n,{encoding:a.show(r.showEncoding)(t)})})}}}(t["Node.FS.Sync"]=t["Node.FS.Sync"]||{}),function(n){"use strict";var a=t["AtCoder.Tenka12019Beginner.C"],r=(t["Control.Applicative"],t["Control.Bind"],t.Effect,t["Effect.Console"]),e=t["Node.Encoding"],o=t["Node.FS.Sync"];t.Prelude;n.main=function(){var t=o.readTextFile(e.UTF8.value)("/dev/stdin")(),n=a.solve(t);return r.log(n)()}}(t.Main=t.Main||{}),t.Main.main();
},{}]},{},["Focm"], null)

Score : 300 points

Problem Statement

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

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

Constraints

1 \leq N \leq 2\times 10^5

S is a string of length N consisting of . and #.

Input

Input is given from Standard Input in the following format:

N
S

Output

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

Sample Input 1

3
#.#

Sample Output 1

1

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

Sample Input 2

5
#.##.

Sample Output 2

2

Sample Input 3

9
.........

Sample Output 3

0


"use strict";

function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0], 10);
  var S = input[1];
  var s = [...S];
  var firstB = s.indexOf("#");
  var toB = 0;

  if (firstB >= 0) {
    for (var i = firstB; i < N; i++) {
      if (s[i] != "#") {
        toB++;
      }
    }
  }

  var lastW = s.lastIndexOf(".");
  var toW = 0;

  if (lastW >= 0) {
    for (var _i = 0; _i < lastW; _i++) {
      if (s[_i] != ".") {
        toW++;
      }
    }
  }

  var blackNum = 0;

  for (var _i2 = 0; _i2 < N; _i2++) {
    if (s[_i2] == "#") {
      blackNum++;
    }
  }

  console.log(Math.min(blackNum, toW, toB));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));