const Main = (input) => {
 const nSplitted = input.split(" ");
  const X = Number(nSplitted[0]);
  const A = Number(nSplitted[1]);
  if (X < 0 || X > 10 || A < 0 || A > 10) {
  	return;
  }
  var result = 10;
  if (X < A) {
  	result = 0;
  }
  console.log(result);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 100 points

Problem Statement

X and A are integers between 0 and 9 (inclusive).

If X is less than A, print 0; if X is not less than A, print 10.

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

If X is less than A, print 0; if X is not less than A, print 10.

Sample Input 1

3 5

Sample Output 1

0

3 is less than 5, so we should print 0.

Sample Input 2

7 5

Sample Output 2

10

7 is not less than 5, so we should print 10.

Sample Input 3

6 6

Sample Output 3

10

6 is not less than 6, so we should print 10.


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

b = 0;

if (X >= A) {
	b = 10;
}

 console.log(b);

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.


function Main(input) {
    var X = parseInt(input[0], 10);
    var A = parseInt(input[1], 10);

    console.log(X < A ? '0' : '10');
}

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


function Main(input) {
    const N = parseInt(input.shift())
    const X = parseInt(input.shift())
    const Ls = input.map(x => parseInt(x));

    var current = 0;
    var sum = 1;
    for (var i = 0; i < N; i++) {
        current += Ls[i];
        if(current <= X) {
            sum++;
        }
    }
    console.log(sum);
}

// 1行入力の場合
// Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());

// 改行で分割
// Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n/));

// 改行・空白で分割
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n|\s/));

Score : 200 points

Problem Statement

A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.

How many times will the ball make a bounce where the coordinate is at most X?

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 100

1 \leq X \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X
L_1 L_2 ... L_{N-1} L_N

Output

Print the number of times the ball will make a bounce where the coordinate is at most X.

Sample Input 1

3 6
3 4 5

Sample Output 1

2

The ball will make a bounce at the coordinates 0, 3, 7 and 12, among which two are less than or equal to 6.

Sample Input 2

4 9
3 3 3 3

Sample Output 2

4

The ball will make a bounce at the coordinates 0, 3, 6, 9 and 12, among which four are less than or equal to 9.


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 k = o.a();
  if(k === 1)return 0;
  return n-k;
}

Score : 100 points

Problem Statement

Takahashi is distributing N balls to K persons.

If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?

Constraints

1 \leq K \leq N \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the maximum possible difference in the number of balls received.

Sample Input 1

3 2

Sample Output 1

1

The only way to distribute three balls to two persons so that each of them receives at least one ball is to give one ball to one person and give two balls to the other person.

Thus, the maximum possible difference in the number of balls received is 1.

Sample Input 2

3 1

Sample Output 2

0

We have no choice but to give three balls to the only person, in which case the difference in the number of balls received is 0.

Sample Input 3

8 5

Sample Output 3

3

For example, if we give 1, 4, 1, 1, 1 balls to the five persons, the number of balls received between the person with the most balls and the person with the fewest balls would be 3, which is the maximum result.


var lines = [];

var readline = require('readline');

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

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

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

    var result = Infinity

    for (var i = 0; i < N; i++) {
        var S1 = 0; var S2 = 0;;

        for (var j = 0; j < i; j++) { S1 += W[j] }
        for (var j = i; j < N; j++) { S2 += W[j] }

        result = Math.min(Math.abs(S1 - S2),result)
    }
    console.log(result)
});

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


var memo = [1];
function Main(input) {
    var result;
    const N = parseInt(input.shift());
    const M = parseInt(input.shift());
    const As = input.map(a => parseInt(a)).filter(function (x, i, self) {
        return self.indexOf(x) === i;
    });

    // 前処理
    var lastA = -10;
    for (var i = 0; i < As.length; i++) {
        var element = As[i];
        if(element-1 == lastA) {
            console.log("0");
            return;
        }
        lastA = element;
    }

    for (var i = 1; i < N; i++) {
        memo.push(memo[i-1] * i);
    }

    var divs = [];
    lastA = -1;
    for (var i = 0; i < As.length; i++) {
        var element = As[i];
        divs.push(getPattern(element - lastA - 2));
        lastA = element;
    }

    divs.push(getPattern(N -lastA -1));

    result = 1;
    divs.forEach(element => {
        result *= element;
      result %= 1000000007;
    });

    console.log(result);

}

function getPattern(div) {
    // console.log("div",div);

    var result = 0;
    var maxTwo = Math.floor(div/2);

    for (var two = 0; two <= maxTwo; two++) {
        // console.log(div - two*2, two);

        result += get12Pattern(div - two*2, two);
        result = result % 1000000007;
    }
    // console.log("result", result);

    return result;
}

function get12Pattern(one, two){
    // console.log(one, two);

    return kaijo(one+two) / (kaijo(one) * kaijo(two));
}

function kaijo(value) {
    return memo[value];
}

// 改行・空白で分割
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim().split(/\n|\s/));

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.


module.exports=function(e){var r={};function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:n})},t.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},t.t=function(e,r){if(1&r&&(e=t(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var o in e)t.d(n,o,function(r){return e[r]}.bind(null,o));return n},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},t.p="",t(t.s=0)}([function(e,r,t){t(1)(t(2).readFileSync("/dev/stdin","UTF-8"))},function(e,r){function t(e,r){return function(e){if(Array.isArray(e))return e}(e)||function(e,r){var t=[],n=!0,o=!1,u=void 0;try{for(var i,l=e[Symbol.iterator]();!(n=(i=l.next()).done)&&(t.push(i.value),!r||t.length!==r);n=!0);}catch(e){o=!0,u=e}finally{try{n||null==l.return||l.return()}finally{if(o)throw u}}return t}(e,r)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}e.exports=function(e){for(var r=e.split("\n"),n=t(r[0].split(" ").map(function(e){return Number(e)}),5),o=n[0],u=(n[1],n[2]),i=n[3],l=n[4],f=r[1].split(""),c=1;c<o;c++)if("#"==f[c-1]&&"#"==f[c])return void console.log("No");if(!(i<l)){for(var a=0,s=u;s<o;s++)if("."==f[s]&&s!=l-1){if(1==a)return void console.log("Yes");a=1}else a=0;return l-2>=0&&l-2<o&&"#"==f[l-2]||l>=0&&l<o&&f[l],void console.log("No")}console.log("Yes")}},function(e,r){e.exports=require("fs")}]);

Score : 400 points

Problem Statement

There are N squares arranged in a row, numbered 1, 2, ..., N from left to right.
You are given a string S of length N consisting of . and #. If the i-th character of S is #, Square i contains a rock; if the i-th character of S is ., Square i is empty.

In the beginning, Snuke stands on Square A, and Fnuke stands on Square B.

You can repeat the following operation any number of times:

Choose Snuke or Fnuke, and make him jump one or two squares to the right. The destination must be one of the squares, and it must not contain a rock or the other person.

You want to repeat this operation so that Snuke will stand on Square C and Fnuke will stand on Square D.

Determine whether this is possible.

Constraints

4 \leq N \leq 200\ 000

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

1 \leq A, B, C, D \leq N

Square A, B, C and D do not contain a rock.

A, B, C and D are all different.

A < B

A < C

B < D

Input

Input is given from Standard Input in the following format:

N A B C D
S

Output

Print Yes if the objective is achievable, and No if it is not.

Sample Input 1

7 1 3 6 7
.#..#..

Sample Output 1

Yes

The objective is achievable by, for example, moving the two persons as follows. (A and B represent Snuke and Fnuke, respectively.)

A#B.#..

A#.B#..

.#AB#..

.#A.#B.

.#.A#B.

.#.A#.B

.#..#AB

Sample Input 2

7 1 3 7 6
.#..#..

Sample Output 2

No

Sample Input 3

15 1 3 15 13
...#.#...#.#...

Sample Output 3

Yes


"use strict";

function Main(input){
  let Line = input.split('\n');
  let Line1 = Line[0].split(' ').map(n => parseInt(n));

  // Translate to index value
  var A = Line1[1] - 1;
  var B = Line1[2] - 1;
  let C = Line1[3] - 1;
  let D = Line1[4] - 1;

  let S = Line[1].trim();

  // console.log("Pattern:ABDC");
  if (B < D && D < C) {

    var comma = [];
    comma3check(S, comma);
    let overtake_index = isSpace3Existing(B, C, comma);

    // BがCに到着するまでにAがBを追い越せないならNG
    if (overtake_index == -1) {
      console.log("No");
      return;

    } else {
      A = overtake_index + 2;
      B = overtake_index;
    }

  }

  var rock = [];
  rock2check(S, rock);
  let A_flag = !isRockExisting(A, C, rock);
  let B_flag = !isRockExisting(B, D, rock);

  if (A_flag && B_flag){
    console.log("Yes");
  } else {
    console.log("No");
  }

}

// 空白が連続して３つ以上あれば追い抜ける
// 空白が連続する開始位置のインデックスを返却
// 追い抜けないときは-1を返却
function isSpace3Existing(start, end, space) {
  var overtake_index = -1;
  const result = space.some(elm => {
    overtake_index = elm;
    return(start < elm && elm <= end - 1);
  });
  return overtake_index;
}

// 岩が連続してあればtrue(通れない）
function isRockExisting(start, end, rock) {
  const result = rock.some(elm => {
    return(start - 1 <= elm && elm < end - 2);
  });
  return result;
}

// 自身と次が岩であれば自身のインデックスを格納する
function rock2check(S, rock){
  for (let i = 0; i < S.length - 1; i++) {
    if (S[i] == '#' && S[i + 1] == '#') {
      rock.push(i);
    }
  }
}

// 自身から３つ空白が続いたら自身のインデックスを格納する
function comma3check(S, comma) {
  for (let i = 0; i < S.length - 2; i++) {
    if (S[i] == '.' && S[i + 1] == '.' && S[i + 2] == '.') {
      comma.push(i);
    }
  }
}

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


(function() {
function Main(input) {
  lines = input.split("\n")[0] * 1
  ans = (lines - 2) * 180
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}())

Score : 100 points

Problem Statement

Given an integer N not less than 3, find the sum of the interior angles of a regular polygon with N sides.

Print the answer in degrees, but do not print units.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print an integer representing the sum of the interior angles of a regular polygon with N sides.

Sample Input 1

3

Sample Output 1

180

The sum of the interior angles of a regular triangle is 180 degrees.

Sample Input 2

100

Sample Output 2

17640


'use strict';(function(input){
  input=input.trim().split('').reduce((a,c)=>a+(c==='x'?1:0),0);
  var ans=((input<=7)?'YES':'NO');
  console.log(ans);
})(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 200 points

Problem Statement

Takahashi is competing in a sumo tournament.
The tournament lasts for 15 days, during which he performs in one match per day.
If he wins 8 or more matches, he can also participate in the next tournament.

The matches for the first k days have finished.
You are given the results of Takahashi's matches as a string S consisting of o and x.
If the i-th character in S is o, it means that Takahashi won the match on the i-th day; if that character is x, it means that Takahashi lost the match on the i-th day.

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO if there is no such possibility.

Constraints

1 \leq k \leq 15

S is a string of length k consisting of o and x.

Input

Input is given from Standard Input in the following format:

S

Output

Print YES if there is a possibility that Takahashi can participate in the next tournament, and print NO otherwise.

Sample Input 1

oxoxoxoxoxoxox

Sample Output 1

YES

Takahashi has 7 wins and 7 losses before the last match. If he wins that match, he will have 8 wins.

Sample Input 2

xxxxxxxx

Sample Output 2

NO


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 s = o.a(1);
  var ans = 0;
  for(var i = 0; i < s.length; i++){
    if(s[i] === "x")ans++;
  }
  return ans>7?"NO":"YES";
}


"use strict";
function Main(input) {
  const args = input.split('\n');
  const N = parseInt(args.shift());
  const ns = Array(N).fill(0);
  const cs = args[N - 1].split(' ').map(m => parseInt(m)).sort((a, b) => a - b);
  const ms = [];
  const abs = [];
  for(let i = 0; i < args.length - 2; i++) {
    const ab = args[i].split(' ').map(m => parseInt(m) - 1);
    abs.push(ab);
    ns[ab[0]]++;
    ns[ab[1]]++;
  }
  let ds = [];
  ns.map((m, i) => {
    return {
      idx: i,
      count: m
    }
  })
  .sort((a, b) => a.count - b.count)
  .forEach((v, i) => ds[v.idx] = cs[i]);
  for(let ab of abs) {
    const a = ab.shift();
    const b = ab.shift();
    ms.push(ds[a] < ds[b] ? ds[a] : ds[b]);
  }
  const M = ms.reduce((p ,c) => p += c);
  console.log(M);
  console.log(ds);
}

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

Score : 500 points

Problem Statement

You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N.
The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.

We will write a positive integer on each vertex in T and calculate our score as follows:

On each edge, write the smaller of the integers written on the two endpoints.

Let our score be the sum of the integers written on all the edges.

Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.

Constraints

1 \leq N \leq 10000

1 \leq a_i,b_i \leq N

1 \leq c_i \leq 10^5

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N

Output

Use the following format:

M
d_1 \ldots d_N

where M is the maximum possible score, and d_i is the integer to write on Vertex i.
d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N.
If there are multiple ways to achieve the maximum score, any of them will be accepted.

Sample Input 1

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

Sample Output 1

10
1 2 3 4 5

If we write 1,2,3,4,5 on Vertex 1,2,3,4,5, respectively, the integers written on the four edges will be 1,2,3,4, for the score of 10. This is the maximum possible score.

Sample Input 2

5
1 2
1 3
1 4
1 5
3141 59 26 53 59

Sample Output 2

197
59 26 3141 59 53

c_1,c_2,\ldots,c_N may not be pairwise distinct.


'use strict'
function Main(input) {
  input = input.split(" ");
  let apple = parseInt(input[0], 10);
  let piece = parseInt(input[1], 10);
  let sum = Math.floor((apple*3 + piece)/2);
  console.log('%s',sum);
}

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'
const Main = (arg) => {
  let input = arg.trim().split('\n');
  let N = input[0].split(' ').map(Number)[0];
  // let Arr1 = input[1].split(' ').map(Number);
  let Res = [];

  // 連想配列(Dictionary)に格納
  for (let i = 1; i <= N; i++) {
    Res[i - 1] = {
      souceOrder: i,
      city: input[i].split(' ')[0],
      score: parseInt(input[i].split(' ')[1]),
      printOrder: 1
    }
  }

  // console.log({ N, Res });
  // console.log(Res[0]);

  // city昇順 score降順 の順に並べ替え
  Res.sort((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;
  });
  // console.log({ Res });

  for (let i = 0; i < N; i++) {
    Res[i].printOrder = (i + 1);
  }

  // console.log({ Res });
  let Ans = [];
  for (let i = 0; i < N; i++) {
    Ans.push(Res[i].souceOrder);
  }

  console.log(Ans.join('\n'));
}
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


function Main(input) {

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

	function List(name,score,num){
	    this.name = name;
	    this.score = score;
	    this.num = num;
	}

	List.prototype.show = function(){
	    return this.num;
	}

	for(var i = 0;i < N;i++){
	     pass = input[i+1].split(" ");
	     lists[i] = new List(pass[0],parseInt(pass[1]),i+1);
	}

    lists.sort((a,b) => { return (a.score < b.score)? 1 : -1; });
    lists.sort((a,b) => { return (a.name > b.name)? 1 : -1; });

    for(var j = 0;j < N;j++){
        console.log(lists[j].show());
    }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict';
(function(input){
  input=input.trim().split(/\n+/);
  input=input.map((str,i)=>str.split(/\s+/).concat(i));
  input.shift();
  input.sort(function(a,b){
    if([a[0],b[0]].sort()[0]===a[0]){
      if(a[0]!==b[0])
        return -1;
      else
        return -(a[1]-b[1])
    }else return +1;
  });
  console.log(input.map(a=>a[2]).join('\n').trim());
})(require('fs').readFileSync('/dev/stdin','utf8'));


'use strict'

const main = (INPUT) => {
  let input = INPUT.split('\n')
  const N = input[0]
  input.shift()
  let ary = input.map(v => v.split(' '))
  ary.sort((a, b) => {
    if (a[0] > b[0]) return 1
    if (a[0] < b[0]) return -1
    if (Number(a[1]) > Number(b[1])) return -1
    if (Number(a[1]) < Number(b[1])) return 1
  })

  ary = ary.map(v => v.join(' '))

  for (let i = 0; i < N; i++) {
    for (let j = 0; j < N; j++) {
      if (ary[i] == input[j]) {
        console.log(j + 1)
        break
      }
    }
  }
}

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])

    var s = {}
    for(var i=1; i <= M; i++)
    {
        var tmp = input[i].split(" ")
        var k = Number(tmp[0])
        var val = 0
        for(var j=1; j <= k; j++)
        {
            val += Math.pow(2,Number(tmp[j])-1)
        }
        // console.log((Array(N).join('0') + val.toString(2)).slice(-N))
        lamp_switch = val
        s[i] = lamp_switch
    }
    var tmpp = input[M+1].split(" ")

    var ans =0
    for(var j=0; j <Math.pow(2,N); j++)
    {
        // console.log((Array(N).join('0') + j.toString(2)).slice(-N))
        var switch_states = j
        var flashCnt=0
        for(var i=1; i <= M; i++)
        {
            //電球i
            var andStr = (Array(N).join('0') + (switch_states & s[i]).toString(2)).slice(-N)
            var onCnt = andStr.split("1").length-1
            // console.log(`電球${i}`)
            // console.log("lamp_switch: " + (Array(N).join('0') + s[i].toString(2)).slice(-N))
            // console.log("switch_states: " + (Array(N).join('0') + j.toString(2)).slice(-N))
            // console.log("and: " + andStr)

            if((onCnt%2 == Number(tmpp[i-1])))
            {
                flashCnt++
            }
        }
        if(flashCnt == M){
            ans++
        }
    }
    console.log(ans)
  }
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//   Main("5 2\n3 1 2 5\n2 2 3\n1 0\n");

Score : 300 points

Problem Statement

We have N switches with "on" and "off" state, and M bulbs. The switches are numbered 1 to N, and the bulbs are numbered 1 to M.

Bulb i is connected to k_i switches: Switch s_{i1}, s_{i2}, ..., and s_{ik_i}. It is lighted when the number of switches that are "on" among these switches is congruent to p_i modulo 2.

How many combinations of "on" and "off" states of the switches light all the bulbs?

Constraints

1 \leq N, M \leq 10

1 \leq k_i \leq N

1 \leq s_{ij} \leq N

s_{ia} \neq s_{ib} (a \neq b)

p_i is 0 or 1.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
k_1 s_{11} s_{12} ... s_{1k_1}
:
k_M s_{M1} s_{M2} ... s_{Mk_M}
p_1 p_2 ... p_M

Output

Print the number of combinations of "on" and "off" states of the switches that light all the bulbs.

Sample Input 1

2 2
2 1 2
1 2
0 1

Sample Output 1

1

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

There are four possible combinations of states of (Switch 1, Switch 2): (on, on), (on, off), (off, on) and (off, off). Among them, only (on, on) lights all the bulbs, so we should print 1.

Sample Input 2

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

Sample Output 2

0

Bulb 1 is lighted when there is an even number of switches that are "on" among the following: Switch 1 and 2.

Bulb 2 is lighted when there is an even number of switches that are "on" among the following: Switch 1.

Bulb 3 is lighted when there is an odd number of switches that are "on" among the following: Switch 2.

Switch 1 has to be "off" to light Bulb 2 and Switch 2 has to be "on" to light Bulb 3, but then Bulb 1 will not be lighted. Thus, there are no combinations of states of the switches that light all the bulbs, so we should print 0.

Sample Input 3

5 2
3 1 2 5
2 2 3
1 0

Sample Output 3

8


"use strict";

function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

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),
        N = _splitNum2[0],
        M = _splitNum2[1];

    var lights = lines.slice(1, M + 1).map(function (line, i) {
      var _splitNum3 = splitNum(line),
          _splitNum4 = _toArray(_splitNum3),
          k = _splitNum4[0],
          s = _splitNum4.slice(1);

      return {
        k: k,
        s: s,
        li: i
      };
    });
    var ps = splitNum(lines[M + 1]);
    var count = 0;

    ll: for (var i = 0; i < Math.pow(2, N); i++) {
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = lights[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var _step$value = _step.value,
              s = _step$value.s,
              li = _step$value.li;
          var swc = 0;
          var _iteratorNormalCompletion2 = true;
          var _didIteratorError2 = false;
          var _iteratorError2 = undefined;

          try {
            for (var _iterator2 = s[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
              var si = _step2.value;
              if (i & 1 << si - 1) swc++;
            }
          } catch (err) {
            _didIteratorError2 = true;
            _iteratorError2 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                _iterator2.return();
              }
            } finally {
              if (_didIteratorError2) {
                throw _iteratorError2;
              }
            }
          }

          if (swc % 2 !== ps[li]) continue ll;
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }

      count++;
    }

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


"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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

!function (fs) {
  "use strict";

  var Treap =
  /*#__PURE__*/
  function () {
    function Treap(getSortKey) {
      _classCallCheck(this, Treap);

      this.getSortKey = getSortKey || function (x) {
        return x;
      };

      this.root = null;
    }

    _createClass(Treap, [{
      key: "insert",
      value: function insert(value) {
        var priority = Math.random();
        var node = {
          value: value,
          key: this.getSortKey(value),
          priority: priority,
          left: null,
          right: null
        };
        this.root = this._insertRec(this.root, node);
      }
    }, {
      key: "erase",
      value: function erase(value) {
        var key = this.getSortKey(value);
        this.root = this._eraseRec(this.root, key);
      }
    }, {
      key: "contains",
      value: function contains(value) {
        return null != this._find(value);
      }
    }, {
      key: "min",
      value: function min() {
        var root = this.root;

        for (; null != root;) {
          if (null == root.left) return root.value;
          root = root.left;
        }

        return null;
      }
    }, {
      key: "_insertRec",
      value: function _insertRec(target, node) {
        if (null == target) return node;
        if (node.key === target.key) return target;else if (node.key < target.key) {
          var newChild = this._insertRec(target.left, node);

          target.left = newChild;
          if (newChild.priority < target.priority) return target;else return this._rotateRight(target);
        } else {
          var _newChild = this._insertRec(target.right, node);

          target.right = _newChild;
          if (_newChild.priority < target.priority) return target;else return this._rotateLeft(target);
        }
      }
    }, {
      key: "_rotateRight",
      value: function _rotateRight(parent) {
        var child = parent.left;
        if (null == child) return parent;
        parent.left = child.right;
        child.right = parent;
        return child;
      }
    }, {
      key: "_rotateLeft",
      value: function _rotateLeft(parent) {
        var child = parent.right;
        if (null == child) return parent;
        parent.right = child.left;
        child.left = parent;
        return child;
      }
    }, {
      key: "_eraseRec",
      value: function _eraseRec(node, key) {
        if (null == node) return null;

        if (key < node.key) {
          node.left = this._eraseRec(node.left, key);
          return node;
        } else if (key > node.key) {
          node.right = this._eraseRec(node.right, key);
          return node;
        }

        if (null == node.left && null == node.right) return null;

        if ((node.left ? node.left.priority : -1) > (node.right ? node.right.priority : -1)) {
          var newParent = node.left;
          var npRightChild = newParent.right;
          node.left = npRightChild;
          newParent.right = this._eraseRec(node, key);
          if (newParent.right && newParent.right.priority > newParent.priority) return this._rotateLeft(newParent);else return newParent;
        } else {
          var _newParent = node.right;
          var npLeftChild = _newParent.left;
          node.right = npLeftChild;
          _newParent.left = this._eraseRec(node, key);
          if (_newParent.left && _newParent.left.priority > _newParent.priority) return this._rotateRight(_newParent);else return _newParent;
        }
      }
    }, {
      key: "_find",
      value: function _find(value) {
        var root = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.root;
        if (null == root) return null;
        if (root.value === value) return root;
        if (value < root.value) return this._find(value, root.left);else return this._find(value, root.right);
      }
    }]);

    return Treap;
  }();

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

    function sortByKey(arr, keys) {
      if (!Array.isArray(keys)) keys = [keys];
      return arr.sort(function (a, b) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
          for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
            var k = _step.value;

            if ("string" == typeof k) {
              var d = a[k] - b[k];
              if (0 !== d) return d;
            } else {
              var _d = a[k[0]] - b[k[0]];

              var sig = "desc" === k[1] ? -1 : "asc" === k[1] ? 1 : Number(k[1]);
              if (0 !== _d) return _d * sig;
            }
          }
        } catch (err) {
          _didIteratorError = true;
          _iteratorError = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
              _iterator.return();
            }
          } finally {
            if (_didIteratorError) {
              throw _iteratorError;
            }
          }
        }

        return 0;
      });
    }

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

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

      var kouji = lines.slice(1, N + 1).map(function (line, i) {
        var _splitNum3 = splitNum(line),
            _splitNum4 = _slicedToArray(_splitNum3, 3),
            S = _splitNum4[0],
            T = _splitNum4[1],
            X = _splitNum4[2];

        return {
          i: i,
          S: S,
          T: T,
          X: X,
          startTime: S - X - .5,
          endTime: T - X - .6
        };
      });
      var D = splitNum(lines.slice(N + 1)).slice(0, Q);
      var events = [];
      var _iteratorNormalCompletion2 = true;
      var _didIteratorError2 = false;
      var _iteratorError2 = undefined;

      try {
        for (var _iterator2 = kouji[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
          var _step2$value = _step2.value,
              X = _step2$value.X,
              startTime = _step2$value.startTime,
              endTime = _step2$value.endTime;
          events.push({
            type: "add",
            time: startTime,
            X: X
          }, {
            type: "delete",
            time: endTime,
            X: X
          });
        }
      } catch (err) {
        _didIteratorError2 = true;
        _iteratorError2 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
            _iterator2.return();
          }
        } finally {
          if (_didIteratorError2) {
            throw _iteratorError2;
          }
        }
      }

      var dindex = 0;
      sortByKey(events, ["time"]);
      var set = new Treap();

      for (var _i2 = 0; _i2 < events.length; _i2++) {
        var _events$_i = events[_i2],
            type = _events$_i.type,
            time = _events$_i.time,
            X = _events$_i.X;

        for (; dindex < D.length && time > D[dindex];) {
          var _stop = set.min();

          console.log(null == _stop ? -1 : _stop);
          dindex++;
        }

        if ("add" === type) set.insert(X);else if ("delete" === type) set.erase(X);
      }

      for (; dindex < D.length; dindex++) {
        var stop = set.min();
        console.log(null == stop ? -1 : stop);
      }
    }(fs.readFileSync("/dev/stdin", "utf8"));
  }();
}(require("fs"));

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 I(t,i){this._s=t.split("\n"),this._c=0,this._l=0,this._f=i||Number}I.prototype.a=function(t){var i=this._s[this._l];if(i){var s=i.trim().split(" "),h=s[this._c];return this._c++,s.length===this._c&&(this._c=0,this._l++),t?t(h):this._f(h)}},I.prototype.l=function(t){var i=this._s[this._l];if(i)return this._c=0,this._l++,i.split(" ").map(t||this._f)},module.exports=I;

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

  var n = o.a();
  var q = o.a();

  var s = [], t = [], x = [];
  for ( var i = 0; i < n; i++ ) {
    s.push(o.a());
    t.push(o.a());
    x.push(o.a());
  }

  var d = [];
  for ( var i = 0; i < q; i++ ) {
    d.push(o.a());
  }

  var arr = [];
  arr.push({s: -Infinity, t: -Infinity, x: Infinity});

  var temp = [];
  for (var i = 0; i < n; i++) {
    temp.push(s[i] - x[i]);
    temp.push(t[i] - x[i]);
  }

  temp.sort((a, b) => a - b);
  for (var i = 0; i < temp.length - 1; i++) {
    if (temp[i] !== temp[i+1]) {
      arr.push({s: temp[i], t: temp[i + 1], x: Infinity});
    }
  }
  arr.push({s: Infinity, t: Infinity, x: Infinity});

  var temp = [];
  for ( var i = 0; i < n; i++ ) {
    temp.push({s: s[i] - x[i], t:t[i] - x[i], x:x[i]});
  }
  temp.sort((a, b) => a.x - b.x);

  for (var i = 0; i < temp.length; i++) {
    var low = 0, high = arr.length - 1;
    while (low < high - 1) {
      var mid = Math.floor((low + high) / 2);
      if (temp[i].s < arr[mid].s) {
        high = mid;
      } else {
        low = mid;
      }
    }
    var cur = low;
    // console.log({cur, arr, temp:temp[i]})
    while (arr[cur].t <= temp[i].t) {
      if (arr[cur].x > temp[i].x) arr[cur].x = temp[i].x;
      cur += 1;
    }
  }
  // console.log({arr});

  for (var i = 0; i < q; i++) {
    var low = 0, high = arr.length - 1;
    while (low < high - 1) {
      var mid = Math.floor((low + high) / 2);
      if (d[i] < arr[mid].s) {
        high = mid;
      } else {
        low = mid;
      }
    }

    // console.log({di: d[i], low})
    if (arr[low].t >= d[i]) {
      if (Number.isFinite(arr[low].x)) {
        console.log(arr[low].x);
      } else {
        console.log(-1);
      }
    } else {
      console.log(-1);
    }
  }
  // console.log({n, q, s, t, x, d})
}

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


function Main(input) {
	input = input.split(" ");
  var A = parseInt(input[0], 10);
  var B = parseInt(input[1], 10);
  var result;

  if(13<=A && A<=100) {
    result = B;
    console.log(result);
  } else if (6<=A && A<=12){
    result = B/2;
    console.log(result);
  } else if (0<=A && A<=5) {
    result = 0;
    console.log(result);
  }
}

main(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.


function Main(input) {

    input = input.split(" ");

    var a = parseInt(input[0],10);
    var b = parseInt(input[1],10);
    var res;

    if(a >= 13){
        res = b;
    }
    if(a >= 6 && a <= 12){
        res = b / 2;
    }
    if(a <= 5){
        res = 0;
    }
    console.log(res);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

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

    if(A >= 13) {
        console.log(B);
    } else if(13 > A && A >= 6) {
        console.log(B / 2);
    } else {
        console.log(0);
    }

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


// inputに入力データ全体が入る
function Main(input) {

   input = input.split(" ");
  var r= parseInt(input[0], 10);
  var D= parseInt(input[1], 10);
  var X= parseInt(input[2], 10);

   var c = [];
for (var i = 0; i <10 ; i++){
            var X = r * X - D;
            console.log(X)
           c[i] = X;}

}

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

Score : 200 points

Problem Statement

The development of algae in a pond is as follows.

Let the total weight of the algae at the beginning of the year i be x_i gram. For i≥2000, the following formula holds:

x_{i+1} = rx_i - D

You are given r, D and x_{2000}. Calculate x_{2001}, ..., x_{2010} and print them in order.

Constraints

2 ≤ r ≤ 5

1 ≤ D ≤ 100

D < x_{2000} ≤ 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

r D x_{2000}

Output

Print 10 lines. The i-th line (1 ≤ i ≤ 10) should contain x_{2000+i} as an integer.

Sample Input 1

2 10 20

Sample Output 1

30
50
90
170
330
650
1290
2570
5130
10250

For example, x_{2001} = rx_{2000} - D = 2 \times 20 - 10 = 30 and x_{2002} = rx_{2001} - D = 2 \times 30 - 10 = 50.

Sample Input 2

4 40 60

Sample Output 2

200
760
3000
11960
47800
191160
764600
3058360
12233400
48933560


function Main(input) {
  var N = parseInt(input.split("\n")[0].split(" ")[0]);//IDカード
  var M = parseInt(input.split("\n")[0].split(" ")[1]);//ゲート
  var left = 1;
  var right = N;

  for(var i = 1; i <= M; i++){
    var tmp = input.split("\n")[i].split(" ").map((tmp)=>Number(tmp));
    var tmpMin = tmp[0];
    var tmpMax = tmp[1];
       left = Math.max(tmpMin,left);
       right = Math.min(tmpMax,right);
  }

  console.log(Math.max((right - left + 1),0));
}

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


'use strict'
function main(input) {
  input = input.trim().split('\n')
  input.shift()
  let min = 0
  let max = 1000000
  input.forEach(val => {
    let temp = val.split(' ').map(val => Number(val))
    if (temp[0] > min) min = temp[0]
    if (temp[1] < max) max = temp[1]
  })
  let ans = max - min + 1
  console.log(ans > 0 ? ans : 0)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input) {
    input = input.trim().split("\n");
    tmp = input[0].split(" ");
    var N = parseInt(tmp[0],10);
    var M = parseInt(tmp[1],10);
    var A = [];
    for(var i = 0; i < N; i++){
        A[i] = parseInt(input[1].split(" ")[i],10);
    }

    for(var j = 2; j <= M+1; j++){
        var B = parseInt(input[j].split(" ")[0],10);
        var C = parseInt(input[j].split(" ")[1],10);

        for(var i = 0; i < B; i++){
            A.push(C);
        }
    }

    A.sort(function(a,b){
        return (a < b ? 1 : -1);
    });

    var output = 0;
    for(var i = 0; i < N; i++){
        output += A[i];
    }
    console.log(output);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

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";
function I(t,i){this._s=t.split("\n"),this._c=0,this._l=0,this._f=i||Number}I.prototype.a=function(t){var i=this._s[this._l];if(i){var s=i.trim().split(" "),h=s[this._c];return this._c++,s.length===this._c&&(this._c=0,this._l++),t?t(h):this._f(h)}},I.prototype.l=function(t){var i=this._s[this._l];if(i)return this._c=0,this._l++,i.split(" ").map(t||this._f)},module.exports=I;

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

  var q = o.a();

  var c = 0;
  var sorted = [];

  for (var i = 0; i < q; i ++) {
    var q1 = o.a();
    if (q1 === 1) {
      var a = o.a();
      var b = o.a();
      c += b;

      sorted.push(a);
    } else {
      sorted = sorted.sort((a, b) => a - b);
      var mid = sorted[Math.floor((sorted.length - 1) / 2)];
      var ans = sorted.map(x => Math.abs(x - mid)).reduce((acc, cur) => acc + cur) + c;
      console.log(mid, ans);
    }
  }
}

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

Score : 600 points

Problem Statement

There is a function f(x), which is initially a constant function f(x) = 0.

We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:

An update query 1 a b: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).

An evaluation query 2: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.

We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.

Constraints

All values in input are integers.

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

-10^9 \leq a, b \leq 10^9

The first query is an update query.

Input

Input is given from Standard Input in the following format:

Q
Query_1
:
Query_Q

See Sample Input 1 for an example.

Output

For each evaluation query, print a line containing the response, in the order in which the queries are given.

The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.

Sample Input 1

4
1 4 2
2
1 1 -8
2

Sample Output 1

4 2
1 -3

In the first evaluation query, f(x) = |x - 4| + 2, which attains the minimum value of 2 at x = 4.

In the second evaluation query, f(x) = |x - 1| + |x - 4| - 6, which attains the minimum value of -3 when 1 \leq x \leq 4. Among the multiple values of x that minimize f(x), we ask you to print the minimum, that is, 1.

Sample Input 2

4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2

Sample Output 2

-1000000000 3000000000


"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 : 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'

function Main(input) {
  input = input.split(' ');
  let N = parseInt(input [0]);
  let K = parseInt(input [1]);
  let result = 0;
  for(let i=1;i<N+1;i++){
    result += Math.pow(0.5, Math.max(Math.ceil(Math.log2(K/i)), 0));

  }
  result /= N
  console.log(result)

}
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


function Main(input) {
  "use strict";
	const lines = input.split("\n");
  let S = lines[0].split(" ").map(e => parseInt(e));

  const K = S.pop()
  const N = S.pop()

  const Ps = [];
  for (let i=0; i < 17; i++) {
    Ps.push(Math.pow(2, i+1))
  }

  const Pr = Ps.map( n => 1/n)
  const L = Ps.length;

  let ans = 0;
  for (let i=1; i<N+1; i++) {
    if (i >= K) {
      ans += 1/N;
      continue
    }
    let idx = 0;
    prb:
    for(let j =0; j < L ; j++) {
      if (i*Ps[j] >= K) {
        idx = j;
        break prb;
      }
    }
    ans += Pr[idx] / N

  }
  console.log(ans)

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


"use strict";

// read lines from stdin
const input = require("fs")
  .readFileSync("/dev/stdin", "utf8")
  .split(" ").map((v) => parseInt(v, 10));

const N = input[0];
const K = input[1];

let borders = [];

for (let i = 1; ; i++) {
  const border = K / Math.pow(2, i);
  borders.push(Math.ceil(border));

  if (border < 1) { break; }
}

let ans = (K < N) ? (N - K + 1) / N : 0;

for (let i = 0; i < borders.length; i++) {
  if (borders[i] > N) {
    borders[i] = N + 1;
    continue;
  }

  ans += ((borders[i - 1] || K) - borders[i]) / (N * Math.pow(2, i + 1));
}

console.log(ans);


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

  function Node(){
    var t=this;
    t.connected=[];
    t.group='none';
  }

  const nodes=new Array(N+1);

  for(let i=1;i<=N;i++){
    nodes[i]=new Node();
  }

  input.forEach(function(a){
    var odd=a[2]%2;
    nodes[a[0]].connected.push([a[1],odd]);
    nodes[a[1]].connected.push([a[0],odd]);
  });

  const stack=[1];

  nodes[1].group=0;

  while(stack.length>0){
    let i=stack[stack.length-1];
    let t=nodes[i];
    if(t.connected.length===0){
      stack.pop();
    }else{
      let c=t.connected[t.connected.length-1];
      let n=nodes[c[0]];
      if(n.group==='none'){
        n.group=(t.group+c[1])%2;
        stack.push(c[0]);
      }else{
        t.connected.pop();
      }
    }
  }

  const ans=[];
  for(let i=1;i<=N;i++){
    ans.push(nodes[i].group);
  }
  console.log(ans.join('\n'));
})(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";
const stringToIntDecimal = s => parseInt(s);

const readEdgeDataLine = line => {
  const numberArray = line.split(" ").map(stringToIntDecimal);

  return {
    vertexNumberA: numberArray[0],
    vertexNumberB: numberArray[1],
    distance: numberArray[2]
  };
};

const readData = input => {
  const lines = input.split("\n");

  return {
    n: parseInt(lines[0]),
    edges: lines.slice(1).map(readEdgeDataLine)
  };
};

const getVertices = data => {
  const n = data.n;
  const edges = data.edges;
  const vertices = new Array(n + 1);
  for (let i = 1; i <= n; i += 1)
    vertices[i] = {
      color: 0,
      adjacentVertices: []
    };
  const edgeCount = n - 1;

  for (let i = 0; i < edgeCount; i += 1) {
    const edge = edges[i];
    vertices[edge.vertexNumberA].adjacentVertices.push({
      vertex: vertices[edge.vertexNumberB],
      distance: edge.distance
    });
    vertices[edge.vertexNumberB].adjacentVertices.push({
      vertex: vertices[edge.vertexNumberA],
      distance: edge.distance
    });
  }

  return vertices;
};

function colorVertex(vertex, excludingVertex) {
  const neighbors = vertex.adjacentVertices;
  const len = neighbors.length;

  for (let i = 0; i < len; i += 1) {
    const neighbor = neighbors[i];
    const neighborVertex = neighbor.vertex;
    if (neighborVertex === excludingVertex) continue;
    neighborVertex.color = neighbor.distance % 2;
    colorVertex(neighborVertex, vertex);
  }
}

function Main(input) {
  const data = readData(input);
  const vertices = getVertices(data);
  colorVertex(vertices[1]);
  const n = data.n;
  for (let i = 1; i <= n; i += 1) console.log(vertices[i].color);
}

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


"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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

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

  var UnionFind =
  /*#__PURE__*/
  function () {
    function UnionFind(N) {
      _classCallCheck(this, UnionFind);

      this.nodes = new Array(N).fill(null).map(function () {
        return {
          parent: null,
          size: 1
        };
      });
    }

    _createClass(UnionFind, [{
      key: "find",
      value: function find(elm) {
        var node = this.nodes[elm];
        var route = [];

        for (; null != node.parent;) {
          route.push(node);
          node = node.parent;
        }

        for (var _i = 0; _i < route.length; _i++) {
          var r = route[_i];
          r.parent = node;
        }

        return node;
      }
    }, {
      key: "union",
      value: function union(elm1, elm2) {
        var node1 = this.find(elm1);
        var node2 = this.find(elm2);

        if (node1 !== node2) {
          node2.parent = node1;
          node1.size += node2.size;
          return node1;
        }
      }
    }, {
      key: "getRootNumber",
      value: function getRootNumber() {
        return this.nodes.filter(function (node) {
          return null == node.parent;
        }).length;
      }
    }]);

    return UnionFind;
  }();

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

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

    var infos = lines.slice(1, M + 1).map(function (line) {
      var _splitNum3 = splitNum(line),
          _splitNum4 = _slicedToArray(_splitNum3, 3),
          X = _splitNum4[0],
          Y = _splitNum4[1],
          Z = _splitNum4[2];

      return {
        X: X,
        Y: Y,
        Z: Z
      };
    });
    var uf = new UnionFind(N);
    var _iteratorNormalCompletion = true;
    var _didIteratorError = false;
    var _iteratorError = undefined;

    try {
      for (var _iterator = infos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
        var _step$value = _step.value,
            X = _step$value.X,
            Y = _step$value.Y;
        uf.union(X - 1, Y - 1);
      }
    } catch (err) {
      _didIteratorError = true;
      _iteratorError = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion && _iterator.return != null) {
          _iterator.return();
        }
      } finally {
        if (_didIteratorError) {
          throw _iteratorError;
        }
      }
    }

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

Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

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

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999


"use strict";
function Main(input) {
 const args = input.split(' ').map(m => parseInt(m));
 const n = args.shift();
 const k = args.shift();
console.log(n - k + 1);

}

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

Score : 100 points

Problem Statement

Snuke has N integers: 1,2,\ldots,N.
He will choose K of them and give those to Takahashi.

How many ways are there to choose K consecutive integers?

Constraints

All values in input are integers.

1 \leq K \leq N \leq 50

Input

Input is given from Standard Input in the following format:

N K

Output

Print the answer.

Sample Input 1

3 2

Sample Output 1

2

There are two ways to choose two consecutive integers: (1,2) and (2,3).

Sample Input 2

13 3

Sample Output 2

11


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var K = parseInt(input[0].split(" ")[1]);
  var ans=N-K+1;

  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 lines = [];
var readline = require('readline');

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

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

rl.on('close', function () {
    var R = Number(lines[0].split(" ")[0]);
    var G = Number(lines[0].split(" ")[1]);
    var B = Number(lines[0].split(" ")[2]);
    var N = Number(lines[0].split(" ")[3]);

    var ans = 0;
    for (var r = 0; r <= 3000; r++) {
        for (var g = 0; g <= 3000; g++) {
            var b = N - r * R - g * G;

            if (b < 0 || b % B !== 0) { continue; }
            ans++;
        }
    }

    console.log(ans);

});

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


// inputに入力データ全体が入る
function Main(input) {
    input = input.trim();
    input = input.split(" ");
    var R = input[0];
    var G = input[1];
    var B = input[2];
    var N = input[3];
    var tmpR;
    var tmpG;
    var tmpB;
    var count = 0;

    for(var i = 0; i < N/R+1; i++){
        tmpR = N - R*i;
        for(var j = 0; j < tmpR/G+1; j++){
            tmpG = tmpR - G*j;
            for(var k = 0; k < tmpG/B+1; k++){
                tmpB = tmpG - B*k;
                if(tmpB == 0){
                    count++;
                }
            }
        }
    }

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


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0]);
  var s = new Array(N);
  var a=0;
  var b=0;
  var c=0;
  var ba=0;
  var ans=0;
  for(var i=0;i<N;i++){
    s[i]=input[i+1].split("");
    for(var j=0;j<s[i].length;j++){
      if(j==0&&s[i][j]=="B"){
        b++;
        c++;
      }
      if(j==s[i].length-1&&s[i][j]=="A"){
        a++;
        c++;
      }
      if(s[i][j]=="B"&&j>0){
        if(s[i][j-1]=="A"){
          ans++;
        }
      }
      if(c==2){
        ba++;
      }
    }
    c=0;
  }
  ans=ans+Math.min(a,b);
  if(b==ba&&a==ba&&ba!=0){
    ans--;
  }

  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"));

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";
function main(input) {
  const args = input.split("\n");

  const N = parseInt(args[0]);

  const p = /(AB)+/g;

  let testStr;
  let testStrLen;
  let countAB = 0;

  let BA = 0;
  let firstB = 0;
  let lastA = 0;

  for(let i = 0; i < N; i++) {
      testStr = args[i + 1];
      testStrLen = testStr.length;
      while(p.exec(testStr)) {
          countAB ++;
      }
      if (testStr.charAt(0) == "B") {
        if (testStr.charAt(testStrLen - 1) == "A") {
          BA++;
        } else {
          firstB++;
        }
      } else if (testStr.charAt(testStrLen - 1) == "A") {
        lastA++;
      }
  }

  countAB += BA - 1;
  if(firstB > 0) {
      countAB ++;
      firstB --;
  }

  if(lastA < firstB) {
      countAB += lastA;
  } else {
      countAB += firstB
  }

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


'use strict'
function Main(input){
  input=input.trim().split(/\s+/);
  var N=input.shift()-0;
  var rightA=input.reduce((acc,str)=>acc+(str[str.length-1]==='A'?1:0), 0);
  var leftB=input.reduce((acc,str)=>acc+(str[0]==='B'?1:0), 0);
  var AB=input.reduce((acc,str)=>acc+str.split('AB').length-1, 0);
  console.log(AB+Math.min(rightA,leftB,N-1));
}

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


function ab_count(array){
  var result=0;
  for(var i=0;i<array.length-1;i++){
    if(array[i]=='A' && array[i+1]=='B'){result++;}
  }
  return result;
}

function main(input){
  const lines = input.split('\n');
  const N = lines[0].split(' ').map(x => parseInt(x))[0];
  lines.shift();
  const S = lines;

  var result = 0;
  var head=0;
  var tail=0;
  var sum=0;
  for(var i=0;i<N;i++){
    var current_s = S[i].split('');
    if(current_s[0]=='B'){head++;}
    if(current_s[current_s.length-1]=='A'){tail++;}
    if(current_s[0]=='B' || current_s[current_s.length-1]=='A'){sum++;}
    result += ab_count(current_s);
//    console.log([current_s,ab_count(current_s)]);
  }
  const addition = Math.min(tail,head, sum-1)

  console.log(result+addition);
}

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


"use strict";

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

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

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

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 _main() {
  // ----------
  function splitNum(line) {
    return (Array.isArray(line) ? line : line.split(/\s+/)).map(function (n) {
      return parseInt(n);
    });
  }
  /**
   * Iterates over integers in [start, end).
   */

  /**
   * implementation of arbitrary-precision unsigned integer.
   */
  var Longer =
  /*#__PURE__*/
  function () {
    function Longer(value) {
      _classCallCheck(this, Longer);

      // enough for 64bit
      this.data = [0, 0, 0];
      var idx = 0;

      while (value !== 0) {
        this.data[idx] = value % Longer.border;
        value = Math.floor(value / Longer.border);
        idx++;
      }
    }

    _createClass(Longer, [{
      key: "add",
      value: function add(right) {
        var result = new Longer(0);
        var max = Math.max(this.data.length, right.data.length);
        var carry = 0;
        var idx = 0;

        for (; idx < max; idx++) {
          var sum = (this.data[idx] || 0) + (right.data[idx] || 0) + carry;
          result.data[idx] = sum % Longer.border;
          carry = Math.floor(sum / Longer.border);
        }

        if (carry > 0) {
          result.data[idx] = carry;
        }

        return result;
      }
    }, {
      key: "mul",
      value: function mul(right) {
        var result = new Longer(0);

        for (var lidx = 0; lidx < this.data.length; lidx++) {
          for (var ridx = 0; ridx < right.data.length; ridx++) {
            var me = this.data[lidx] * right.data[ridx];
            var tidx = lidx + ridx;
            var value = me;

            while (value > 0) {
              var sum = (result.data[tidx] || 0) + value;
              result.data[tidx] = sum % Longer.border;
              value = Math.floor(sum / Longer.border);
              tidx++;
            }
          }
        }

        return result;
      }
    }, {
      key: "toString",
      value: function toString() {
        var d = this.data.concat().reverse(); // let fsti = d.findIndex(v => v !== 0);

        var fsti = function (arr, pred) {
          for (var i = 0; i < arr.length; i++) {
            if (pred(arr[i], i)) {
              return i;
            }
          }

          return null;
        } // not full polyfill!
        (d, function (v) {
          return v !== 0;
        });

        if (fsti == null) {
          return "0";
        }

        return d.slice(fsti).map(function (v, i) {
          if (i === 0) {
            return String(v);
          } else {
            // return String(v).padStart(Longer.digits, "0");
            return padStart(String(v), Longer.digits, "0");
          }
        }).join("");

        function padStart(str, num, pad) {
          var n = num - str.length;
          var result = "";

          for (var i = 0; i < n; i++) {
            result += pad;
          }

          return result + str;
        }
      }
    }]);

    return Longer;
  }();
  /** digits per element. */

  Longer.digits = 7;
  Longer.border = Math.pow(10, Longer.digits);
  /**
   * UnionFind of integers in [0, N).
   * */

  /*#__PURE__*/
  (function () {
    function UnionFind(N) {
      _classCallCheck(this, UnionFind);

      this.nodes = new Array(N).fill(null).map(function () {
        return {
          parent: null,

          /**
           * size of set.
           * meaningless if not root
           */
          size: 1
        };
      });
    }
    /**
     * Find the root of element.
     */

    _createClass(UnionFind, [{
      key: "find",
      value: function find(elm) {
        var node = this.nodes[elm];
        var route = [];

        while (node.parent != null) {
          route.push(node);
          node = node.parent;
        }

        for (var _i2 = 0; _i2 < route.length; _i2++) {
          var r = route[_i2];
          r.parent = node;
        }

        return node;
      }
      /**
       * Union two sets.
       * @returns new root of merged set.
       */

    }, {
      key: "union",
      value: function union(elm1, elm2) {
        var node1 = this.find(elm1);
        var node2 = this.find(elm2);

        if (node1 === node2) {
          return;
        }

        node2.parent = node1;
        node1.size += node2.size;
        return node1;
      }
    }]);

    return UnionFind;
  })();
  /**
   * Runs a recursive function expressed as a generator function.
   */

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

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

    console.log(Math.floor(T / A) * B);
  })(require("fs").readFileSync("/dev/stdin", "utf8"));
}

_main();

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


'use strict'

class Main {
  solve() {
    const n = input.nextInt();
    const list = Array.from(input.nextLine()).map(e=>e==='#'?1:0);
    let skip = true;
    const l1 = [];
    for (let i = 0; i < n; ++i) {
      if (list[i] == 1) skip = false;
      if (skip) {continue;}
      l1.push(list[i]);
    }
    let size = l1.length;
    for (let i = l1.length - 1; i >= 0; --i) {
      if (l1[i] == 0) { break; }
      size = i;
    }
    const l2 = l1.slice(0,size);
    if (l2.length == 0) return 0;
    const black = l2;
    const white = l2.map(e=>e==1?0:1);
    const blackSum = _.sumArray(black);
    const whiteSum = _.sumArray(white);
    const blackMax = _.sum(black);
    const whiteMax = _.sum(white);
    const pre = [];
    pre.push(whiteMax);
    for (let i = 0; i < black.length; ++i) {
      pre.push(blackSum[i]+(whiteMax - whiteSum[i]));
    }
    return _.min(pre);
  }
}

class Mod {
  constructor(mod) {
    if (mod == null) { mod = Combinatorics.DefaultMod; }
    this.mod = mod;
  }
  mult(a,b) {
    let ret = 0;
    a %= this.mod;
    b %= this.mod;
    while (b) {
      if (b&1) {
        ret += a;
        if (ret > this.mod) { ret -= this.mod; }
      }
      a <<= 1;
      if (a > this.mod) { a -= this.mod; }
      b >>= 1;
    }
    return ret;
  }
  pow(a,b) {
    let ret = 1;
    while(b) {
      if (b&1) { ret = this.mult(ret,a); }
      a = this.mult(a,a);
      b >>= 1;
    }
    return ret;
  }
  div(a,b) { return this.mult(a, this.pow(b, this.mod-2)) }
  comb(n,k) { return MOD.mult(factTable[n],MOD.mult(invFactTable[k],invFactTable[n-k])); }
}
const MOD = new Mod(998244353);

class Underscore {
  sum(arr) { return arr.reduce((a,b)=>a+b); }
  modSum(arr,mod) { if (mod == null) { mod = MOD.mod; } return arr.reduce((a,b)=>(a+b)%mod); }
  min(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.reduce((a,b) => func(a,b) < 0 ? a : b); }
  max(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.reduce((a,b) => func(a,b) > 0 ? a : b); }
  sort(arr, func) { if (func == null) {func = (a,b) => a - b} return arr.sort(func) }
  uniq(arr) {
    arr.sort();
    for(let i = 0; i < arr.length - 1; ++i) {
      arr[i] = arr[i+1] == arr[i] ? null : arr[i];
    }
    return arr.filter(e => e != null);
  }
  range(start, stop, step) {
    if (stop == null) { stop = start || 0; start = 0; }
    if (!step) { step = stop < start ? -1 : 1; }
    const length = Math.max(Math.ceil((stop - start) / step), 0);
    const range = Array(length);
    for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; }
    return range;
  }
  first (array, n) {
    if (array == null || array.length < 1) return n == null ? void 0 : [];
    if (n == null) return array[0];
    return this.initial(array, array.length - n);
  };
  initial (array, n) { return array.slice.call(array, 0, Math.max(0, array.length - (n == null ? 1 : n))); }
  tail(array, n) { return array.slice.call(array, n == null ? 1 : n); }
  last (array, n) { if (n == null) return array[array.length - 1]; return this.tail(array, Math.max(0, array.length - n)); }
  sumArray (arr) { return this.tail(arr.reduce(((a,b,i) => {a.push(b + a[i]); return a}), [0])); }
  diffArray (arr) { const s = []; for (let i = 1; i < arr.length; ++i) { s.push(arr[i] - arr[i-1]); } return s; }
  // 配列の値以下の最大のindex
  binarySearch (array, key, iteratee) {
    const itr = (obj) => (typeof obj === 'object') ? obj[iteratee] : obj;
    const value = itr(key);
    let low = 0, high = array.length;
    while (low < high) {
      let mid = Math.floor((low + high) / 2);
      if (itr(array[mid]) < value) low = mid + 1; else high = mid;
    }
    return low;
  };
}
const _ = new Underscore();

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

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

  /* 1行 or 複数行文字列 */
  nextLine(n) {
    if (n) {
      const ret = this.data.slice(this.cursor, this.cursor + n);
      this.cursor += n;
      return ret;
    }
    return this.data[this.cursor++];
  }
  /* 1整数 */
  nextInt() { return parseInt(this.nextLine()); }
  /* 一行文字配列 */
  nextStrArr() { return this.nextLine().split(' '); }
  /* 一行整数配列 */
  nextIntArr() { return this.nextStrArr().map((e) => parseInt(e)); }
  /* 一行浮動小数点配列 */
  nextFloatArr() { return this.nextStrArr().map((e) => parseFloat(e)); }
  /* 複数行整数配列 */
  nextIntLine(n) { return this.nextLine(n).map((e) => parseInt(e)) }
  /* 複数行浮動小数点配列 */
  nextFloatLine(n) { return this.nextLine(n).map((e) => parseFloat(e)) }
  /* 複数行文字列二次元配列 */
  nextStrRange(n) { return this.nextLine(n).map((line) => line.split(' ')); }
  /* 複数行整数二次元配列 */
  nextIntRange(n) {
    return this.nextLine(n).map((line) => line.split(' ').map((e) => parseInt(e)));
  }
  /* 複数行浮動小数点数二次元配列 */
  nextFloatRange(n) {
    return this.nextLine(n).map((line) => line.split(' ').map((e) => parseFloat(e)));
  }
}
const input = new Input();

class Out {
  constructor() {
    this.option = {
      'true': 'Yes',
      'false': 'No',
    };
  }
  write(output){
    let ret;
    if (output == null) return;
    if (output === true) { ret = this.option['true']; }
    else if (output === false) { ret = this.option['false']; }
    else { ret = output; }
    console.log(ret);
  }
  bool(option) {
    this.option['false'] = option[0];
    this.option['true'] = option[1];
    return this;
  }
}
const out = new Out();

out.write(new Main().solve());

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


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

  var changeStr = S.charAt(K - 1);
  var str = '';

  for (var i = 0; i < S.length; i++) {
    if (S.charAt(i) !== changeStr) {
      str += '*';
    } else {
      str += changeStr;
    }
  }
  console.log(str);
}

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

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**


function Main(input) {
    "use strict";
    const elements = input.split('\n');
    let blackFlag = false;
    let numBlack = 0;
    let numWhiteAfterBlack = 0;

    for (let i = 0; i < elements[0]; i++) {
        if (blackFlag === false && elements[1][i] === '#') {
            blackFlag = true;
        }
        if (blackFlag === true && elements[1][i] === '.') {
            numWhiteAfterBlack++;
        }
        if (elements[1][i] === '#') {
            numBlack++;
        }
    }

    if (numWhiteAfterBlack === 0) {
        console.log('0');
    } else if (numBlack <= numWhiteAfterBlack) {
        console.log(numBlack);
    } else {
        console.log(numWhiteAfterBlack);
    }
}

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


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

  var count_All_white = S.split("#").length-1;

  var count_dot=0;
  for(var i=0; i < S.length; i++){
    if(S[i] == "#") break;
    count_dot++;
  }

  var count_sharp = S.length-1;
  for(var i=S.length-1; i == 0; i--){
    if(S[i] == ".") break;
    count_sharp--;
  }

  var sharp_num=0;
  var dot_num=0;
  for(var i=count_dot;i<count_sharp+1;i++){
    if(S[i] == "#") sharp_num++;
    if(S[i] == ".") dot_num++;
  }

  console.log(Math.min(count_All_white,sharp_num, dot_num));
}

var input=Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// var input=`3
// #.#`
// Main(input);


function Main(input){
	inputs = input.trim().split(' ');
	nums = inputs.map(inputs=>parseInt(inputs,10));
    a = nums[0]+(nums[0]-1);
    b = nums[1]+(nums[1]-1);
    c = nums[0]+(nums[1]);
	console.log(Math.max(a, b, c));
}

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

Score : 100 points

Problem Statement

There are two buttons, one of size A and one of size B.

When you press a button of size X, you get X coins and the size of that button decreases by 1.

You will press a button twice. Here, you can press the same button twice, or press both buttons once.

At most how many coins can you get?

Constraints

All values in input are integers.

3 \leq A, B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of coins you can get.

Sample Input 1

5 3

Sample Output 1

9

You can get 5 + 4 = 9 coins by pressing the button of size 5 twice, and this is the maximum result.

Sample Input 2

3 4

Sample Output 2

7

Sample Input 3

6 6

Sample Output 3

12


'use strict'
function Main(input){
  input=input.trim().split(/\s+/).map(x=>x-0);
  var A=input.shift();
  var B=input.shift();
  var result=Math.max(2*A-1,2*B-1,A+B);
  console.log(result);
}

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


"use strict";
function Main(input) {
    let lines = input.split("\n");
    let ab = lines.shift().split(/\s/).map((v) => v - 0);
    let A = ab[0], B = ab[1];
    let set = [[A, A-1], [A, B], [B, B-1]];
    let sum = set.map((v) => v[0] + v[1]);
    let ans = Math.max(...sum);
    console.log(ans);
}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
	var mt = input.split(/\n/)[0];
  	var height = input.split(/\n/)[1].split(/\s/);
  	var maxHeight = 0;
  	var num = 0;
  	for (var i = 0; i <= mt; i++) {
    	if (height[i] > maxHeight) {
        	maxHeight = height[i];
          	num++;
        }
    }
  	console.log(num);
}

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

Score : 200 points

Problem Statement

There are N mountains ranging from east to west, and an ocean to the west.

At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns.

The height of the i-th mountain from the west is H_i.

You can certainly see the ocean from the inn at the top of the westmost mountain.

For the inn at the top of the i-th mountain from the west (i = 2, 3, ..., N), you can see the ocean if and only if H_1 \leq H_i, H_2 \leq H_i, ..., and H_{i-1} \leq H_i.

From how many of these N inns can you see the ocean?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq H_i \leq 100

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the number of inns from which you can see the ocean.

Sample Input 1

4
6 5 6 8

Sample Output 1

3

You can see the ocean from the first, third and fourth inns from the west.

Sample Input 2

5
4 5 3 5 4

Sample Output 2

3

Sample Input 3

5
9 5 6 8 4

Sample Output 3

1


function Main(input) {
    var odd  = 0;
    var even = 0;
	for(var i = 0; i < input.length; i = i + 2) {
      if (input[i] === '0') {
          even++;
      } else {
          odd++;
      }
	}
	for(var i = 1; i < input.length; i = i + 2) {
      if (input[i] === '0') {
          odd++;
      } else {
          even++;
      }
	}
    console.log(even > odd ? odd : even);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 300 points

Problem Statement

N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N.

The i-th tile from the left is painted black if the i-th character of S is 0, and painted white if that character is 1.

You want to repaint some of the tiles black or white, so that any two adjacent tiles have different colors.

At least how many tiles need to be repainted to satisfy the condition?

Constraints

1 \leq |S| \leq 10^5

S_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

S

Output

Print the minimum number of tiles that need to be repainted to satisfy the condition.

Sample Input 1

000

Sample Output 1

1

The condition can be satisfied by repainting the middle tile white.

Sample Input 2

10010010

Sample Output 2

3

Sample Input 3

0

Sample Output 3

0