var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
var n=arr.shift()-0;
while(n--){
   var xy=[0,0];
   var max=[0,0,0];
   while(true){
      var str=arr.shift();
      if(str=="0 0")break;
      var ary=str.split(" ").map(Number);
      xy[0]+=ary[0];
      xy[1]+=ary[1];
      var d=Math.sqrt(xy[0]*xy[0]+xy[1]*xy[1]);
      if(max[0]<d)max=[d,xy[0],xy[1]];
      else if(max[0]==d && max[1]<xy[0])max=[d,xy[0],xy[1]];
      }
   max.shift();
   console.log(max.join(" "));
}

Exploring Caves

There are many caves deep in mountains found in the countryside. In legend,
each cave has a treasure hidden within the farthest room from the cave's
entrance. The Shogun has ordered his Samurais to explore these caves with
Karakuri dolls (robots) and to find all treasures. These robots move in the
caves and log relative distances and directions between rooms.

Each room in a cave is mapped to a point on an integer grid (x, y >= 0).
For each cave, the robot always starts from its entrance, runs along the grid
and returns to the entrance (which also serves as the exit). The treasure in
each cave is hidden in the farthest room from the entrance, using Euclid
distance for measurement, i.e. the distance of the room at point (x, y) from the
entrance (0, 0) is defined as the square root of (x*x+y*y). If more than one
room has the same farthest distance from the entrance, the treasure is hidden in
the room having the greatest value of x. While the robot explores a cave, it
records how it has moved. Each time it takes a new direction at a room, it notes
the difference (dx, dy) from the last time it changed its direction. For
example, suppose the robot is currently in the room at point (2, 4). If it moves
to room (6, 4), the robot records (4, 0), i.e. dx=6-2 and dy=4-4. The first data
is defined as the difference from the entrance. The following figure shows rooms
in the first cave of the Sample Input. In the figure, the farthest room is the
square root of 61 distant from the entrance.

Based on the records that the robots bring back, your job is to determine the
rooms where treasures are hidden.

Input

In the first line of the input, an integer N showing the number of
caves in the input is given. Integers dxi and
dyi are i-th data showing the differences between
rooms. Note that since the robot moves along the grid, either
dxi or dyi is zero. An integer pair
dxi = dyi = 0 signals the end of one cave's
data which means the robot finished the exploration for the cave and returned
back to the entrance. The coordinates are limited to (0,0)-(1000,1000).

Output

Print the position (x, y) of the treasure room on a line for each cave.

Sample Input

3
1 0
0 1
-1 0
1 0
0 5
-1 0
0 -1
5 0
0 1
0 -1
1 0
0 -4
-3 0
0 3
2 0
0 -2
-1 0
0 1
0 -1
1 0
0 2
-2 0
0 -3
3 0
0 4
-4 0
0 -5
-2 0
0 0
1 0
-1 0
0 0
2 0
0 1
-1 0
0 1
-1 0
0 -2
0 0

Output for the Sample Input

6 5
1 0
2 1


process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data',function(line){
	before(line);
});

var log = console.log;
function before(line){
	var lines = line.split("\n");
	lines = lines.filter(function(e){
		return (e !== "");
	});
	main(lines);
}

//-----------
function main(lines){
	var ls = lines.map(function(e){return Number(e);});
	while(ls.length > 1){
		var tpl = ls.shift();
		var arr = ls.slice(0,tpl);
		ls = ls.slice(tpl);
		var mid = arr.indexOf(Math.min.apply(this,arr));
		arr.splice(mid,1);
		var Mid = arr.indexOf(Math.max.apply(this,arr));
		arr.splice(Mid,1);
		var sum = arr.reduce(function(p,c,i,a){return p+c;});
		log(Math.round(sum/arr.length));
	}
}

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

Problem A: ICPC Score Totalizer Software

The International Clown and Pierrot Competition (ICPC), is one of the
most distinguished and also the most popular events on earth in the
show business.

One of the unique features of this contest is the great number of
judges that sometimes counts up to one hundred. The number of judges
may differ from one contestant to another, because judges with any
relationship whatsoever with a specific contestant are temporarily
excluded for scoring his/her performance.

Basically, scores given to a contestant's performance by the judges
are averaged to decide his/her score. To avoid letting judges with
eccentric viewpoints too much influence the score, the highest and the
lowest scores are set aside in this calculation. If the same highest
score is marked by two or more judges, only one of them is ignored.
The same is with the lowest score. The average, which may contain
fractions, are truncated down to obtain final score as an integer.

You are asked to write a program that computes the scores of
performances, given the scores of all the judges, to speed up the event
to be suited for a TV program.

Input

The input consists of a number of datasets, each corresponding to a
contestant's performance. There are no more than 20 datasets in the input.

A dataset begins with a line with an integer n, the number of
judges participated in scoring the performance (3 ≤ n ≤
100). Each of the n lines following it has an integral
score s (0 ≤ s ≤ 1000) marked by a judge. No
other characters except for digits to express these numbers are in the
input. Judges' names are kept secret.

The end of the input is indicated by a line with a single zero in it.

Output

For each dataset, a line containing a single decimal integer
indicating the score for the corresponding performance should be
output. No other characters should be on the output line.

Sample Input

3
1000
342
0
5
2
2
9
11
932
5
300
1000
0
200
400
8
353
242
402
274
283
132
402
523
0

Output for the Sample Input

342
7
300
326

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.


/*
	?§£????????????:Graph I - Breadth First Search
	(http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_C)

	Status:Accepted

	??????:
		??¨??£???????°??????§???????????????????????????????????¢?´¢??????????????§???????????£????????????????????¢?´¢????????????????????????????????±???????????°???????????°????????¨?°????????????????

*/
var log = console.log;
if (typeof process != "undefined") {
    var input = "";
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', function(chunk) {
        input += chunk;
    });
    process.stdin.on('end', function() {
        var lines = input.split("\n");
        main(lines);
    });
}

function main(lines) {
    lines = lines.map(function(line) {
        return line.split(" ").map(function(e) {
            return Number(e);
        });
    });
    while (lines[0][0] != 0 && lines[0][1] != 0) {
        var fl = lines.shift();
        var W = fl[0];
        var H = fl[1];
        var set = lines.slice(0, H);
        lines = lines.slice(H);
        processSet(W, H, set);
    }
}

function processSet(W, H, set) {
    //!!log(set);
    var visited = [];
    for (var h = 0; h < H; h++) {
        visited[h] = [];
        for (var w = 0; w < W; w++) {
            visited[h][w] = false;
        }
    }
    var stack = [];
    var islands = 0;
    for (var h = 0; h < H; h++) {
        for (var w = 0; w < W; w++) {
            //!!log("look at [" + h + "," + w + "]");
            if (
                set[h][w] == 1 &&
                !visited[h][w]
            ) {
                //???????¨??????????????????¶?????°??§??????
                //dfs???????????????
                //!!log("[" + h + "," + w + "] is new island!");
                //!!log("start dfs");
                stack.push([h, w]);
                visited[h][w] = true;
                while (stack.length > 0) {
                    //!!log("now stack is ->");
                    //!!log(stack);
                    //??????????????£??????????????§
                    //???????????¨???????????????
                    var now = stack.pop();
                    stack.push(now);
                    var count = 0;
                    var next = [];
                    for (var dw = -1; dw <= 1; dw++) {
                        for (var dh = -1; dh <= 1; dh++) {
                            //count???????????§?????????????£???°???
                            if (count !== 0) {
                                break;
                            }
                            var th = now[0] + dh;
                            var tw = now[1] + dw;
                            if (
                                0 <= th && th < H &&
                                0 <= tw && tw < W
                            ) {
                                //???????????´??????????????????
                                //??°??????
                                if (!visited[th][tw] &&
                                    set[th][tw] == 1
                                ) {
                                    //????????????????????????
                                    count++;
                                    //??????????????????????????????????????????????????????
                                    if (count == 1) {
                                        next = [th, tw];
                                    }
                                }
                            }
                        }
                    }
                    //????????¢?´¢?????????????????£??\??????????????????
                    if (count > 0) {
                        stack.push(next);
                        visited[th][tw] = true;
                    } else {
                        //??£??\???????????????????????¢?´¢???????????????
                        stack.pop();
                    }
                }
                islands++;
            } else {
                //????????????????????£?????´??????
                //?£???°???
                visited[h][w] = true;
            }
        }
    }
    log(islands);
}

Problem B: How Many Islands?

You are given a marine area map that is a mesh of squares, each
representing either a land or sea area.
Figure B-1 is an example of a map.

Figure B-1: A marine area map

You can walk from a square land area to another if they are horizontally,
vertically, or diagonally adjacent to each other on the map.
Two areas are on the same island if and only if you can
walk from one to the other possibly through other land areas.
The marine area on the map is surrounded by the sea and therefore you
cannot go outside of the area on foot.

You are requested to write a program that reads the map and counts the
number of islands on it.
For instance, the map in Figure B-1 includes three islands.

Input

The input consists of a series of datasets, each being in the following format.

w h

c1,1 c1,2 ... c1,w

c2,1 c2,2 ... c2,w

...

ch,1 ch,2 ... ch,w

w and h are positive integers no more than 50 that
represent the width and the height of the given map, respectively.
In other words, the map consists of w×h squares of the same size.
w and h are separated by a single space.

ci, j is either 0 or 1 and delimited by a single space.
If ci, j = 0, the square that is the i-th from
the left and j-th from the top on the map represents a sea
area.
Otherwise, that is, if ci, j = 1, it represents a land area.

The end of the input is indicated by a line containing two zeros
separated by a single space.

Output

For each dataset, output the number of the islands in a line.
No extra characters should occur in the output.

Sample Input

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

Output for the Sample Input

0
1
1
3
1
9


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
var N=Arr.shift()-0;
for(var i=0;i<N;i++){
   var ymd=Arr[i].split(" ").map(Number);
   var y=ymd[0];
   var m=ymd[1];
   var d=ymd[2];
   var day=0;
   for(var j=1;j<y;j++){
      day+=(j%3==0)?200:195;
   }
   if(y%3==0){
      day+=20*(m-1);
   }else{
      for(var j=1;j<m;j++)day+=(j%2==0)?19:20;
   }
   day+=d;
   console.log(196471-day);
}

Millennium

A wise king declared a new calendar. "Tomorrow shall be the first day of the calendar, that is, the day 1 of the month 1 of the year 1. Each year consists of 10 months, from month 1 through month 10, and starts from a big month. A common year shall start with a big month, followed by small months and big months one after another. Therefore the first month is a big month, the second month is a small month, the third a big month, ..., and the 10th and last month a small one. A big month consists of 20 days and a small month consists of 19 days. However years which are multiples of three, that are year 3, year 6, year 9, and so on, shall consist of 10 big months and no small month."

Many years have passed since the calendar started to be used. For celebration of the millennium day (the year 1000, month 1, day 1), a royal lottery is going to be organized to send gifts to those who have lived as many days as the number chosen by the lottery. Write a program that helps people calculate the number of days since their birthdate to the millennium day.

Input

The input is formatted as follows.

n

Y1 M1 D1

Y2 M2 D2

...

Yn Mn Dn

Here, the first line gives the number of datasets as a positive integer n, which is less than or equal to 100. It is followed by n datasets. Each dataset is formatted in a line and gives three positive integers, Yi (< 1000), Mi (≤ 10), and Di (≤ 20), that correspond to the year, month and day, respectively, of a person's birthdate in the king's calendar. These three numbers are separated by a space.

Output

For the birthdate specified in each dataset, print in a line the number of days from the birthdate, inclusive, to the millennium day, exclusive. Output lines should not contain any character other than this number.

Sample Input

8
1 1 1
344 3 1
696 5 1
182 9 5
998 8 7
344 2 19
696 4 19
999 10 20

Output for the Sample Input

196470
128976
59710
160715
252
128977
59712
1


#!/usr/bin/node
// Generated by CoffeeScript 1.3.3 (minified manually)
(function() {
  var a=[],stdin;
  stdin=process.openStdin();
  stdin.setEncoding('utf8');

  stdin.on('data', function(input) {
    var x = input.split("\n");
    if(x.length > 2 || x[1] !== '')a = x;
    else a.push(x[0]);
  });

  stdin.on('end', function(z) {
    var b, i, j, m, n, r, y;
    n = parseInt(a.shift());
    for(i=0;i<n;i++){
      b = a[i].split(" ");
      for(j=0;j<b.length;j++)b[j]=parseInt(b[j]);
      y = b[0] - 1;
      m = b[1] - 1;
      r = 0;
      if (y % 3 !== 2) {
        r = Math.floor(m / 2);
      }
      console.log(196471 - y * 195 - Math.floor(y / 3) * 5 - m * 20 + r - b[2]);
    }
  });
}).call(this);


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
while(true){
   var n=Arr.shift()-0;
   if(n==0)break;
   var first=Arr.shift().split(":");
   first=first[1].slice(0,-1).split(",");
   var obj={};
   for(var i=0;i<n-1;i++){
      var arr=Arr.shift().split(":");
      obj[arr[0]]=arr[1].slice(0,-1).split(",");
   }
   var L=0;
   while(true){
      if(L==first.length)break;
      L=first.length;
      first.forEach(function(v,i){
         if(obj.hasOwnProperty(v)){
            first[i]="";
            first=first.concat(obj[v]);
         }
      });
   }
   first=first.filter(function(v){return v!=""});
   var OBJ={};
   first.forEach(function(v){OBJ[v]=true;});
   console.log(Object.keys(OBJ).length);
}

Problem A: Membership Management

Peter is a senior manager of Agile Change Management (ACM) Inc., where each employee is a member of one or more task groups. Since ACM is agile, task groups are often reorganized and their members frequently change, so membership management is his constant headache.

Peter updates the membership information whenever any changes occur: for instance, the following line written by him means that Carol and Alice are the members of the Design Group.

design:carol,alice.

The name preceding the colon is the group name and the names following it specify its members.

A smaller task group may be included in a larger one. So, a group name can appear as a member of another group, for instance, as follows.

development:alice,bob,design,eve.

Simply unfolding the design above gives the following membership specification, which is equivalent to the original.

development:alice,bob,carol,alice,eve.

In this case, however, alice occurs twice. After removing one of the duplicates, we have the following more concise specification.

development:alice,bob,carol,eve.

Your mission in this problem is to write a program that, given group specifications, identifies group members.

Note that Peter's specifications can include deeply nested groups. In the following, for instance, the group one contains a single member dave.

one:another.
another:yetanother.
yetanother:dave.

Input

The input is a sequence of datasets, each being in the following format.

n

group1:member1,1,...,member1,m1.

.

.

.

groupi:memberi,1,...,memberi,mi.

.

.

.

groupn:membern,1,...,membern,mn.

The first line contains n, which represents the number of groups and is a positive integer no more than 100. Each of the following n lines contains the membership information of a group: groupi (1 ≤ i ≤ n) is the name of the i-th task group and is followed by a colon (:) and then the list of its mi member s that are delimited by a comma (,) and terminated by a period (.).

Those group names are mutually different. Each mi (1 ≤ i ≤ n) is between 1 and 10, inclusive. A member is another group name if it is one of group1, group2,..., or groupn. Otherwise it is an employee name.

There are no circular (or recursive) definitions of group(s). You may assume that mi member names of a group are mutually different.

Each group or employee name is a non-empty character string of length between 1 and 15, inclusive, and consists of lowercase letters.

The end of the input is indicated by a line containing a zero.

Output

For each dataset, output the number of employees included in the first group of the dataset, that is group1, in a line. No extra characters should occur in the output.

Sample Input

2
development:alice,bob,design,eve.
design:carol,alice.
3
one:another.
another:yetanother.
yetanother:dave.
3
friends:alice,bob,bestfriends,carol,fran,badcompany.
bestfriends:eve,alice.
badcompany:dave,carol.
5
a:b,c,d,e.
b:c,d,e,f.
c:d,e,f,g.
d:e,f,g,h.
e:f,g,h,i.
4
aa:bb.
cc:dd,ee.
ff:gg.
bb:cc.
0

Output for the Sample Input

4
1
6
4
2


const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const lines = input.trim().split('\n');

const getMax = (limit, numbers) => {
	return
}

const getHighestPriceSum = (budget, priceList) => {
	const sums= [];
	for (i=0; i<priceList.length; i++) {
		const leftAddend = priceList[i]
		for (j=0; j<priceList.length; j++) {
			if (i !== j) {
				const rightAddend = priceList[j]
				sums.push(leftAddend + rightAddend);
			}
		}
	}

	return sums.reduce((acc, next) => {
		if (next > acc) {
			if (next <= budget) {
				return next
			}
			return acc
		}
		return acc
	}, 0);
};

let ctr = 0;

const dataSets = [];

const objHolder = {};

while (line = lines.shift()) {
	if (ctr % 2 === 0) {
		const budget = line.split(' ').map(Number)[1];
		objHolder.budget = budget;
	} else {
		const priceList = line.split(' ').map(Number);
		objHolder.priceList = priceList;

		const { budget } = objHolder;
		const highest = getHighestPriceSum(budget, priceList)
		if (highest === 0) {
			console.log('NONE')
		} else {
			console.log(highest)
		}
	}

	ctr++
}

Taro's Shopping

Mammy decided to give Taro his first shopping experience.
Mammy tells him to choose any two items he wants from those
listed in the shopping catalogue,
but Taro cannot decide which two, as all the items look attractive.
Thus he plans to buy the pair of two items with
the highest price sum, not exceeding the amount Mammy allows.
As getting two of the same item is boring, he wants two different items.

You are asked to help Taro select the two items.
The price list for all of the items is given.
Among pairs of two items in the list,
find the pair with the highest price sum
not exceeding the allowed amount,
and report the sum.
Taro is buying two items, not one, nor three, nor more.
Note that, two or more items in the list may be priced equally.

Input

The input consists of multiple datasets, each in the following format.

n m
a1 a2 ... an

A dataset consists of two lines.
In the first line, the number of items n and the maximum
payment allowed m are given.
n is an integer satisfying 2 ≤ n ≤ 1000.
m is an integer satisfying 2 ≤ m ≤ 2,000,000.
In the second line, prices of n items are given.
ai (1 ≤ i ≤ n) is the price
of the i-th item.
This value is an integer greater than or equal to 1 and
less than or equal to 1,000,000.

The end of the input is indicated by a line containing two zeros.
The sum of n's of all the datasets does not exceed 50,000.

Output

For each dataset, find the pair with the highest price sum
not exceeding the allowed amount m
and output the sum in a line.
If the price sum of every pair of items exceeds m,
output NONE instead.

Sample Input

3 45
10 20 30
6 10
1 2 5 8 9 11
7 100
11 34 83 47 59 29 70
4 100
80 70 60 50
4 20
10 5 10 16
0 0

Output for the Sample Input

40
10
99
NONE
20


process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", function (chunk) {
    var input = chunk.trim().split("\n");
    var n = input.shift();
    var button = ["", ".,!? ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
    button = button.map(function (key) {
        return key.split("");
    });
    for (var i = 0; i < n; i++) {
        var data = input[i].split("").map(Number);
        var message = "";
        var character = "";
        var count = 0;
        data.forEach(function (key) {
            if (key > 0) {
                character = button[key][count % button[key].length];
                count++;
            } else {
                message += character;
                character = "";
                count = 0;
            }
        });
        console.log(message);
    }
});

Problem A: Keitai Message

Alice さんは Miku さんに携帯電話でメールを送ろうとしている。

携帯電話には入力に使えるボタンは数字のボタンしかない。 そこで、文字の入力をするために数字ボタンを何度か押して文字の入力を行う。携帯電話の数字ボタンには、次の文字が割り当てられており、ボタン 0 は確定ボタンが割り当てられている。この携帯電話では 1 文字の入力が終わったら必ず確定ボタンを押すことになっている。

1: . , ! ? (スペース)

2: a b c

3: d e f

4: g h i

5: j k l

6: m n o

7: p q r s

8: t u v

9: w x y z

0: 確定ボタン

例えば、ボタン 2、ボタン 2、ボタン 0 と押すと、文字が 'a' → 'b' と変化し、ここで確定ボタンが押されるので、文字 b が出力される。
同じ数字を続けて入力すると変化する文字はループする。すなわち、ボタン 2 を 5 回押して、次にボタン 0 を押すと、文字が 'a' → 'b' → 'c' → 'a' → 'b' と変化し、ここで確定ボタンを押されるから 'b' が出力される。

何もボタンが押されていないときに確定ボタンを押すことはできるが、その場合には何も文字は出力されない。

あなたの仕事は、Alice さんが押したボタンの列から、Alice さんが作ったメッセージを再現することである。

Input

最初の行にテストケースの数が与えられる。 続いて各テストケースについて、最大で長さ 1024 の数字列が1行で与えられる。

Output

Alice さんが作ったメッセージの文字列をそれぞれのテストケースについて 1 行ごとに出力せよ。
ただし、出力は 1 文字以上 76 文字未満であると仮定してよい。

Sample Input

5
20
220
222220
44033055505550666011011111090666077705550301110
000555555550000330000444000080000200004440000

Output for the Sample Input

a
b
b
hello, world!
keitai


function prime(max){
   var arr=[];
   for(var i=0;i<=max;i++)arr[i]=i;
   arr[0]=false;
   arr[1]=false;
   var sqrt=Math.floor(Math.sqrt(max));
   for(var i=2;i<=sqrt;i++){
      if(arr[i]==false)continue;
         for(var j=i+i;j<=max;j+=i){
            arr[j]=false;
         }
   }
   var result=[];
   for(var i=0;i<=max;i++){
      if(arr[i]!==false)result.push(arr[i]);
   }
   return result;
}
var p=prime(30000);
var P={};
p.forEach(function(v){P[v]=true;});
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n").map(Number);
arr.some(function(v){
   if(v==0)return true;
   var ans={};
   for(var i=0;i<p.length;i++){
      var a=p[i];
      if(a>=v)break;
      for(var j=0;j<p.length;j++){
         var b=p[j];
         if(b>=v || a+b>=v)break;
         var c=v-(a+b);
         if(P.hasOwnProperty(c)==false)continue;
         if(a<b+c && b<a+c && c<a+b){
            var abc=[a,b,c];
            abc.sort(function(a,b){return a-b;});
            ans[abc.join(",")]=true;
         }
      }
   }
   console.log(Object.keys(ans).length);
});

Problem A: Space Coconut Crab II

A space hunter, Ken Marineblue traveled the universe, looking for the space coconut crab. The
space coconut crab was a crustacean known to be the largest in the universe. It was said that
the space coconut crab had a body of more than 400 meters long and a leg span of no shorter
than 1000 meters long. Although there were numerous reports by people who saw the space
coconut crab, nobody have yet succeeded in capturing it.

After years of his intensive research, Ken discovered an interesting habit of the space coconut
crab. Surprisingly, the space coconut crab went back and forth between the space and the
hyperspace by phase drive, which was the latest warp technology. As we, human beings, was
not able to move to the hyperspace, he had to work out an elaborate plan to capture them.
Fortunately, he found that the coconut crab took a long time to move between the hyperspace
and the space because it had to keep still in order to charge a sufficient amount of energy for
phase drive. He thought that he could capture them immediately after the warp-out, as they
moved so slowly in the space.

He decided to predict from the amount of the charged energy the coordinates in the space
where the space coconut crab would appear, as he could only observe the amount of the charged
energy by measuring the time spent for charging in the hyperspace. His recent spaceship,
Weapon Breaker, was installed with an artificial intelligence system, CANEL. She analyzed the
accumulated data and found another surprising fact; the space coconut crab always warped out
near to the center of a triangle that satisfied the following conditions:

each vertex of the triangle was one of the planets in the universe;

the length of every side of the triangle was a prime number; and

the total length of the three sides of the triangle was equal to T, the time duration the
space coconut crab had spent in charging energy in the hyperspace before moving to the
space.

CANEL also devised the method to determine the three planets comprising the triangle from
the amount of energy that the space coconut crab charged and the lengths of the triangle sides.
However, the number of the candidate triangles might be more than one.

Ken decided to begin with calculating how many different triangles were possible, analyzing
the data he had obtained in the past research. Your job is to calculate the number of different
triangles which satisfies the conditions mentioned above, for each given T.

Input

The input consists of multiple datasets. Each dataset comes with a line that contains a single
positive integer T (1 ≤ T ≤ 30000).

The end of input is indicated by a line that contains a zero. This should not be processed.

Output

For each dataset, print the number of different possible triangles in a line. Two triangles are
different if and only if they are not congruent.

Sample Input

10
12
15
777
4999
5000
0

Output for the Sample Input

0
1
2
110
2780
0


Problem D:バトルタウン

あなたは友人たちとゲームを開発することにした．
ゲームのタイトルは「バトルタウン」．
戦車による市街戦をテーマにしたゲームだ．
ゲーム開発の第一歩として，次のようなプロトタイプを開発することにした．

このプロトタイプでは，登場する戦車はプレイヤーの戦車のみであり，
敵の戦車は登場しない．
プレイヤーの戦車はプレイヤーの入力に従ってマップ上で様々な動作をする．
以下に，戦車の動作に関する仕様を述べる．

マップの構成要素は表1の通りである．
戦車が移動できるのはマップ内の平地の上だけである．

表1: マップの構成要素

文字

要素

.

平地

*

レンガの壁

#

鉄の壁

-

水

^

戦車（上向き）

v

戦車（下向き）

<

戦車（左向き）

>

戦車（右向き）

プレイヤーの入力は文字の列で与えられる．
各文字に対応する動作は表2の通りである．

表2: プレイヤーの入力に対する動作

文字

動作

U

Up: 戦車を上向きに方向転換し，さらに一つ上のマスが平地ならばそのマスに移動する

D

Down: 戦車を下向きに方向転換し，さらに一つ下のマスが平地ならばそのマスに移動する

L

Left: 戦車を左向きに方向転換し，さらに一つ左のマスが平地ならばそのマスに移動する

R

Right: 戦車を右向きに方向転換し，さらに一つ右のマスが平地ならばそのマスに移動する

S

Shoot: 戦車が現在向いている方向に砲弾を発射する

砲弾はレンガの壁あるいは鉄の壁にぶつかるか，マップの外に出るまで直進する．
レンガの壁にぶつかった場合は，砲弾は消滅し，レンガの壁は平地に変化する．
鉄の壁にぶつかった場合は，砲弾は消滅するが，鉄の壁は変化しない．
マップの外に出たときは砲弾はそのまま消滅する．

あなたの仕事は，初期マップとプレイヤーの入力操作列が与えられたときに，
最終的なマップの状態を出力するプログラムを作成することである．

Input

入力の1行目にはデータセット数を表す数 T
(0 < T ≤ 100) が与えられる．
この行に引き続き T 個のデータセットが与えられる．

各データセットの1行目にはマップの高さと幅を表す整数
H と W が
1つの空白文字で区切られて与えられる．
これらの整数は 2 ≤ H ≤ 20,
2 ≤ W ≤ 20 を満たす．
続く H 行はマップの初期状態を表す．
各行は長さ W の文字列である．
マップに含まれる文字はすべて表1で定義されたものであり，
全体でちょうど1つの戦車を含む．
マップに続く行には入力操作列の長さ N
(0 < N ≤ 100) が与えられ，
次の行には入力操作列を表す長さ N の文字列が与えられる．
入力操作列は表2で定義された文字のみからなる文字列である．

Output

各データセットに対し，すべての入力操作を終えた後のマップを，
入力マップと同じ形式で出力せよ．
データセットの間には1行の空行を出力せよ．
最後のデータセットの後に余計な空行を出力しないよう注意すること．

Sample Input

4
4 6
*.*..*
*.....
..-...
^.*#..
10
SRSSRRUSSR
2 2
<.
..
12
DDSRRSUUSLLS
3 5
>-#**
.-*#*
.-**#
15
SSSDRSSSDRSSSUU
5 5
v****
*****
*****
*****
*****
44
SSSSDDRSDRSRDSULUURSSSSRRRRDSSSSDDLSDLSDLSSD

Output for the Sample Input

*....*
......
..-...
..>#..

<.
..

^-#**
.-.#*
.-..#

.....
.***.
..*..
..*..
....v


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
var NTE=Arr.shift().split(" ").map(Number);
var N=NTE[0];
var T=NTE[1];
var E=NTE[2];
var x=Arr.shift().split(" ").map(Number);
var ans=-1;
for(var i=0;i<N;i++){
   if(ans!=-1)break;
   var time;
   var j=1;
   while(true){
      time=x[i]*j;
      if(T+E<time)break;
      if(T-E<=time && time<=T+E){ans=i+1;break;}
      j++;
   }
}
console.log(ans);

A - アルデンテ

問題文

わたしは近所のスーパーで初めてスパゲッティというものを購入した．パッケージの情報によると，このスパゲッティは T 秒茹でると最も理想的な状態に茹で上がるらしい．

ところでわたしは電気が嫌いな人間であり，家にはテレビやパソコンはおろか，時計さえ無い．
そのためスパゲッティを茹でようにも，時間を測ることができない．
電池式の時計は嫌なので，わたしは代わりに砂時計を買おうと考え，スーパーの砂時計売り場へと向かった．
売り場には N 個の砂時計があった．i 番目の砂時計はちょうど xi 秒だけ測ることができるようであった．
いろいろあって悩ましいが，スパゲッティのために砂時計を何個も買うのは馬鹿らしいのでこの中からちょうど 1 個だけ買おうと思う．

しかし皆さんご存知の通り，砂時計というのは一度測り始めると，それから測り終えるまでは途中の時刻というのはまったく分からない．
そのため，もし私が i 番目の砂時計を買って使ったとすると，時計を連続して使うことで xi 秒，2xi 秒，3xi 秒，... という時間を測ることができるが，逆にそれ以外の時間は測ることができない．

理想的な茹で上がりに必要な時間は T 秒らしいが，ここでは妥協して E (< T) 秒以内の誤差を許そう．
すなわち，どれか 1 つの砂時計を用いて，T−E 秒，T−E+1 秒，T−E+2 秒，... ，T+E−2 秒，T+E−1 秒，T+E 秒のうちのどれかの時間を計測したい．
私は何番目の砂時計を購入して使えばよいだろうか?

入力形式

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

N T E
x1 ... xN

N は砂時計の個数である．T はスパゲッティを理想的に茹で上げるのに必要な時間(秒)，E は茹で上げに許容する誤差の時間(秒)である．
xi は i 番目の砂時計が 1 回で測ることできるの時間(秒)である．

出力形式

何番目の砂時計を使えばよいか出力せよ．そのような砂時計が複数個ある場合，それらの中からどれか 1 つを出力せよ．
どの砂時計を使っても時間が測れない場合は -1 を出力せよ．

制約

1 ≤ N ≤ 100

1 ≤ T ≤ 1,440

0 ≤ E < T

1 ≤ xi ≤ 10^4

入力値はすべて整数である．

入出力例

入力例 1

2 10 2
3 4

出力例 1

2

8秒，9秒，10秒，11秒，12秒 のうちのいずれかの時間を計測できればよい．
1 番目の砂時計で測ることのできる時間は 3秒，6秒，9秒，12秒，... であり，
2 番目の砂時計で測ることのできる時間は 4秒，8秒，12秒，16秒，... であるので，どちらの砂時計を用いても目的の時間を計測できる．
出力例 1 では 2 を答えとしているが，1 を答えにしても正解である．

入力例 2

3 10 5
16 17 18

出力例 2

-1

どの砂時計を使っても目的の時間は計測できない．

Writer: 花田裕一朗
Tester: 小浜翔太郎


n=+require("fs").readFileSync("/dev/stdin","utf-8")

function kaip(n) {
  n = n+""
  if (n[0] != n[n.length-1]) return false;
  for (var i=1; i<n.length/2; ++i)
    if (n[i] != n[n.length-i-1]) return false;
  return true;
}

(function(){
  if (kaip(n)) {
    console.log(n)
    return;
  }
  for (j=1;;++j) {
    if (kaip(n-j)) {
      console.log(n-j);
      return;
    }
    if (kaip(n+j)) {
      console.log(n+j);
      return;
    }
  }
})(n)

回文数

Problem Statement

整数nに最も近い回文数を求めよ．

なお，非負整数xが回文数であるとは，xを十進法で表現した文字列とそれを反転させた文字列が等しいことをいう．

例えば0,7,33,10301などは回文数であり，32,90,1010などは回文数でない．

Input

入力は以下の形式に従う．与えられる数は全て整数である．

n

Constraints

1≦n≦10^4

Output

nに最も近い回文数を出力せよ．

そのような数が複数ある場合は最も小さいものを出力せよ．

Sample Input 1

13

Output for the Sample Input 1

11

13に最も近い回文数は11である．

Sample Input 2

7447

Output for the Sample Input 2

7447

7447は回文数なのでそのまま出力すればよい．

Sample Input 3

106

Output for the Sample Input 3

101

106に最も近い回文数は111と101のふたつあるが，そのうち小さい方の101を出力する．


/**
 * Created by hiroqn on 13/10/08.
 */
var fs = require('fs'),
    length = fs.fstatSync(process.stdin.fd).size,
    buffer = new Buffer(length),
    bytesRead = fs.readSync(process.stdin.fd, buffer, 0, length, 0),
    input = buffer.toString('utf8', 0, bytesRead).split('\n');
main();

function main() {
  var
      isMinus = input[0][0] === '-',
      str = isMinus ? input[0].slice(1) : input[0],
      ss1, ss2,//separate string
      si1, si2,
      i,
      x, y,
      ans = 0;
  if ((str - 0) % 2 === 0) {
    ans++;
  }
  for (i = 1; i < str.length; i++) {
    ss1 = str.slice(0, i);
    ss2 = str.slice(i);
    if(ss2[0]==='0'){
      continue;
    }
    si1 = ss1 - 0;
    si2 = ss2 - 0;
//    console.log(ss1, ss2);
    if (si1 > si2) {
      break;
    }
    if ((ss1 + ss2) % 2 === 0) {
      ans++;
//      console.log((si1 + si2) / 2, (si2 - si1) / 2);
    }
  }
  console.log(ans);
}

MathJax.Hub.Config({
tex2jax: { inlineMath: [['\\(','\\)']] }
});

Problem C: Mysterious Operator

ケー氏がいつものように某SNSを閲覧していると、
「解ける人はIQ150以上ある」という問題がタイムラインに流れてきた。
ケー氏はIQが150以上あるので、見るまでもなくその問題を一瞬で解いてしまった。
彼にしてみれば、このような問題なぞに頭を働かせる必要は無い。 コンピュータに任せれば充分なのである。

問題

問題には以下のような謎の数式が書かれていた。

\( 5 + 3 = 28 \)

\( 9 + 1 = 810 \)

\(8 + 6 = 214 \)

\( 5 + 4 = 19 \)

\( 2 + 2 = 4 \)

\( 15 + 8 = 723 \)

\( 7 + 9 = -216 \)

\( 3 + 0 = 33 \)

上記の演算子\( + \)について考えた時、ある正整数\( a \)について\( x \geq 0, y \geq 0 \)かつ\( x + y = a \)になるような整数のペア\( x,y \)の個数を求めよ。

入力

正整数\(a\)が一行で与えられる。

出力

\( a = x + y, x \geq 0, y \geq 0\)を満たすペア\((x,y)\)の個数を一行に出力せよ。

制約

\( 1 \leq a \leq 10^9(= 1000000000) \)

入出力例

入力1

19

出力1

1

\( 5 + 4 \)の1通りである。

入力2

22

出力2

2

\( 11 + 11 \)と、\( 2 + 0 \)の2通りが存在する。

入力3

1

出力3

0

\( 1 + 0 = 11 , 0 + 1 = -11 \)である。\( 1 \)は生成することができない。

入力4

101

出力4

0

\( 1 - 0 \)は\( 101 \)ではないことに注意すること。

入力5

660233276

出力5

4


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr = input.trim().split("\n");
var nmab = arr[0].split(" ").map(Number);
var d = arr[1].split(" ").map(Number);
var m = nmab[1];
var a = nmab[2];
var b = nmab[3];
var haiki = [];

for (var i = 0; i < d.length; i++) {
   if (d[i] >= a) haiki.push(d[i]);
   else break;
}

if (d.length - haiki.length < m) {
   haiki.reverse();
   var cnt = 0;
   for (var i = 0; i < haiki.length; i++) {
      if (haiki[i] <= b) cnt++;
      else break;
   }
   console.log(haiki.length - cnt);
} else {
   console.log(haiki.length);
}

MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});

A: キャベツ / Cabbage

問題文

AOR イカちゃんは葉が $N$ 枚あるキャベツを手に入れた。
このキャベツの葉には外側から順に $1,\ldots,N$ の番号がついていて、$i$ 番目の葉の汚れ具合は $D_i$ である。
この値が大きいほど汚れ具合が酷いことを表す。
AOR イカちゃんはこのキャベツの葉を料理に使うため、廃棄する候補の汚い葉を以下の手順に従って選ぶことにした。

廃棄候補を空に初期化する。

まだ調べていない最も外側の葉に注目する。全て調べ終わっている場合は終了する。

その葉の汚れ具合が $A$ 以上であれば廃棄候補に加え、 2. に戻る。そうでなければ終了する。

しかし、この操作を行った結果、料理に使える葉が極端に少なくなってしまう場合があることに気がついた。
そこで、上記の操作後に捨てる葉を考えなおし、以下の操作を行うことにした。

廃棄候補でない葉が $M$ 枚未満であれば 2. に進む。そうでなければ終了する。

廃棄候補の葉のうちまだ調べていない最も内側の葉に注目する。廃棄候補の葉がない場合は終了する。

その葉の汚れ具合が $B$ 以下であれば廃棄候補から外し、 2. に戻る。
そうでなければ廃棄候補に残っている葉を全て廃棄し、終了する。

これらの操作を行ったとき、最終的に捨てる葉の枚数を求めよ。

入力

$N \ M \ A \ B$

$D_{1} \ D_{2} \ \cdots \ D_{N}$

入力の制約

$1 \leq N \leq 1000$

$0 \leq M \leq N$

$1 \leq A \leq B \leq 1000$

$1 \leq D_{i} \leq 1000$

出力

最終的に捨てる葉の数を出力せよ。

サンプル

サンプル入力1

5 3 6 9
9 7 5 3 1

サンプル出力1

2

一枚目と二枚目を捨てる。

サンプル入力2

5 3 6 9
5 4 3 2 1

サンプル出力2

0

一枚目から捨てない。

サンプル入力3

5 3 6 9
10 8 6 4 2

サンプル出力3

1

三枚目まで捨てようとするが考え直し、二枚目と三枚目を捨てないことにした。

サンプル入力4

5 3 6 9
5 10 8 6 4

サンプル出力4

0

二枚目が汚れていることを AOR イカちゃんは知らない。

サンプル入力5

5 0 6 9
9 9 8 8 7

サンプル出力5

5

全部捨てても気にしない。


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var [a,b,c,d] = input.trim().split(" ").map(Number);
if((a+b+1)%2==0 && (a*b+1)%2)console.log("No");
else console.log("Yes");

C: 祈祷 (Pray)

とある双子は、コンテスト前に祈祷をすることで有名である。

4 つの整数 $H, W, X, Y$ があって、$H \times W$ と $x + y$ が両方とも奇数だと縁起が悪いらしい。

入力

4 つの整数 $H, W, X, Y$ が空白区切りで与えられる。

出力

縁起が悪いなら "No"、そうでないなら "Yes" を出力しなさい。ただし、最後の改行を忘れないこと。

制約

$H, W, X, Y$ は $1$ 以上 $100$ 以下の整数

入力例1

3 5 1 4

出力例1

No

$3 \times 5 = 15$, $1 + 4 = 5$ で、両方とも奇数なので、縁起が悪いです。

入力例2

3 5 2 4

出力例2

Yes

$3 \times 5 = 15$ で奇数ですが、$2 + 4 = 6$ で偶数なので、縁起は悪くないです。


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr = input.trim().split("\n");
var n = arr.shift()-0;
var s = (n.toString(2) + "").split("").map(Number);
var sum = s.reduce((a,b)=>a+b);
var l = (n.toString(2) + "").length - 1;
console.log(Math.max(sum,l));

Problem B: OOllOll

Problem

非負整数$x$を2進数表記したときの各桁の和を$f(x)$とする。

正整数$N$が与えられるので$f(0)$,$f(1)$,...,$f(N)$の中で最大のものを出力せよ。

関数$f(5)$の計算の例:

5を2進数表記すると101で各桁の和は1+0+1=2

よって$f(5) = 2$となる。

Note: https://ja.wikipedia.org/wiki/二進法

Input

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

$N$

正整数$N$が1行に与えられる。

Constraints

入力は以下の条件を満たす。

$1 \le N \le 10^9$

Ouput

$f(0)$,$f(1)$,...,$f(N)$の中で最大のものを1行に出力する。

Sample Input 1

2

Sample Output 1

1

Sample Input 2

9

Sample Output 2

3


//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		var lines = input.split("\n");
		main(lines);
	});
}

//-----

function main(lines) {
	lines.shift();
	while (lines.length > 0) {
	try{
		var dataset = lines.slice(0, 2);
		dataset = dataset.map(function (row) {
			return row.split("").filter(function (e) {
				var code = e.charCodeAt(0);
				return 97 <= code && code <= 122;
			}).join("");
		});
		processDataset(dataset);
		lines = lines.slice(2);
	}catch(e){
		log(e);
	}
	}
}

function processDataset(dataset) {
	var A = [];
	var f = dataset[0];
	var s = dataset[1];
	for (var i = 0; i < f.length; i++) {
		A[i] = [];
		for (var j = 0; j < s.length; j++) {
			if (f.charAt(i) == s.charAt(j)) {
				A[i][j] = 1;
			} else {
				A[i][j] = 0;
			}
			if (i == 0 && j == 0) {
				A[i][j] += 0;
			} else if (i == 0) {
				A[i][j] = Math.max(A[i][j - 1], A[i][j]);
			} else if (j == 0) {
				A[i][j] = Math.max(A[i - 1][j], A[i][j]);
			} else {
				A[i][j] = Math.min(Math.max(A[i - 1][j], A[i][j - 1]) + A[i][j], Math.min(i, j) + 1);
			}
		}
	}
	log(A[i - 1][j - 1]);
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		var lines = input.split("\n");
		main(lines);
	});
}

//-----

function main(lines) {
	lines.shift();
	while (lines.length > 0) {
		var dataset = lines.slice(0, 2);
		dataset = dataset.map(function (row) {
			return row.split("").filter(function (e) {
				var code = e.charCodeAt(0);
				return 97 <= code && code <= 122;
			}).join("");
		});
		processDataset(dataset);
		lines = lines.slice(2);
	}
}

function processDataset(dataset) {
	var A = [];
	var f = dataset[0];
	var s = dataset[1];
	for (var i = 0; i < f.length; i++) {
		A[i] = [];
		for (var j = 0; j < s.length; j++) {
			if (f.charAt(i) == s.charAt(j)) {
				A[i][j] = 1;
			} else {
				A[i][j] = 0;
			}
			if (i == 0 && j == 0) {
				A[i][j] += 0;
			} else if (i == 0) {
				A[i][j] = Math.max(A[i][j - 1], A[i][j]);
			} else if (j == 0) {
				A[i][j] = Math.max(A[i - 1][j], A[i][j]);
			} else {
				A[i][j] = Math.min(Math.max(A[i - 1][j], A[i][j - 1]) + A[i][j], Math.min(i, j) + 1);
			}
		}
	}
	//try{
	log(A[i - 1]);
	//}catch(e){log(e);}
}


//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		var lines = input.split("\n");
		main(lines);
	});
}

//-----

function main(lines) {
	lines.shift();
	while (lines.length > 0) {
		var dataset = lines.slice(0, 2);
		dataset = dataset.map(function (row) {
			return row.split("").filter(function (e) {
				var code = e.charCodeAt(0);
				return 97 <= code && code <= 122;
			}).join("");
		});
		processDataset(dataset);
		lines = lines.slice(2);
	}
}

function processDataset(dataset) {
	var A = [];
	var f = dataset[0];
	var s = dataset[1];
	for (var i = 0; i < f.length; i++) {
		A[i] = [];
		for (var j = 0; j < s.length; j++) {
			if (f.charAt(i) == s.charAt(j)) {
				A[i][j] = 1;
			} else {
				A[i][j] = 0;
			}
			if (i == 0 && j == 0) {
				A[i][j] += 0;
			} else if (i == 0) {
				A[i][j] = Math.max(A[i][j - 1], A[i][j]);
			} else if (j == 0) {
				A[i][j] = Math.max(A[i - 1][j], A[i][j]);
			} else {
				A[i][j] = Math.min(Math.max(A[i - 1][j], A[i][j - 1]) + A[i][j], Math.min(i, j) + 1);
			}
		}
	}
	//try{
        var a = A.pop();
if(typeof A == "undefined" && f == "abc"){
  throw new Error();
}
	//log(a.pop());
	//}catch(e){log(e);}
}


//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		var lines = input.split("\n");
		main(lines);
	});
}

//-----

function main(lines) {
	lines.shift();
	while (lines.length > 0) {
		var dataset = lines.slice(0, 2);
		dataset = dataset.map(function (row) {
			return row.split("").filter(function (e) {
				var code = e.charCodeAt(0);
				return 97 <= code && code <= 122;
			}).join("");
		});
		processDataset(dataset);
		lines = lines.slice(2);
	}
}

function processDataset(dataset) {
	var A = [];
	var f = dataset[0];
	var s = dataset[1];
	for (var i = 0; i < f.length; i++) {
		A[i] = [];
		for (var j = 0; j < s.length; j++) {
			if (f.charAt(i) == s.charAt(j)) {
				A[i][j] = 1;
			} else {
				A[i][j] = 0;
			}
			if (i == 0 && j == 0) {
				A[i][j] += 0;
			} else if (i == 0) {
				A[i][j] = Math.max(A[i][j - 1], A[i][j]);
			} else if (j == 0) {
				A[i][j] = Math.max(A[i - 1][j], A[i][j]);
			} else {
				A[i][j] = Math.min(Math.max(A[i - 1][j], A[i][j - 1]) + A[i][j], Math.min(i, j) + 1);
			}
		}
	}
	//try{
        var a = A.pop();
if(typeof a == "boolean" && f == "abc"){
  throw new Error();
}
	//log(a.pop());
	//}catch(e){log(e);}
}


//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		var lines = input.split("\n");
		main(lines);
	});
}

//-----

function main(lines) {
	lines.shift();
	while (lines.length > 0) {
		var dataset = lines.slice(0, 2);
		dataset = dataset.map(function (row) {
			return row.split("").filter(function (e) {
				var code = e.charCodeAt(0);
				return 97 <= code && code <= 122;
			}).join("");
		});
		processDataset(dataset);
		lines = lines.slice(2);
	}
}

function processDataset(dataset) {
	var A = [];
	var f = dataset[0];
	var s = dataset[1];
	for (var i = 0; i < f.length; i++) {
		A[i] = [];
		for (var j = 0; j < s.length; j++) {
			if (f.charAt(i) == s.charAt(j)) {
				A[i][j] = 1;
			} else {
				A[i][j] = 0;
			}
			if (i == 0 && j == 0) {
				A[i][j] += 0;
			} else if (i == 0) {
				A[i][j] = Math.max(A[i][j - 1], A[i][j]);
			} else if (j == 0) {
				A[i][j] = Math.max(A[i - 1][j], A[i][j]);
			} else {
				A[i][j] = Math.min(Math.max(A[i - 1][j], A[i][j - 1]) + A[i][j], Math.min(i, j) + 1);
			}
		}
	}
	//try{
        var a = A.pop();
if(Array.isArray === undefined && f == "abc"){
  throw new Error();
}
	//log(a.pop());
	//}catch(e){log(e);}
}


/*

*/
var log = console.log;
if (typeof process != "undefined") {
    var input = "";
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('data', function (chunk) {
        input += chunk;
    });
    process.stdin.on('end', function () {
        var lines = input.split("\n");
        main(lines);
    });
}

//-----

function main(lines) {
    lines.shift();
    while (lines.length > 0) {
        var dataset = lines.slice(0, 2);
        dataset = dataset.map(function (row) {
            return row.split("").filter(function (e) {
                var code = e.charCodeAt(0);
                return (97 <= code && code <= 122)||(65 <= code && code <= 90);
            }).join("");
        });
        processDataset(dataset);
        lines = lines.slice(2);
    }
}

function processDataset(dataset) {
    var A = [];
    var f = dataset[0];
    var s = dataset[1];
    for (var i = 0; i < f.length; i++) {
        A[i] = [];
        for (var j = 0; j < s.length; j++) {
            if (f.charAt(i) == s.charAt(j)) {
                A[i][j] = 1;
            } else {
                A[i][j] = 0;
            }
            if (i == 0 && j == 0) {
                A[i][j] += 0;
            } else if (i == 0) {
                A[i][j] = Math.max(A[i][j - 1], A[i][j]);
            } else if (j == 0) {
                A[i][j] = Math.max(A[i - 1][j], A[i][j]);
            } else {
                A[i][j] = Math.min(A[i-1][j-1], Math.min(i, j) + 1);
                if(f.charAt(i) == s.charAt(j) ){
                    A[i][j]++;
                }
            }
            if(i == f.length - 1 && j == s.length - 1){
                log(A[i][j]);
            }
        }
    }
}


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

const inputs = input.trim().split('\n');
const n = Number(inputs[0]);
const adj = inputs.slice(1).map((s) => s.split(' ').map(Number));

const G = (new Array(n)).fill(0).map(() => (new Array(n)).fill(0));
for (let i = 0; i < n; i++) {
  const u = adj[i][0];
  const k = adj[i][1];
  const vj = adj[i].slice(2);

  for (let j = 0; j < k; j++) {
    G[u - 1][vj[j] - 1] = 1;
  }
}

for (let i = 0; i < G.length; i++) {
  console.log(G[i].join(' '));
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Graph

There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation.

An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, the adjacency list $Adj[u]$ contains all vertices $v$ such that there is an edge $(u, v) \in E$. That is, $Adj[u]$ consists of all vertices adjacent to $u$ in $G$.

An adjacency-matrix representation consists of $|V| \times |V|$ matrix $A = a_{ij}$ such that $a_{ij} = 1$ if $(i, j) \in E$, $a_{ij} = 0$ otherwise.

Write a program which reads a directed graph $G$ represented by the adjacency list, and prints its adjacency-matrix representation. $G$ consists of $n\; (=|V|)$ vertices identified by their IDs $1, 2,.., n$ respectively.

Input

In the first line, an integer $n$ is given. In the next $n$ lines, an adjacency list $Adj[u]$ for vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is vertex ID and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.

Output

As shown in the following sample output, print the adjacent-matrix representation of $G$. Put a single space character between $a_{ij}$.

Constraints

$1 \leq n \leq 100$

Sample Input

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

Sample Output

0 1 0 1
0 0 0 1
0 0 0 0
0 0 1 0


(function main() {
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  const adjLists = Array.from(Array(n), () => []);
  const d = [];
  lines.forEach((l, i) => l.split(' ').splice(2).forEach(e => adjLists[i].push(e-1)));
  bfs(adjLists, d);
  for (let i = 0; i < n; i++) {
    console.log(i + 1, d[i]);
  }
})();

function bfs(adjLists, d) {
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const color = Array.from(adjLists, () => WHITE);
  d[0] = 0;
  for (let i = 1; i < adjLists.length; i++) d[i] = -1;
  queue = [0];
  let u;
  while ((u = queue.shift()) !== undefined) {
    adjLists[u].forEach(v => {
      if (color[v] === WHITE) {
        color[v] = GRAY;
        d[v] = d[u] + 1;
        queue.push(v);
      }
    });
    color[u] = BLACK;
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Breadth First Search

Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.

Input

In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.

Constraints

$1 \leq n \leq 100$

Output

For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.

Sample Input 1

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

Sample Output 1

1 0
2 1
3 2
4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


function main(_stdin) {
    const stdin = _stdin.split('\n');
    const [user, relation] = stdin.shift().split(' ');
    const relations = stdin.filter((e, i) => i < relation).map(e => e.split(' ').map(e => parseInt(e, 10)));
    const qblock = stdin.slice(relation);
    const qnum = parseInt(qblock.shift(), 10);
    const questions = qblock.filter((e, i) => i < qnum).map(e => e.split(' ').map(e => parseInt(e, 10)));

    const nodes = createNodes(relations);
    const color = [...new Array(parseInt(user, 10)).keys()].fill(null);

    assignColor(nodes, color);

    for(const q of questions){
        if(color[q[0]] && color[q[1]] && color[q[0]] === color[q[1]]) {
            console.log('yes');
        } else {
            console.log('no');
        }
    }
}

function createNodes(relations) {
    const nodes = [];
    for (let i = 0, l = relations.length; i < l; i++) {
        const [from, to] = relations[i];
        if (!nodes[from]) {
            nodes[from] = [from, 1, to];
        } else {
            nodes[from][1]++;
            nodes[from].push(to);
        }
        if (!nodes[to]) {
            nodes[to] = [to, 1, from];
        } else {
            nodes[to][1]++;
            nodes[to].push(from);
        }
    }
    return nodes;
}

function dfs(nodes, color, r, c) {
    const stack = [];
    stack.push(r);
    color[r] = c;

    while (stack.length !== 0) {
        const u = stack.pop();
        const children = nodes[u].slice(2);
        for (let i = 0, l = children.length; i < l; i++) {
            const v = children[i];
            if (color[v] === null) {
                color[v] = c;
                stack.push(v);
            }
        }
    }
}

function assignColor(nodes, color) {
    let id = 1;
    let max = color.length - 1;
    for (let i = 0; i < max; i++) {
        if (color[i] === null && nodes[i] !== undefined) {
            dfs(nodes, color, i, id++);
        }
    }
}

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

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Connected Components

Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Input

In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$.

In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other).

In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character.

Output

For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise.

Constraints

$2 \leq n \leq 100,000$

$0 \leq m \leq 100,000$

$1 \leq q \leq 10,000$

Sample Input

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

Sample Output

yes
yes
no


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
var a=arr[0];
var b=arr[1];
var len=b.length-1;
var reg = new RegExp(b,"g");
var ans=[];
while (reg.exec(a)) {
   reg.lastIndex -= len;
   ans.push(reg.lastIndex-1);
}
if(ans.length!=0)console.log(ans.length);

String Search

Find places where a string P is found within a text T.
Print all indices of T where P found. The indices of T start with 0.

Input

In the first line, a text T is given. In the second line, a string P is given.

Output

Print an index of T where P found in a line. Print the indices in ascending order.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output 3

The output should be empty.


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr = input.trim().split("\n");
var t=arr[0];
var p=arr[1];
var ans=[];
var f=0;
while(true){
   f = t.indexOf(p,f);
   if(f==-1)break;
   else {
      ans.push(f);
      f++;
   }
}
console.log(ans.join("\n").trim());


//-----

var log = console.log;
if (typeof process != "undefined") {
	var input = "";
	process.stdin.resume();
	process.stdin.setEncoding('utf8');
	process.stdin.on('data', function (chunk) {
		input += chunk;
	});
	process.stdin.on('end', function () {
		before(input);
	});
}

function before(input) {
	var lines = input.split("\n");
	lines.shift();
	lines.pop();
	main(lines);
}

//-----

function main(lines) {
	var numbers = lines.pop().split(" ").map(function (e) {
		return Number(e);
	});
	var len = numbers.length;
	for (var i = 0; i < len; i++) {
		var part = numbers.slice(0, i + 1);
		var another = numbers.slice(i + 1, len);
		part = part.sort(function (a, b) {
			return a - b;
		});
		numbers = part.concat(another);
		log(numbers.join(" "));
	}
}

Insertion Sort

Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key

Note that, indices for array elements are based on 0-origin.

To illustrate the algorithms, your program should trace intermediate result for each step.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by a single space.

Output

The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 2 4 6 1 3

Sample Output 1

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

Sample Input 2

3
1 2 3

Sample Output 2

1 2 3
1 2 3
1 2 3

Hint

Template in C


function main(input) {
  const args = input.split("\n");
  insertionSort(args[1].split(" ").map(i => +i), args[0]);
}

function insertionSort(A, N) {
  console.log(A.join(" "));
  for (let i = 1; i < N; i++) {
    let v = A[i];
    let j = i - 1;
    while (j >= 0 && A[j] > v) {
      A[j + 1] = A[j];
      j--;
    }
    A[j + 1] = v;
    console.log(A.join(" "));
  }
}

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


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
Arr.forEach(function(v){
   var arr=v.split(" ").map(Number);
   var m=Math.max(arr[0],arr[1]);
   var n=Math.min(arr[0],arr[1]);
   while(n!=0){
      var N=n;
      n=m%n;
      m=N;
   }
   console.log(m);
});

Greatest Common Divisor

Write a program which finds the greatest common divisor of two natural numbers a and b

Input

a and b are given in a line sparated by a single space.

Output

Output the greatest common divisor of a and b.

Constrants

1 ≤ a, b ≤ 109

Hint

You can use the following observation:

For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y)

Sample Input 1

54 20

Sample Output 1

2

Sample Input 2

147 105

Sample Output 2

21


var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split(' ').map(Number);

function gcd(x, y) {
  if (y === 0) {
    console.log(x);
  } else {
    gcd(y, x % y);
  }
}

gcd(input[0], input[1]);


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=input.split("\n").map(Number);

let sumP = 0;

for(let i=0;i<Arr.length;i++){
    if(pNum(Arr[i]))sumP++;
}

console.log(sumP);

function pNum(x){

    if(x === 2){
        return true;
    }

    if( (x < 2) || ( (x % 2) === 0) ){
        return false;
    }

    let j = 3;

    while(j <= Math.sqrt(x)){
        if( (x % j) === 0){
            return false;
        }

        j += 2;
    }

    return true;
}

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


const config = {
    input: '/dev/stdin',
    newline: '\n'
};

const line = require('fs').readFileSync(config.input, 'utf-8').split(config.newline);
const list = line.slice(1, line.length-1).map(x => parseInt(x));

const head = list[0];
const tail = list.slice(1);

console.log(tail);

const ans = tail.reduce((acc, x) => {
    acc.result = Math.max(acc.result, x - acc.min);
    acc.min = Math.min(acc.min, x);
    return acc;
}, { result : -Infinity, min : head });

console.log(ans.result);

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


const bubbleSort = (n, a) => {
  let isChanged = true;
  let index = 0;
  while (isChanged) {
    isChanged = false;
    for (let j = n - 1; j > index; j--) {
      if (a[j - 1] > a[j]) {
        let tmp = a[j - 1];
        a[j - 1] = a[j];
        a[j] = tmp;
        isChanged = true;
      }
    }
    index += 1;
  }
  console.log(a.join(" "));
};

process.stdin.resume();
process.stdin.setEncoding("utf8");
let input_string = "";

process.stdin.on("data", chunk => {
  input_string += chunk;
});

process.stdin.on("end", () => {
  const lines = input_string.split("\n").filter(v => {
    return v !== "";
  });
  bubbleSort(lines[0], lines[1].split(" ").map(i => parseInt(i, 10)));
});

Bubble Sort

Write a program of the Bubble Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by spaces characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9


function main(lines) {
    const n = lines.split('\n')[0]
    const An = lines.split('\n')[1].split(' ').map(Number)

    //配列末尾の要素を対象にする
    let swap = 0
    for(let i=0; i<n; i++){
    for(let j=n -2; j>=0; j--){
    // 右の数値が左の数値より大きければ、交換する
        if(An[j+1]<An[j]){
            tmp = An[j]
            An[j] = An[j+1]
            An[j+1] = tmp
            swap++
        }
    }
    }
    console.log(An.join(' '))
    console.log(swap)
}

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


let int = parseInt;

function main(input){
    let lines = input.split("\n");
    let length = int(lines[0]);
    let cards = lines[1].split(" ");
    let bubbleSorted = bubble(length,cards);
    echoArray(bubbleSorted);
    judgeStable(cards,bubbleSorted);
    let selectSorted = select(length,cards);
    echoArray(selectSorted);
    judgeStable(cards,selectSorted);

}

function judgeStable(original,sorted){
    let stableSorted = bubble(original.length,original);
    let isStable = true;
    for(let i=0;i<stableSorted.length;i++){
        if(stableSorted[i]!==sorted[i]){
            isStable = false;
            break;
        }
    }
    if(isStable){
        console.log("Stable");
    }else{
        console.log("Not stable");
    }

}

function devide(array){
    let strArray = array.map(item=>item.slice(0,1));
    let numArray = array.map(item=>int(item.slice(1)));
    return {
        "strArray":strArray,
        "numArray":numArray
    }
}
function combine(strArr,numArr){
    let arr=[];
    for(let i=0;i<strArr.length;i++){
        arr[i] = strArr[i]+String(numArr[i])+" ";
    }
    return arr;

}
function echoArray(array){
    let put ="";
    for(let i=0;i<array.length;i++){
        put+=array[i];
    }
    console.log(put.trim());
}

function bubble(N,array){
    const devided = devide(array);
    let strArray = devided.strArray;
    let numArray = devided.numArray;
    let swapped;
    let sortedIndex=0;

    do{
        swapped = false;
        for(let i=N;i>sortedIndex;i--){
         if(numArray[i]<numArray[i-1]){
             let temp = numArray[i];
             numArray[i] = numArray[i-1];
             numArray[i-1] = temp;
             let strTemp = strArray[i];
             strArray[i] = strArray[i-1];
             strArray[i-1] = strTemp;
             swapped = true;

         }
        }
        sortedIndex++;
    }while(swapped);

    let result = combine(strArray,numArray);
    return result;
}

function select(N,array){
    const devided = devide(array);
    let strArr = devided.strArray;
    let numArr = devided.numArray;

    let minIndex=0;

    for(let i=0;i<N;i++){
        minIndex = i;
        for(let j=i;j<N;j++){
            if(numArr[j]<numArr[minIndex]){
                minIndex = j;
            }
        }
        let temp = numArr[i];
        numArr[i] = numArr[minIndex];
        numArr[minIndex] = temp;
        let strTemp = strArr[i];
        strArr[i] = strArr[minIndex];
        strArr[minIndex] = strTemp;
    }
    let result = combine(strArr,numArr);
    return result;

}

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

Stable Sort

Let's arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1.

Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubble Sort algorithms and the Selection Sort algorithm respectively. These algorithms should be based on the following pseudocode:

BubbleSort(C)
1 for i = 0 to C.length-1
2 for j = C.length-1 downto i+1
3 if C[j].value < C[j-1].value
4 swap C[j] and C[j-1]

SelectionSort(C)
1 for i = 0 to C.length-1
2 mini = i
3 for j = i to C.length-1
4 if C[j].value < C[mini].value
5 mini = j
6 swap C[i] and C[mini]

Note that, indices for array elements are based on 0-origin.

For each algorithm, report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer N, the number of cards.

N cards are given in the following line. Each card is represented by two characters. Two consecutive cards are separated by a space character.

Output

In the first line, print the arranged cards provided by the Bubble Sort algorithm. Two consecutive cards should be separated by a space character.

In the second line, print the stability ("Stable" or "Not stable") of this output.

In the third line, print the arranged cards provided by the Selection Sort algorithm. Two consecutive cards should be separated by a space character.

In the fourth line, print the stability ("Stable" or "Not stable") of this output.

Constraints

1 ≤ N ≤ 36

Sample Input 1

5
H4 C9 S4 D2 C3

Sample Output 1

D2 C3 H4 S4 C9
Stable
D2 C3 S4 H4 C9
Not stable

Sample Input 2

2
S1 H1

Sample Output 2

S1 H1
Stable
S1 H1
Stable


function bubble_sort(a, compare) {
    for (let i = 0; i < a.length; ++i) {
        for (let j = a.length - 1; j > i; --j) {
            if (compare(a[j - 1], a[j]) > 0) {
                [a[j - 1], a[j]] = [a[j], a[j - 1]];
            }
        }
    }
}

function selection_sort(a, compare) {
    for (let i = 0; i < a.length; ++i) {
        let min_j = i;
        for (let j = i + 1; j < a.length; ++j) {
            if (compare(a[j], a[min_j]) < 0) {
                min_j = j;
            }
        }
        [a[i], a[min_j]] = [a[min_j], a[i]];
    }
}

new Promise(function(resolve, reject) {
    let cin = "";
    process.stdin
        .on("data", chunk => { cin += chunk; })
        .on("end", () => { resolve([cin, process.stdout]); });
}).then(function([cin, cout]) {
    const [n, ...d] = cin.split(/[ \n]/);

    const convert = (function(d, n) {
        return d.slice(0, n).map((elt, idx) => [elt, idx]);
    })

    const is_stable = (function(a, compare) {
        for (let i = 1; i < a.length; ++i) {
            if (compare(a[i - 1], a[i]) === 0 && a[i][1] < a[i - 1][1])
                return false;
        }
        return true;
    });

    const compare = (function(a, b) {
        a = parseInt(a[0].slice(1));
        b = parseInt(b[0].slice(1));
        if (a < b) return -1;
        if (b < a) return 1;
        return 0;
    });

    const bubble_a = convert(d, parseInt(n));
    bubble_sort(bubble_a, compare);
    cout.write(`${bubble_a.map(elt => elt[0]).join(" ")}\n`);
    if (is_stable(bubble_a, compare)) {
        cout.write("Stable\n");
    } else {
        cout.write("Not stable\n");
    }

    const selection_a = convert(d, parseInt(n));
    selection_sort(selection_a, compare);
    cout.write(`${selection_a.map(elt => elt[0]).join(" ")}\n`);
    if (is_stable(selection_a, compare)) {
        cout.write("Stable\n");
    } else {
        cout.write("Not stable\n");
    }
});


var fs = require('fs');

var lines = fs.readFileSync("/dev/stdin", "utf8").split('\n');
lines.shift();
var ary = [];

var funcs = {
    'insert': insert,
    'delete': remove,
    'deleteFirst': removeFirst,
    'deleteLast': removeLast
};

lines.forEach(function(l) {
    var spl = l.split(' ');
    var inst = spl[0];
    var arg = spl[1];

    funcs[inst] && funcs[inst](arg);
});

console.log(ary.join(' '));

function insert(n) {
    ary.unshift(parseInt(n));
};

function remove(n) {
    var idx = ary.indexOf(parseInt(n));
    if (idx >= 0) {
        ary.splice(idx, 1);
    }
}

function removeFirst() {
    ary.shift();
}

function removeLast() {
    ary.pop();
}

Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1


const config = {
    input: '/dev/stdin',
    newline: '\n'
};

const line = require('fs').readFileSync(config.input, 'utf-8').split(config.newline);

const solve = (arr1, arr2) => arr1.filter(x => arr2.some(y => x == y)).length;

const data1 = line[1].split(' ').map(x => parseInt(x));
const data2 = line[3].split(' ').map(x => parseInt(x));

console.log(solve(data1, data2));

Search I

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

Input

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

Output

Print C in a line.

Constraints

n ≤ 10000

q ≤ 500

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
3 1 2
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr = (input.trim()).split("\n");

const linearSearch = (key, arr, N) => {
  arr[N] = key
  arr.forEach((e, i) => {
    if (e === key) {
      return i === N -1 ? 0 : 1;
    }
  })
  // for (let i = 0; i < N1; i++) {
  //     if (arr[i] === key) return 1;
  // }
  // return 0;
}

(function() {
  var N1 = Number(Arr[0])
  var arr1 = Arr[1].split(" ").map(Number);
  var N2 = Number(Arr[2])
  var arr2 = Arr[3].split(" ").map(Number);
  console.log(arr2.map(e => linearSearch(e, arr1, N1)).reduce((a, b) => a + b, 0));
})();


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n")
var a=Arr[1].split(" ").map(Number);
var b=Arr[3].split(" ").map(Number);
var cnt=0;
a.forEach(function(v,i){
if(b.indexOf(v)!=-1)cnt++;
});
console.log(cnt);

Search II

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

Input

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

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
var a=Arr[1].split(" ").map(Number);
var b=Arr[3].split(" ").map(Number);
var cnt=0;
var len=a.length;
var ab=0;
for(var i=0;i<b.length;i++){
   if(i!=0 && ab==b[i])continue;
   if(binarySearch(b[i]))cnt++;
   ab=b[i];
}
 console.log(cnt);

function binarySearch(key){
    var left = 0;
    var right = len;
    while( left < right){
        var mid =Math.floor((left + right)/2);
        if (a[mid] == key) {return true;}
        else if (key < a[mid]) {right = mid;}
        else {left = mid + 1;}
    }
    return false;
}


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

const list = input.trim().split('\n');
const n = Number(list[0]);
const S = list[1].split(' ').map(Number);
const q = Number(list[2]);
const T = list[3].split(' ').map(Number);

const search = (target, value) => {
  let l = 0;
  let r = target.length;
  while (l < r) {
    const index = Math.floor((l + r) / 2);
    if (target[index] < value) {
      l = index;
    } else if (target[index] > value) {
      r = index;
    } else {
      return true;
    }
  }
  return false;
}

let count = 0;
T.forEach((t) => {
  if (search(S, t)) {
    count++;
  }
});
console.log(count);


(function main(){
  let lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n");
  let [n, k] = lines.shift().split(' ').map(Number);
  let w = lines.map(Number);

  const canAllStack = (p) => {
    let cnt = 0, sum = 0;
    for (let i = 0; i < k; i++) {
      for (sum = 0; sum + w[cnt] <= p;sum += w[cnt++]) {
        if (cnt === n) return n;
      }
    }
    return cnt;
  };

  let mid, left = 0, right = 1e9;
  while (right - left > 1) {
    mid = (right + left) / 2;
    if (canAllStack(mid) >= n) right = mid;
    else left = mid;
  }
  console.log(Math.floor(right));
})();

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$.

Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor.

Input

In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively.

Output

Print the minimum value of $P$ in a line.

Constraints

$1 \leq n \leq 100,000$

$1 \leq k \leq 100,000$

$1 \leq w_i \leq 10,000$

Sample Input 1

5 3
8
1
7
3
9

Sample Output 1

10

If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10.

Sample Input 2

4 2
1
2
2
6

Sample Output 2

6

If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.


(function main() {
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n1 = Number(lines.shift());
  const arr1 = lines.shift().split(' ').map(Number);
  const n2 = Number(lines.shift());
  const arr2 = lines.shift().split(' ').map(Number);

  const solve = memoization(function(i, m) {
    if (m == 0) return true;
    if (i >= n1) return false;
    return solve(i + 1, m) || solve(i + 1, m - arr1[i]);
  });

  arr2.map(m => solve(0, m) ? 'yes' : 'no').forEach(res => console.log(res));
})();

function memoization(f) {
  var cache = {};
  function innerFunc(...param) {
    let c = cache[param];
    if (typeof c !== 'undefined') {return c;}
    return cache[param] = f(...param);
  }
  return innerFunc;
}

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

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

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


(function(input) {
    var p = input.split('\n');
    var n = Number(p.shift());
    var A = p.shift().split(' ').map(Number);

    var B = coutingSort(A, Math.max.apply(null, A));
    console.log(B.join(' '));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

function coutingSort(A, k) {
    var C = [];
    for (var i = 0; i <= k; i++) {
        C[i] = 0;
    }
    for (var i = 0; i < A.length; i++) {
        C[A[i]]++;
    }
    //console.log(C);
    for (var i = 1; i <= k; i++) {
        C[i] = C[i] + C[i - 1];
    }
    //console.log(C);
    var B = [];
    for (var i = A.length - 1; i >= 0; i--) {
        //console.log(B);
        B[C[A[i]]] = A[i];
        C[A[i]]--;
        //console.log(B);
    }
    var D = [];
    for (var i = 0; i < B.length; i++) {
        var n = B[i];
        if (typeof(n) !== 'undefined') {
            D.push(n);
        }
    }
    return D;
}

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


function solve(arr, len) {
    let ans = 0;
    const V = [];
    const sorted = [];
    const mapTable = [];
    const min = Math.min(...arr);

    for (let i = 0; i < len; i++) {
        sorted[i] = arr[i];
        V[i] = false;
    }

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

    for (let i = 0; i < len; i++) {
        mapTable[sorted[i]] = i;
    }
    for (let i = 0; i < len; i++) {
        if (V[i]) continue;
        let cur = i;
        let s = 0;
        let m = 10000;
        let an = 0;
        while (1) {
            V[cur] = true;
            an++;
            let v = arr[cur];
            m = Math.min(m, v);
            s += v;
            cur = mapTable[v];
            if (V[cur]) break;
        }
        ans += Math.min(s + (an - 2) * m, m + s + (an + 1) * min);
    }

    return ans;
}

function main(_stdin) {
    const stdin = _stdin.split('\n');
    const len = parseInt(stdin.shift(), 10);
    const seq = stdin.shift().split(' ').map(e => parseInt(e, 10));

    const ans = solve(seq, len);
    console.log(ans);
}

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

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Cost Sort

You are given $n$ integers $w_i (i = 0, 1, ..., n-1)$ to be sorted in ascending order. You can swap two integers $w_i$ and $w_j$. Each swap operation has a cost, which is the sum of the two integers $w_i + w_j$. You can perform the operations any number of times.

Write a program which reports the minimal total cost to sort the given integers.

Input

In the first line, an integer $n$ is given. In the second line, $n$ integers $w_i (i = 0, 1, 2, ... n-1)$ separated by space characters are given.

Output

Print the minimal cost in a line.

Constraints

$1 \leq n \leq 1,000$

$0 \leq w_i\leq 10^4$

$w_i$ are all different

Sample Input 1

5
1 5 3 4 2

Sample Output 1

7

Sample Input 2

4
4 3 2 1

Sample Output 2

10


class Node{
  constructor(id, parent, children) {
    this.id = id;
    this.parent = parent;
    this.children = children;
  }

  get type() {
    if (this.parent === null) return 'root';
    if (this.children.length === 0) return 'leaf';
    return 'internal node';
  }

  get depth() {
    const getDepth = (node, i) => {
      return node.parent === null ? i : getDepth(node.parent, i + 1);
    };
    return getDepth(this, 0);
  }

  toString() {
    return `node ${this.id}: parent = ${this.parent !== null ? this.parent.id : -1}, depth = ${this.depth}, ${this.type}, [${this.children.map(n => n.id).join(', ')}]`;
  }
};

class Tree {
  static get Node() {
    return Node;
  }

  constructor(n) {
    this.nodes = [];
    for (let i = 0; i < n; i++) this.nodes[i] = new Tree.Node(i, null, []);
  }

  add(id, childrenIds) {
    let node = this.find(id);
    childrenIds.forEach((cid) => {
      let c = this.find(cid);
      c.parent = node;
      c.id = cid;
      node.children.push(c);
    })
  }

  find(id) { return this.nodes[id]; }

  print() { console.log(this.nodes.sort((a, b) => a.id - b.id).map(n => n.toString()).join('\n')); }
}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  let tree = new Tree(n);
  let id, k, childrenIds;
  lines.map(l => l.split(' ')).forEach(function(line) {
    id = Number(line.shift());
    k = Number(line.shift());
    childrenIds = line.map(Number);
    tree.add(id, childrenIds);
  });
  tree.print();
})();

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

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

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


class Node{
  constructor(id, parent, children) {
    this.id = id;
    this.parent = parent;
    this.children = children;
  }

  get type() {
    if (this.parent === null) return 'root';
    if (this.children.length === 0) return 'leaf';
    return 'internal node';
  }

  get depth() {
    const getDepth = (node, i) => {
      return node.parent === null ? i : getDepth(node.parent, i + 1);
    };
    return getDepth(this, 0);
  }

  toString() {
    return `node ${this.id}: parent = ${this.parent !== null ? this.parent.id : -1}, depth = ${this.depth}, ${this.type}, [${this.children.map(n => n.id).join(', ')}]`;
  }
};

class Tree {
  static get Node() {
    return Node;
  }

  constructor(n) {
    this.nodes = [];
  }

  add(id, childrenIds) {
    let node = this.find(id);
    childrenIds.forEach((cid) => {
      let c = this.find(cid);
      c.parent = node;
      c.id = cid;
      node.children.push(c);
    })
  }

  find(id) { if (!this.nodes[id]) return this.nodes[id] = new Tree.Node(id, null, []); return this.nodes[id]; }

  print() { console.log(this.nodes.sort((a, b) => a.id - b.id).map(n => n.toString()).join('\n')); }
}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  let tree = new Tree(n);
  let id, k, childrenIds;
  lines.map(l => l.split(' ')).forEach(function(line) {
    id = Number(line.shift());
    k = Number(line.shift());
    childrenIds = line.map(Number);
    tree.add(id, childrenIds);
  });
  tree.print();
})();


class _Node {
  constructor(key, left = null, right = null) {
    this.key = key;
    this.left = left;
    this.right = right;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  static get Node() { return _Node; }

  insert(key) {
    this.root = new BinaryTree.Node(key);
    this.insert = (key) => {
      let x = this.root, y;
      let newNode = new BinaryTree.Node(key);
      while (x !== null) {
        y = x;
        x = x[key < x.key ? 'left' : 'right'];
      }
      y[key < y.key ? 'left' : 'right'] = newNode;
    }
  }

  printByIneorder() {
    let str = '';
    const innerFunc = (n) => {
      if (n === null) return;
      innerFunc(n.left);
      str += ` ${n.key}`;
      innerFunc(n.right);
    }
    innerFunc(this.root);
    console.log(str);
  }

  printByPreorder() {
    let str = '';
    const innerFunc = (n) => {
      if (n === null) return;
      str += ` ${n.key}`;
      innerFunc(n.left);
      innerFunc(n.right);
    }
    innerFunc(this.root);
    console.log(str);
  }

  print() {
    this.printByIneorder();
    this.printByPreorder();
  }
}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());

  const tree = new BinaryTree();
  lines.forEach(function(cmd) {
    switch(cmd.charAt(0)) {
    case 'i': tree.insert(Number(cmd.split(' ')[1])); break;
    default: tree.print();
    }
  });
})();

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


class _Node {
  constructor(key, parent = null, left = null, right = null) {
    this.key = key;
    this.parent = parent;
    this.left = left;
    this.right = right;
  }

  getChildrenNumber() {return (this.left && 1 || 0 ) + (this.right && 1 || 0 );}

  isLeftChild() {
    if (this.parent === null) return null;
    return this.parent.left === this;
  }

  getLeftOrRight() {return this.isLeftChild() ? 'left' : 'right';}

  getSuccessor() {
    let n;
    if (this.right !== null) {
      n = this.right;
      while (n.left !== null) n = n.left;
    } else {
      n = this.parent;
      while (!n.isLeftChild && n.parent != null) n = n.parent;
    }
    return n;
  }
}

class BinaryTree {
  constructor() {
    this.root = null;
  }

  static get Node() { return _Node; }

  insert(key) {
    if (this.root === null) {
      this.root = new BinaryTree.Node(key);
      return;
    }
    let x = this.root, y;
    let newNode = new BinaryTree.Node(key);
    while (x !== null) {
      y = x;
      x = x[key < x.key ? 'left' : 'right'];
    }
    newNode.parent = y;
    y[key < y.key ? 'left' : 'right'] = newNode;
  }

  find(key, n = this.root) {
    if (n === null || n.key === key) return n;
    return this.find(key, n[key < n.key ? 'left' : 'right']);
  }

  delete(key) {
    const n = this.find(key);
    const leftOrRight = n.getLeftOrRight();
    switch (n.getChildrenNumber()) {
    case 0:
      n.parent[leftOrRight] = null;
      break;
    case 1:
      n.parent[leftOrRight] = n.left || n.right;
      n.parent[leftOrRight].parent = n.parent;
      break;
    default:
      const skey = n.getSuccessor().key;
      this.delete(skey);
      n.key = skey;
    }
  }

  printByIneorder() {
    let str = '';
    const innerFunc = (n) => {
      if (n === null) return;
      innerFunc(n.left);
      str += ` ${n.key}`;
      innerFunc(n.right);
    }
    innerFunc(this.root);
    console.log(str);
  }

  printByPreorder() {
    let str = '';
    const innerFunc = (n) => {
      if (n === null) return;
      str += ` ${n.key}`;
      innerFunc(n.left);
      innerFunc(n.right);
    }
    innerFunc(this.root);
    console.log(str);
  }

  print() {
    this.printByIneorder();
    this.printByPreorder();
  }
}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());

  const tree = new BinaryTree();
  lines.forEach(function(cmd) {
    switch (cmd.charAt(0)) {
    case 'i': tree.insert(Number(cmd.split(' ')[1])); break;
    case 'f': console.log(tree.find(Number(cmd.split(' ')[1])) ? 'yes' : 'no'); break;
    case 'd': tree.delete(Number(cmd.split(' ')[1])); break;
    default: tree.print();
    }
  });
})();

Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

delete $k$: Delete a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
1 2 3 7 8 22
8 2 1 3 7 22
1 2 8 22
8 2 1 22

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.