var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
while(true){
   var hw=arr.shift();
   if(hw=="0 0")break;
   hw=hw.split(" ").map(Number);
   var h=hw[0];
   var w=hw[1];
   var yx=[];
   for(var i=0;i<h;i++)yx.push(arr.shift().split(""));
   var ary=[];
   for(var i=0;i<h;i++)ary.push(yx[i].join(""));
   for(var i=0;i<w;i++){
      var str="";
      for(var j=0;j<h;j++)str+=yx[j][i];
      ary.push(str);
   }
   var H=[];
   for(var i=0;i<h;i++)H.push(i);
   while(H.length!=0){
      var v=H.shift();
      //---------------------------------------------
      var str=yx[v][0];
      var j=v;
      var x=0;
      while(true){
         j++;
         x++;
         if(j==h)j=0;
         if(x==w)x=0;
         if(x==0)H=H.filter(function(value){return (j!=value);});
         if(j==v && x==0)break;
         str+=yx[j][x];
      }
      ary.push(str);
      //---------------------------------------------
      var str=yx[v][0];
      var j=v;
      var x=0;
      while(true){
         j--;
         x++;
         if(j<0)j=h-1;
         if(x==w)x=0;
         if(j==v && x==0)break;
         str+=yx[j][x];
      }
      ary.push(str);
      //---------------------------------------------
   }
   var obj={};
   ary.forEach(function(v){
      var len=v.length;
      var vA=v;
      var vB=v.split("").reverse().join("");
      vA=vA+vA;
      vB=vB+vB;
      for(var i=0;i<len;i++){
         var strA=vA.slice(i,len+i);
         var strB=vB.slice(i,len+i);
         while(strA.length!=1){
            if(obj.hasOwnProperty(strA))obj[strA]++;
            else obj[strA]=1;
            strA=strA.slice(0,-1);
         }
         while(strB.length!=1){
            if(obj.hasOwnProperty(strB))obj[strB]++;
            else obj[strB]=1;
            strB=strB.slice(0,-1);
         }
      }
   });
   var max=0;
   var ans="0";
   for(var k in obj){
      if(obj[k]>=2 && max<k.length){max=k.length;ans=k;}
   }
   console.log(ans);
}

Problem B: The Sorcerer's Donut

Your master went to the town for a day. You could have a relaxed day without hearing his
scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he
can't live without eating tens of donuts everyday. What a chore for such a beautiful day.

But last week, you overheard a magic spell that your master was using. It was the time to
try. You casted the spell on a broomstick sitting on a corner of the kitchen. With a flash of
lights, the broom sprouted two arms and two legs, and became alive. You ordered him, then he
brought flour from the storage, and started kneading dough. The spell worked, and how fast he
kneaded it!

A few minutes later, there was a tall pile of dough on the kitchen table. That was enough for
the next week. \OK, stop now." You ordered. But he didn't stop. Help! You didn't know the
spell to stop him! Soon the kitchen table was filled with hundreds of pieces of dough, and he
still worked as fast as he could. If you could not stop him now, you would be choked in the
kitchen filled with pieces of dough.

Wait, didn't your master write his spells on his notebooks? You went to his den, and found the
notebook that recorded the spell of cessation.

But it was not the end of the story. The spell written in the notebook is not easily read by
others. He used a plastic model of a donut as a notebook for recording the spell. He split the
surface of the donut-shaped model into square mesh (Figure B.1), and filled with the letters
(Figure B.2). He hid the spell so carefully that the pattern on the surface looked meaningless.
But you knew that he wrote the pattern so that the spell "appears" more than once (see the next
paragraph for the precise conditions). The spell was not necessarily written in the left-to-right
direction, but any of the 8 directions, namely left-to-right, right-to-left, top-down, bottom-up,
and the 4 diagonal directions.

You should be able to find the spell as the longest string that appears more than once. Here,
a string is considered to appear more than once if there are square sequences having the string
on the donut that satisfy the following conditions.

Each square sequence does not overlap itself. (Two square sequences can share some squares.)

The square sequences start from different squares, and/or go to different directions.

Figure B.1: The Sorcerer's Donut Before
Filled with Letters, Showing the Mesh and 8
Possible Spell Directions

Figure B.2: The Sorcerer's Donut After Filled
with Letters

Note that a palindrome (i.e., a string that is the same whether you read it backwards or forwards)
that satisfies the first condition "appears" twice.

The pattern on the donut is given as a matrix of letters as follows.

ABCD
EFGH
IJKL

Note that the surface of the donut has no ends; the top and bottom sides, and the left and right
sides of the pattern are respectively connected. There can be square sequences longer than both
the vertical and horizontal lengths of the pattern. For example, from the letter F in the above
pattern, the strings in the longest non-self-overlapping sequences towards the 8 directions are
as follows.

FGHE
FKDEJCHIBGLA
FJB
FIDGJAHKBELC
FEHG
FALGBIHCJEDK
FBJ
FCLEBKHAJGDI

Please write a program that finds the magic spell before you will be choked with pieces of donuts
dough.

Input

The input is a sequence of datasets. Each dataset begins with a line of two integers h and w,
which denote the size of the pattern, followed by h lines of w uppercase letters from A to Z,
inclusive, which denote the pattern on the donut. You may assume 3 ≤ h ≤ 10 and 3 ≤ w ≤ 20.

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

Output

For each dataset, output the magic spell. If there is more than one longest string of the same
length, the first one in the dictionary order must be the spell. The spell is known to be at least
two letters long. When no spell is found, output 0 (zero).

Sample Input

5 7
RRCABXT
AABMFAB
RROMJAC
APTADAB
YABADAO
3 13
ABCDEFGHIJKLM
XMADAMIMADAMY
ACEGIKMOQSUWY
3 4
DEFG
ACAB
HIJK
3 6
ABCDEF
GHIAKL
MNOPQR
10 19
JFZODYDXMZZPEYTRNCW
XVGHPOKEYNZTQFZJKOD
EYEHHQKHFZOVNRGOOLP
QFZOIHRQMGHPNISHXOC
DRGILJHSQEHHQLYTILL
NCSHQMKHTZZIHRPAUJA
NCCTINCLAUTFJHSZBVK
LPBAUJIUMBVQYKHTZCW
XMYHBVKUGNCWTLLAUID
EYNDCCWLEOODXYUMBVN
0 0

Output for the Sample Input

ABRACADABRA
MADAMIMADAM
ABAC
0
ABCDEFGHIJKLMNOPQRSTUVWXYZHHHHHABCDEFGHIJKLMNOPQRSTUVWXYZ


function Main(input){
    input = input.split("\n");
    var k = 0;
    while(1){
        var n = parseInt(input[k++],10);
        if(n == 0)
            break;

        input[k] = input[k].split(" ");

        var min = 1000000000;
        for(var i = 0;i < n;i++){
            for(var j = i + 1;j < n;j++){
                var a = Math.abs(parseInt(input[k][i],10) - parseInt(input[k][j],10));
                if(min > a)
                    min = a;
            }
        }
        console.log(min);
        k++;
    }
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));

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

Selection of Participants of an Experiment

Dr. Tsukuba has devised a new method of programming training.
In order to evaluate the effectiveness of this method,
he plans to carry out a control experiment.
Having two students as the participants of the experiment,
one of them will be trained under the conventional method
and the other under his new method.
Comparing the final scores of these two,
he will be able to judge the effectiveness of his method.

It is important to select two students having the closest possible scores,
for making the comparison fair.
He has a list of the scores of all students
who can participate in the experiment.
You are asked to write a program which selects two of them
having the smallest difference in their scores.

Input

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

n

a1 a2 … an

A dataset consists of two lines.
The number of students n is given in the first line.
n is an integer satisfying 2 ≤ n ≤ 1000.
The second line gives scores of n students.
ai (1 ≤ i ≤ n) is the score of the i-th student, which is a non-negative integer not greater than 1,000,000.

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

Output

For each dataset, select two students with the smallest difference in their scores,
and output in a line (the absolute value of) the difference.

Sample Input

5
10 10 10 10 10
5
1 5 8 9 11
7
11 34 83 47 59 29 70
0

Output for the Sample Input

0
1
5

Submitted source-code file size, in bytes.

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

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


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

let count = 0;
var numberOfStudents = 0;
var totalStudents = 0;

while(count < lines.length) {

	if(count%2 == 0) {
		numberOfStudents = +lines[count];
		if (numberOfStudents==0) {
			break;
		} else if(numberOfStudents>1000) {
			console.log('Number of students must not be greater than 1,000.');
			break;
		} else if(numberOfStudents<2) {
			console.log('Number of students must not be less than 2.');
			break;
		} else {
			totalStudents += numberOfStudents;
			if(totalStudents>50000) {
				break;
			}
		}
	} else {
		let scoresString = lines[count].split(' ');

		if(scoresString.length != numberOfStudents) {
			console.log(`Number of students is not equal to number of scores at line ${count+1}`);
			break;
		} else {
		let scores = scoresString.map(score => +score);
			var leastDiff = null;
			var currentDiff;
			for (let i = scores.length - 1; i >= 0; i--) {
				if(isNotGreaterThanMillion(scores[i])) {
					break;
				} else {
					for(j=i; j>=0; j--) {
					if(i) {
						if (leastDiff != null) {
							currentDiff = Math.abs(scores[i] - scores[j-1]);
						if (currentDiff < leastDiff) {
							leastDiff = currentDiff;
						}
					} else {
						leastDiff = Math.abs(scores[i] - scores[j-1]);
					}

				}
					}
				}

			}
			console.log(leastDiff);
		}
	}

count++;

}

function isNotGreaterThanMillion(number) {
	if (number>1000000) {
		return true;
	}
}


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

const lines = input.trim().split('\n');

while (line = lines.shift()) {

    const numbers = line.split(' ').map(Number);
    // Edit from here

    if(numbers.length > 1){
        let keys = [...numbers.keys()]
        let nearest = Math.max(...numbers) - Math.min(...numbers) + 1;
        let result = [];
        for(let key = 0, lngth = numbers.length; key < lngth; key++){

            for(let innerKey = key + 1; innerKey < lngth; innerKey++){
                if( (Math.abs(numbers[keys[key]] - numbers[keys[innerKey]])) < nearest){
                    result = [numbers[keys[key]], numbers[keys[innerKey]]];
                    nearest = (Math.abs(numbers[keys[key]] - numbers[keys[innerKey]]));
                }
            }

        }
        if(result.length === 2){
            const [first, sec] = result
            var res = [first > sec ? first - sec : sec - first ]
        }
        console.log(res.toString())
    }
    // to here
}


const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const lines = input.trim().split('\n');
while (line = lines.shift()) {
	const [n, max] = line.split(' ').map(Number);
	if (n === 0 && max === 0) { break; }
	const temp = [];

	let prices = lines.shift().split(' ').map(Number);
	for (let i = 0; i <= max; i++) {
		for (let j = i; j <= n; j++) {
			if (prices[i] + prices[j] <= max) {
				temp.push(prices[i] + prices[j]);
			}
		}
	}

	const maxShits = Math.max(temp[temp.length - 1]);

	console.log(`${(temp.length > 1 && maxShits <= max) ? maxShits : 'NONE'}`)
}

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


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 bomb(y,x){
   cnt++;
   var dx=[0,-1,1,0];
   var dy=[-1,0,0,1];
   for(var i=0;i<4;i++){
      var X=x+dx[i];
      var Y=y+dy[i];
      if(Y>=h || Y<0 || X>=w || X<0)continue;
      if(yx[Y][X]=="S")continue;
      else if(yx[Y][X]=="."){yx[Y][X]="S";bomb(Y,X);}
      else {
         if(color=="" || color==yx[Y][X])color=yx[Y][X];
         else color="bad";
      }
   }
}
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
while(true){
   var wh=arr.shift();
   if(wh=="0 0")break;
   wh=wh.split(" ").map(Number);
   var w=wh[0];
   var h=wh[1];
   var yx=[];
   for(var i=0;i<h;i++)yx.push(arr.shift().split(""));
   var ans=[0,0];
   for(var y=0;y<h;y++){
      for(var x=0;x<w;x++){
         var color="";
         var cnt=0;
         if(yx[y][x]=="."){yx[y][x]="S";bomb(y,x);}
         if(color=="B")ans[0]+=cnt;
         else if(color=="W")ans[1]+=cnt;
      }
   }
   console.log(ans[0]+" "+ans[1]);
}

Surrounding Area

土地囲い

English text is not available in this practice contest.

ある 2 人の不動産屋が，客船に乗って南の島に向かっていた．青い空，さわやかな風…．2 人は他の乗客とともに船旅を楽しんでいた．ところが，ある日突然発生した竜巻によって客船が沈んでしまった．他の乗客は救助隊によって救助されたが，どういうわけかこの 2 人だけ見落とされてしまった．数日の漂流の後，彼らはある無人島に流れ着いた．この無人島は長方形であり，以下の図のように格子に区切られていた．

図 C-1: 無人島の形状

彼らはとても欲深かったので，助けを呼ぶことではなく，この無人島の土地を売ることを考えていた．そして，彼らは土地を折半するということはせず，土地の奪い合いを始めた．彼らはそれぞれ自分の土地にしたいところを，一方は黒い杭で，もう一方は白い杭で囲み始めた．全ての杭は格子の中央に打たれ，また 1 つの格子に複数の杭が打たれることはなかった．しばらくすると双方とも疲れ果てて，杭を打つことを止めた．

あなたの仕事は，黒い杭および白い杭で囲まれた土地の面積を求めるプログラムを書くことである．ただし，格子 (i, j) が黒い杭に囲まれているとは，直感的には「格子 (i, j) から上下左右に任意に移動したとき，最初に当たる杭は常に黒い杭である」ことを意味する．正確には以下のように定義される．

黒い杭に「拡大隣接した」格子を次のとおりに定める．白い杭についても同様とする．

格子 (i, j) に杭が存在せず，さらに格子 (i, j) に隣接する格子のいずれかに黒い杭が存在するならば，格子 (i, j) は黒い杭に拡大隣接している．

格子 (i, j) に杭が存在せず，さらに格子 (i, j) に隣接する格子のいずれかが黒い杭に拡大隣接しているならば，格子 (i, j) は黒い杭に拡大隣接している．このルールは再帰的に適用される．

このとき，格子 (i, j) が黒い杭に拡大隣接していて，さらに白い杭に隣接していないとき，またそのときに限って，格子 (i, j) が黒い杭に囲まれているという．また逆に，格子 (i, j) が白い杭に拡大隣接していて，さらに黒い杭に隣接していないとき，またそのときに限って，格子 (i, j) が白い杭に囲まれているという．

Input

入力は複数のデータセットから構成される．各データセットは以下のような構成になっている．

w h

a1,1 a2,1 a3,1 ... aw,1

a1,2 a2,2 a3,2 ... aw,2

...

a1,h a2,h a3,h ... aw,h

w は土地の横幅，h は土地の縦幅を表す．これらは 1 ≦ w,h ≦ 50 を満たす．各 ai,j は格子 (i, j) の状態を表す 1 つの半角文字であり，「B」は黒い杭が打たれていることを，「W」は白い杭が打たれていることを，「.」（ピリオド）はいずれの杭も打たれていないことをそれぞれ示す．

w = h = 0 は入力の終端を表しており，データセットには含まれない．

Output

各データセットについて，黒い杭が囲んだ土地の大きさ，および白い杭が囲んだ土地の大きさを 1 つの空白で区切って 1 行に出力しなさい．

Sample Input

10 10
.....W....
....W.W...
...W...W..
....W...W.
.....W...W
......W.W.
BBB....W..
..B..BBBBB
..B..B....
..B..B..W.
5 3
...B.
...BB
.....
1 1
.
0 0

Output for the Sample Input

6 21
12 0
0 0


function syukusyou(yx){
   var cnt=0;
   yx=yx.filter(v=>{
      var flag = v.every(val=> val==".");
      if(!flag){
         cnt=0;
         return true;
      }else if(flag && cnt==0){
         cnt++;
         return true;
      }else {
         return false;
      }
   });
   return yx;
}

function kaiten(yx){
   return  yx[0].map((a, i) => yx.map(b => b[i]));
}

function saikiY(y,x,d){
   if(yx[y][x] != ".")return yx[y][x];
   else if(y+d!=-1 && y+d!=h)return saikiY(y+d,x,d);
   else return ".";
}

function saikiX(y,x,d){
   if(yx[y][x]!=".")return yx[y][x];
   else if(x+d!=-1 && x+d!=w)return saikiX(y,x+d,d);
   else return ".";
}

function kesu(y,x){
   var arr= [saikiY(y,x,1),saikiY(y,x,-1),saikiX(y,x,1),saikiX(y,x,-1)];
   var a = arr.filter(function (x, i, self) {
      if(x==".")return false;
      return self.indexOf(x) === i && i !== self.lastIndexOf(x);
   });
   a.forEach(v=> replaceFn(y,x,v));
   return a.length*2;
}

function replaceFn(y,x,s){
   for(var i=0;i<h;i++){
      if(yx[i][x]==s)yx[i][x]=".";
   }
   for(var i=0;i<w;i++){
      if(yx[y][i]==s)yx[y][i]=".";
   }
}

var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr=input.trim().split("\n");
var yx = arr.slice(1).map(v=> v.split(""));
yx=syukusyou(yx);
yx=kaiten(yx);
yx=syukusyou(yx);
var h=yx.length;
var w=yx[0].length;
var sum=0;
while(true){
   var flag=false;
   yx.forEach((ary,y)=>{
      ary.forEach((v,x)=>{
         if(v=="."){
            var add = kesu(y,x);
            if(add != 0)flag=true;
            sum += add;
         }
      });
   });
   if(!flag)break;
}
console.log(sum);

J: Tiles are Colorful

ICPC で良い成績を収めるには修行が欠かせない．うさぎは ICPC で勝ちたいので，今日も修行をすることにした．

今日の修行は，流行りのパズルをすばやく解いて，瞬発力を鍛えようというものである．今日挑戦するのは，色とりどりのタイルが並んでいてそれらを上手く消していくパズルだ

初期状態では，グリッド上のいくつかのマスにタイルが置かれている．各タイルには色がついている．プレイヤーはゲーム開始後，以下の手順で示される操作を何回も行うことができる．

タイルが置かれていないマスを 1 つ選択し，そのマスを叩く．

叩いたマスから上に順に辿っていき，タイルが置かれているマスに至ったところでそのタイルに着目する．タイルが置かれているマスがないまま盤面の端に辿り着いたら何にも着目しない．

同様の操作を叩いたマスから下・左・右方向に対して行う．最大 4 枚のタイルが着目されることになる．

着目したタイルの中で同じ色のものがあれば，それらのタイルを盤面から取り除く．同じ色のタイルの組が 2 組あれば，それら両方を取り除く．

タイルを取り除いた枚数と同じ値の得点が入る．

着目をやめる．

たとえば，以下のような状況を考えよう．タイルが置かれていないマスはピリオドで，タイルの色はアルファベット大文字で表されている．

..A.......
.......B..
..........
..B.......
..A.CC....

ここで上から 2 行目，左から 3 列目のマスを叩く操作を考える．着目することになるタイルは A , B , B の 3 枚であるから，B の 2 枚が消えて盤面は以下のようになり，2 点を得る．

..A.......
..........
..........
..........
..A.CC....

このパズルはゆっくりしていると時間切れになってしまい，盤面の一部が見えなくなりどのくらい修行が足りなかったのかがわからなくなってしまう．
各色のタイルは 2 枚ずつ置かれているが，それらをすべて消せるとは限らないので，予めプログラムに得点の最大値を計算させておきたい．

Input

M N
C1,1C1,2...C1,N
C2,1C2,2...C2,N
...
CM,1CM,2...CM,N

整数 M, N は盤が 縦 M × 横 N のマス目であることを表す．Ci, j はアルファベット大文字またはピリオド ( . ) であり，上から i 行目，左から j 列目のマスについて，アルファベット大文字の場合は置かれているタイルの色を表し，ピリオドの場合はこのマスにタイルが置かれていないことを表す．

1 ≤ M ≤ 500，1 ≤ N ≤ 500 を満たす．各アルファベット大文字は入力中に 0 個または 2 個現れる．

Output

得点の最大値を 1 行に出力せよ．

Sample Input 1

5 10
..A.......
.......B..
..........
..B.......
..A.CC....

Sample Output 1

4

Sample Input 2

3 3
ABC
D.D
CBA

Sample Output 2

4

Sample Input 3

5 7
NUTUBOR
QT.SZRQ
SANAGIP
LMDGZBM
KLKIODP

Sample Output 3

34


var dx = [1,1,1,0,0,-1,-1,-1];
var dy = [1,0,-1,1,-1,1,0,-1];

function judge(s,turn,ii,jj){
    var sum = 0;
    for(var i = 0;i < 8;i++){
        var su = 0;
        var x = jj + dx[i],y = ii + dy[i];
        while(x > 0 && x < 9 && y > 0 && y < 9){
            if(s[y][x] == turn){sum += su;break;}
            else if(s[y][x] == turn * (-1))su++;
            else
                break;
            x += dx[i];y += dy[i];
        }
    }
    return sum;
}

function put(s,turn,ii,jj){
    for(var i = 0;i < 8;i++){
        var su = 0;
        var x = jj + dx[i],y = ii + dy[i];
        var flag = false;
        while(x > 0 && x < 9 && y > 0 && y < 9){
            if(s[y][x] == turn){flag = true;break;}
            else if(s[y][x] == turn * (-1))su++;
            else
                break;
            x += dx[i];y += dy[i];
        }
        if(flag){
            var x = jj + dx[i],y = ii + dy[i];
            for(var j = 0;j < su;j++){
                s[y][x] = turn;
                x += dx[i];y += dy[i];
            }
        }
    }
    s[ii][jj] = turn;
}

function Main(input){
    input = input.split("\n");
    var s = [];
    for(var i = 1;i <= 8;i++){
        s[i] = [];
    }

    var fin = 0;

    for(var i = 1;i <= 8;i++){
        for(var j = 1;j <= 8;j++){
            if(input[i - 1][j - 1] == 'o'){
                fin++;
                s[i][j] = 1;
            }
            else if (input[i - 1][j - 1] == 'x'){
                fin++;
                s[i][j] = -1;
            }
            else
                s[i][j] = 0;
        }
    }

    var turn = 1;var aaa = false;

    while(fin < 64){
        var maxi = 0,imax = -1,jmax = -1;
        if(turn == 1){
            for(var i = 1;i <= 8;i++){
                for(var j = 1;j <= 8;j++){
                    if(s[i][j] == 0){
                        var a = judge(s,turn,i,j);
                        if(a > maxi){
                            maxi = a;imax = i;jmax = j;
                        }
                    }
                }
            }
        }else{
            for(var i = 1;i <= 8;i++){
                for(var j = 1;j <= 8;j++){
                    if(s[i][j] == 0){
                        var a = judge(s,turn,i,j);
                        if(a >= maxi){
                            maxi = a;imax = i;jmax = j;
                        }
                    }
                }
            }
        }

        if(maxi > 0){
            aaa = false;
            fin++;
            put(s,turn,imax,jmax);
        }else{
            if(aaa)
                break;
            aaa = true;
        }
        turn *= (-1);
    }

    for(var i = 1;i <= 8;i++){
        var ans = "";
        for(var j = 1;j <= 8;j++){
            if(s[i][j] == 1)
                ans += 'o';
            else if(s[i][j] == (-1))
                ans += 'x';
            else
                ans += '.';
        }
        console.log(ans);
    }
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));

問題文

お菓子の魔女 CHARLOTTE は巴マミとクッキーゲームを楽しんでいる．クッキーゲームは 8\times 8 の格子状に区切られたテーブルクロスの上にチーズクッキーとチョコレートクッキーを置いて行われる．各格子には高々 1 個のチョコレートクッキーまたはチーズクッキーしか置くことはできない．

お菓子の魔女はチーズクッキーを，巴マミはチョコレートクッキーを交互に置いてゲームを行う．自分のクッキーを置いたあと，そのクッキーから上下左右斜めの各 8 方向について，置くクッキーとすでに置いていた自分のクッキーの間に相手のクッキーのみが直線に並んでいた場合に，その挟まれた相手のクッキーのすべてが自分のクッキーで置き換えられる．クッキーゲームのプレイヤーは自分のターンが回ってきた時，1 つ自分のクッキーを置くことができる．ただし，相手のクッキーを少なくとも 1 つ以上自分のクッキーに置き換えられなければならない．そのような置き場がない場合，自分のターンをパスをしなければならない．

お菓子の魔女も巴マミも考えるのが少々苦手である．そこで，回ってきたターン毎にそのターンの中で置き換えられるクッキーの数を最大化することを考えることにした．巴マミのターンのときに置き換えられるクッキーの数を最大にするようなクッキーを置く場所の候補が複数ある場合は，より上の場所を，それでも複数ある場合はより左の場所を選択することにした．また同様に，お菓子の魔女のターンのときに候補が複数ある場合はより下の場所を，それでも複数ある場合はより右の場所を選択することにした．

テーブルクロスに置かれたクッキーの状態が与えられるので，巴マミからはじめ，彼女たちがそこからクッキーゲームを行い，共に新たなクッキーが置けなくなるまでゲームを続けた時のテーブルクロスの上に置かれたクッキーの状態を求めよ．

入力形式

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

s_{11} s_{12} ... s_{18}\\
s_{21} s_{22} ... s_{28}\\
...\\
s_{81} s_{82} ... s_{88}\\

s_{ij} はテーブルクロスに置かれたクッキーの初期状態を表す文字で，上から i 行目，左から j 列目の格子の状態を表す．チョコレートクッキーが置かれているときs_{ij}は 'o' であり，チーズクッキーが置かれているときは 'x', 何も置かれていないときは '.' となる．

出力形式

クッキーゲームが行われた後のテーブルクロスの上に置かれたクッキーの状態を，入力形式と同じ形式で出力せよ．

制約

s_{ij} は 'o', 'x', '.' のいずれかである．

入出力例

入力例 1

ooox....
.x......
ooo.....
........
........
........
........
........

出力例1

ooooo...
.o......
ooo.....
...o....
....o...
........
........
........

入力例 2

........
........
........
...ox...
...xo...
........
........
........

出力例 2

xxxxxxxx
xxxooxxx
xxxxooxx
xxxxxxxx
ooxxooox
ooxoooox
oxooooox
ooooooox

入力例 3

........
........
..ooo...
..oxo...
..ooo...
........
........
........

出力例 3

........
........
..ooo...
..ooo...
..ooo...
.....o..
......o.
........

Problem Setter: Flat35


function Main(input){
    input = input.split("\n");
    var k = 0;
    while(1){
        input[k] = input[k].split(" ");
        var d = parseInt(input[k][0],10);
        var e = parseInt(input[k++][1],10);
        if(d == 0 && e == 0)
            break;

        var min = 100000000;
        for(var i = 0;i <= d;i++){
            if(Math.abs(e - Math.sqrt(i * i + (d - i) * (d - i))) < min)
                min = Math.abs(e - Math.sqrt(i * i + (d - i) * (d - i)));
        }
        console.log(min);
    }
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));

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

Koto Municipal Subway

Koto市営地下鉄

Koto市は，下図のように，道路が碁盤の目状である有名な街である．
南北に伸びる道と東西に伸びる道は，それぞれ1kmの間隔で並んでいる．
Koto市の最も南西の交差点にあるKoto駅を (0, 0) として，そこから東に x km，北に y km 進んだ位置を (x, y) と記すこととする (0 ≤ x, y である)．

5年後に開かれるオリンピックにより観光客が増大することを見越して，市はKoto駅を始発駅とする新しい地下鉄の路線を建設することを決めた．
現在，Koto駅の次の駅として新しく建設されるShin-Koto駅までのレールを敷く計画を立てている．
レールは，Koto駅からShin-Koto駅に向かってまっすぐ敷く．
従って，Shin-Koto駅の場所を (x, y) としたとき，レールの長さは， √(x2 + y2) である．
レールを敷くための費用は，敷いたレールの長さ分だけ必要になる．
レールの長さが1.5kmのように小数であっても，費用も同じように1.5必要となる．

Shin-Koto駅の場所 (x, y) はまだ決定しておらず，以下の条件を満たす場所にする予定である．

交差点である．つまり， x と y がそれぞれ整数である．

Koto駅から道路に沿って歩いた最短距離が，ちょうど D である．つまり， x + y = D を満たす．

上の2つの条件を満たす中で，市が定めるレールの予算 E とレールの費用とのずれ | √(x2 + y2) - E | が最小となるようにShin-Koto駅の場所を選ぶ．
ここで |A| は， A の絶対値を表す．
あなたの仕事は，上記のようにShin-Koto駅を建設したときの，レールを敷くための費用と予算とのずれを出力するプログラムを作成することである．

Input

入力は，複数のデータセットから構成され，1つの入力に含まれるデータセットの数は100以下である． 各データセットの形式は次の通りである．

D E

D (1 ≤ D ≤ 100)は，Koto駅からShin-Koto駅まで道路に沿って歩いたときの最短距離を表す整数である．
E (1 ≤ E ≤ 100)は，レール建設のための予算を表す整数である．

入力の終わりは，空白で区切られた2つのゼロからなる行によって示される．

Output

各データセットに対して，問題の条件を満たすようにレールを敷いたときの費用と予算とのずれを1行で出力せよ．
答えには 10-3 を越える絶対誤差があってはならない．
各行の終わりに改行を出力しなかった場合や，不必要な文字を出力した場合，誤答と判断されてしまうため，注意すること．

Sample Input

2 1
7 5
7 6
7 7
76 5
8 41
0 0

Output for Sample Input

0.4142135624
0
0.0827625303
0
48.7401153702
33

Hint

1つ目のデータセットでは，下図のように，Koto駅から道路に沿って2km進んだ交差点がShin-Koto駅を建設する場所の候補となる．

各交差点にShin-Koto駅を建設した場合の，レールを敷くための費用と予算1とのずれは次のようになる．

(2, 0) ： | √(22 + 02) - 1 | = 1.0

(1, 1) ： | √(12 + 12) - 1 | = 0.4142135623...

(0, 2) ： | √(02 + 22) - 1 | = 1.0

よって，費用と予算とのずれが最小になるのは， (1, 1) に建設した場合となる．


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr = input.trim().split("\n");
var n = arr.shift() - 0;
var a = 0;
for (var i = 0; i < n; i++) {
   (arr[i] == "A") ? a++ : a--;
   if (a < 0) break;
}
console.log((a == 0) ? "YES" : "NO");

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

A - 阿吽の呼吸

Problem Statement

時は進んで 2060 年，共に 70 歳を迎える前田さんと後藤さんは長い付き合いの友人であり，大学時代にACM-ICPCで共に戦った仲間でもある．

二人は今でもよく一緒にお茶を飲みつつ，競技プログラミングの話で盛り上がっている．

二人で一緒にお茶を飲む時，前田さんが 1 回Aと言うと，その発言の後に後藤さんがちょうど 1 回Unと返事をする習慣がいつのまにか出来た．

しかし最近後藤さんは物忘れや勘違いをすることが多く，前田さんがAと言っても，後藤さんはたまにUnの返事を忘れたり，余計に返事をしたりする．

ついこの間も前田さんと後藤さんはお茶を飲みながら，二人のお気に入りのデータ構造について話し込んでいたようだ．

この時の会話の中から，Aで表される前田さんの発言と，Unで表される後藤さんの返事のみからなる記録が時系列で与えられたとき，後藤さんが習慣通りに反応したとみなすことが出来るかチェックしてほしい．

注意点として，前田さんの発言に対し，後藤さんの返事が多少遅れても，後藤さんは習慣通りに反応したとみなせる場合がある，ということが挙げられる．
例えば，前田さんが2回連続してAと言った後，後藤さんが 2 回連続してUnと返事をして会話が終了した場合は，後藤さんが習慣通りの返事をしたとみなされる (Sample Input 2 参照)．

また，会話が終了した時点で，前田さんがAと言った回数と，後藤さんがUnと返事した回数が一致しても，後藤さんが習慣通りに返事をしたとはみなされない場合もあるので注意すること．
例えば，前田さんが1回Aと言った後，後藤さんが 2 回連続してUnと返事し，その後で前田さんが 1 回Aと言って会話が終了した場合は，後藤さんが習慣通りの返事をしたとはみなされない (Sample Input 3 参照)．

Input

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

$N$

$S_1$

$S_2$

$…$

$S_N$

最初の行はひとつの整数からなる．
$N$ は，記録に含まれる前田さんがAと発言した回数と後藤さんがUnと返事した回数の合計を表し，$1 \leq N \leq 100$ を満たす．
その後 $N$ 行に，文字列 $S_i$ が続き，各 $S_i (1 \leq i \leq N)$ はAかUnのどちらかに一致する．ここでAは前田さんの発言，Unは後藤さんの返事を表す．
$i$ の小さい順に $S_i$ が記録されたものとする．
前田さんと後藤さんが同時に発言することは無かったとする．

Output

後藤さんが習慣通りに反応したとみなすことが出来ればYES，出来なければNOを1行で出力すること．

Sample Input 1

4
A
Un
A
Un

Output for the Sample Input 1

YES

Sample Input 2

4
A
A
Un
Un

Output for the Sample Input 2

YES

Sample Input 3

4
A
Un
Un
A

Output for the Sample Input 3

NO

Sample Input 4

1
Un

Output for the Sample Input 4

NO


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
if(input=="ani")console.log("square1001");
else console.log("e869120");

B: 双子 (Twins)

とある双子は、自分たちのどちらが兄でどちらが弟かがあまり知られていないことに腹を立てた。

"ani" と入力されたら "square1001"、"otouto" と入力されたら "e869120" と出力するプログラムを作りなさい。

入力

入力として "ani" または "otouto" という文字列のどちらかが与えられます。

出力

"e869120" または "square1001" を、問題文の通りに出力してください。最後の改行を忘れないようにしましょう。

入力例1

ani

出力例1

square1001

入力例2

otouto

出力例2

e869120


const line = require('fs').readFileSync('/dev/stdin', 'utf-8').split('\n');

const fib = n => {
    const memo = [];
    const helper = x => {
        if (x <= 1) return 1;
        if (memo[x] !== undefined) return memo[x];
        memo[x] = helper(x-1) + helper(x-2);
        return memo[x];
    }

    return helper(n);
};

console.log(fib(44));

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

Fibonacci Number

Write a program which prints $n$-th fibonacci number for a given integer $n$. The $n$-th fibonacci number is defined by the following recursive formula:

\begin{equation*}
fib(n)= \left \{
\begin{array}{ll}
1　 & (n = 0) \\
1　 & (n = 1) \\
fib(n - 1) + fib(n - 2) & \\
\end{array}
\right.
\end{equation*}

Input

An integer $n$ is given.

output

Print the $n$-th fibonacci number in a line.

Constraints

$0 \leq n \leq 44$

Sample Input 1

3

Sample Output 1

3


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

const inputs = input.trim().split('\n');
const n = Number(inputs.shift());
const adj = inputs.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 v = adj[i].slice(2);

  for (let j = 0; j < k; j++) {
    G[u - 1][v[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), () => []);
  lines.forEach((l, i) => l.split(' ').splice(2).forEach(e => adjLists[i].push(e-1)));

  const d = [], f = [];
  dfs(adjLists, d, f);
  for (let i = 0; i < n; i++) {
    console.log(i + 1, d[i], f[i]);
  }
})();

function dfs(adjLists, d, f) {
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const size = adjLists.length;
  const color = Array.from(adjLists, () => WHITE);

  let time = 0;
  function visit(u) {
    color[u] = GRAY;
    d[u] = ++time;
    adjLists[u].forEach(v => {
      if (color[v] === WHITE) {
        visit(v);
      }
    });
    color[u] = BLACK;
    f[u] = ++time;
  }
  adjLists.forEach((u, i) => {
    if (color[i] === WHITE) visit(i);
  });
}

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

Depth First Search

Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.

This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.

DFS timestamps each vertex as follows:

$d[v]$ records when $v$ is first discovered.

$f[v]$ records when the search finishes examining $v$’s adjacency list.

Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:

$G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.

IDs in the adjacency list are arranged in ascending order.

The program should report the discover time and the finish time for each vertex.

When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.

The timestamp starts with 1.

Input

In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $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$.

Output

For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

Sample Input 1

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

Sample Output 1

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

Sample Input 2

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

Sample Output 2

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

This is example for Sample Input 2 (discover/finish)

Reference

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


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

  const adjLists = Array.from(Array(n), () => []);
  lines.forEach((l, i) => l.split(' ').splice(2).forEach(e => adjLists[i].push(e-1)));

  const d = [], f = [];
  dfs(adjLists, d, f);
  for (let i = 0; i < n; i++) {
    console.log(`${i + 1} ${d[i]} ${f[i]}`);
  }
})();

function dfs(adjLists, d, f) {
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const size = adjLists.length;
  const color = Array.from(adjLists, () => WHITE);

  let time = 0;
  function visit(u) {
    color[u] = GRAY;
    d[u] = ++time;
    adjLists[u].forEach(v => {
      if (color[v] === WHITE) {
        visit(v);
      }
    });
    color[u] = BLACK;
    f[u] = ++time;
  }
  adjLists.forEach((e, u) => {
    if (color[u] === WHITE) visit(u);
  });
}


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

const inputs = input.trim().split('\n');
const n = Number(inputs.shift());
const adj = inputs.map((s) => s.split(' ').map(Number));

class Time {
  constructor(now = 0) {
    this.now = now;
  }
  getNow() {
    return ++this.now;
  }
}
const time = new Time();

class Node {
  constructor(id) {
    this.id = id;
    this.children = [];
  }
  add(node) {
    this.children.push(node);
  }
  isVisited() {
    return !!this.start;
  }
  calc() {
    this.start = time.getNow();
    this.children.sort((a, b) => a.id > b.id);
    this.children.forEach(child => child.isVisited() || child.calc());
    this.end = time.getNow();
  }
  toString() {
    return [this.id, this.start, this.end].join(' ');
  }
}

class Tree {
  constructor() {
    this.map = new Map();
  }
  getNode(id) {
    this.map.has(id) || this.map.set(id, new Node(id));
    return this.map.get(id);
  }
  calc() {
    for (let i = 1; i <= this.map.size; i++) {
      const node = this.map.get(i);
      node.isVisited() || node.calc();
    }
  }
  print() {
    for (let i = 1; i <= this.map.size; i++) {
      const node = this.map.get(i);
      console.log(node.toString());
    }
  }
}

const tree = new Tree();
adj.forEach(([u, k, ...vk]) => {
  const parent = tree.getNode(u);
  vk.forEach(v => {
    const node = tree.getNode(v);
    parent.add(node);
  });
});

tree.calc();
tree.print();


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

  const adjLists = Array.from(Array(n), () => []);
  lines.forEach((l, i) => l.split(' ').splice(2).forEach(e => adjLists[i].push(e-1)));

  const d = [], f = [];
  dfs(adjLists, d, f);
  str = '';
  for (let i = 0; i < n; i++) {
    str += `${i + 1} ${d[i]} ${f[i]}\n`;
  }
  console.log(str);
})();

function dfs(adjLists, d, f) {
  const WHITE = 0, GRAY = 1, BLACK = 2;
  const size = adjLists.length;
  const color = Array.from(adjLists, () => WHITE);

  let time = 0;
  function visit(u) {
    color[u] = GRAY;
    d[u] = ++time;
    adjLists[u].forEach(v => {
      if (color[v] === WHITE) {
        visit(v);
      }
    });
    color[u] = BLACK;
    f[u] = ++time;
  }
  adjLists.forEach((e, u) => {
    if (color[u] === WHITE) visit(u);
  });
}

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.


//config = { input: 'tmp', newline: '\r\n' }; // win
config = { input: '/dev/stdin', newline: '\n' }; // linux

line = require('fs').readFileSync(config.input, 'ascii')
  .trim()
  .split(config.newline)
  .map(function (line) { return line.split(' ').map(Number); });

n = line[0][0];
m = line[0][1];
q = line[m+1][0];

adj = new Array(n+1);
for (i = 0; i <= n; i++) adj[i] = null;

for (i = 1; i <= m; i++) {
  min = Math.min(line[i][0], line[i][1]);
  max = Math.max(line[i][0], line[i][1]);
  while (adj[min] !== null) min = adj[min];
  adj[max] = min;
}

for (i = m+2; i < (m+2) + q; i++) {
  q0 = line[i][0];
  q1 = line[i][1];
  while (adj[q0] !== null) q0 = adj[q0];
  while (adj[q1] !== null) q1 = adj[q1];
  console.log((q0 === q1) ? 'yes' : 'no');
}

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


//config = { input: 'tmp', newline: '\r\n' }; // win
config = { input: '/dev/stdin', newline: '\n' }; // linux

line = require('fs').readFileSync(config.input, 'ascii')
  .split(config.newline);
line[0] = line[0].split(' ').map(Number);
H = line[0][0];
W = line[0][1];
field = line.slice(1, 1+H);
line[1+H] = line[1+H].split(' ').map(Number);
R = line[1+H][0];
C = line[1+H][1];
pat = line.slice(1+H+1, 1+H+1+R);

if (H < R || W < C) process.exit();

mem = new Array(H-R+1);
for (i = 0; i <= H-R; i++) {
  mem[i] = new Array(W-C+1);
  for (j = 0; j <= W-C; j++) mem[i][j] = 0;
}

match_count = new Array(W-C+1);
match = new Array(W-C+1);
for (i = 0; i <= W-C; i++) {
  match_count[i] = 0;
  match[i] = false;
}

function string_match(str1, str2, W, C) {
  var i, j, k;
  for (i in match_count) match_count[i] = 0;
  for (i = 0; i <= W-C; i++) {
    for (j = 0; j < C; j++) {
      if (str1[i+j] === str2[j]) match_count[i]++;
    }
  }
  for (i in match) match[i] = (match_count[i] === C);
}

for (i = 0; i < H; i++) {
  for (j = Math.max(0, i-H+R); j < R && j <= i; j++) {
    string_match(field[i], pat[j], W, C);
    for (k in match) {
      if (!match[k]) continue;
      mem[i-j][k]++;
    }
  }
}

for (i in mem)
  for (j in mem[i])
    if (mem[i][j] === R) console.log('%s %s', i, j);

Pattern Search

Find places where a R × C pattern is found within a H × W region. Print top-left coordinates (i, j) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and (H-1, W-1) respectively.

Input

In the first line, two integers H and W are given. In the following H lines, i-th lines of the region are given.

In the next line, two integers R and C are given. In the following R lines, i-th lines of the pattern are given.

output

For each sub-region found, print a coordinate i and j separated by a space character in a line. Print the coordinates in ascending order of the row numbers (i), or the column numbers (j) in case of a tie.

Constraints

1 ≤ H, W ≤ 1000

1 ≤ R, C ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

4 5
00010
00101
00010
00100
3 2
10
01
10

Sample Output 1

0 3
1 2


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var arr = input.trim().split("\n");
var str=arr.shift();
var n = arr.shift()-0;
var ans = "";
for(var i=0;i<n;i++){
   console.log(str.includes(arr[i])?1:0);
}

String Search

Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i.

Input

In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively.

Output

For each question, print 1 if the text includes P_i, or print 0 otherwise.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P_i ≤ 1000

1 ≤ Q ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
4
aa
ba
bb
xyz

Sample Output 1

1
1
0
0


(function(input) {
    var p = input.split(' ').map(Number);
    var x = p.shift();
    var y = p.shift();
    console.log(greatestCommonDevisor(x, y));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

function greatestCommonDevisor(x, y) {
    return Math.max.apply(null, commonDevisor(x, y));
}

function commonDevisor(x, y) {
    if (x > y) {
        x = x % y;
    } else if (x < y) {
        var tmp = y;
        y = x;
        x = tmp % x;
    }
    var a = [];
    for (var i = 1; i <= x; i++) {
        if (x % i === 0 && y % i === 0) {
            a.push(i);
        }
    }
    return a;
}

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');
var Arr=(input.trim()).split("\n").map(Number);
Arr.shift();
var max=Arr.reduce(function(a,b){return Math.max(a,b);});
Arr.sort(function(a,b){a-b;});
var max=Arr[Arr.length-1];
var arr=[2];
for(var i=3;i<=max;i++){
   var a=true;
   for(var j=0;j<arr.length;j++){
      if(i%arr[j]==0){a=false;break;}
   }
   if(a)arr.push(i);
   i++;
}

var num=0;
var f=0;
for(var i=0;i<Arr.length;i++){
   var index=arr.indexOf(Arr[i],f);
   if(index!=-1){
      f=index;
      num++;
   }
}
console.log(num);

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


(function(input) {
    var p = input.split('\n').map(Number);
    var n = p.shift();
    var a = p.slice(0, n);
    var pns = primeNumbersIn(a);
    console.log(pns.length);
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

function greatestCommonDevisor(x, y) {
    return Math.max.apply(null, commonDevisors(x, y));
}

function commonDevisors(x, y) {
    if (x > y) {
        x = x % y;
    } else if (x < y) {
        var tmp = y;
        y = x;
        x = tmp % x;
    }
    var a = [];
    var ds = divisors(x);
    for (var i = 0; i < ds.length ; i++) {
        var d = ds[i];
        if (y % d === 0) {
            a.push(i);
        }
    }
    return a;
}

function divisors(x) {
    var a = [];
    for (var i = 1; i <= x; i++) {
        if (x % i === 0) {
            a.push(i);
        }
    }
    return a;
}

function isPrimeNumber(x) {
    if (x < 2) {
        return false;
    }
    for (var i = 2; i < x; i++) {
        if (x % i === 0) {
            return false;
        }
    }
    return true;
}

function inArray(needle, heystack) {
    return heystack.indexOf(needle) !== -1;
}

function primeNumbersIn(a) {
    a = a.sort(function(a, b) {
        return a - b;
    });
    var t = 0;
    var n = a[t];
    do {
        for (var i = n * 2; i <= Math.max.apply(null, a); i += n) {
            var index = a.indexOf(i);
            if (index > -1) {
                a = a.slice(0, index).concat(a.slice(index + 1, a.length));
            }
        }
        n = a[++t];
    } while (n < Math.sqrt(Math.max.apply(null, a)))
    return a;
}


(() => {

    var lines = [];

    require('readline').createInterface({
        input: process.stdin,
    }).on('line', (line) => {
        lines.push(Number(line));
    });

    process.stdin.on("end", () => {
        console.log(lines.filter(isPrime).length);
    });

    const isPrime = function(x){
        if(x == 2){
            return true;
        }

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

        const sqrt_x = Math.sqrt(x);
        for(let i = 3; i <= sqrt_x; i+=2){
            if(x % i === 0){
                return false;
            }
        }
        return true;
    }

})();


function main() {
  var n = input[0];
  var maxv = -1000000000;
  var minv = input[1];
  for (j = 2; j <= n; j++) {
    maxv = Math.max(maxv, input[j] - minv);
    minv = Math.min(minv, input[j]);
  }
  console.log(maxv);
}

var input = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
  input += chunk;
});
process.stdin.on('end', function() {
  input = input.split('\n');
  input.pop();
  main();
});

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 getMaxv = arr => {
  let j = 0;
  let maxv = -Infinity;
  let min = Infinity;
  for (j = 0; j < arr.length; j++) {
    maxv = Math.max(maxv, arr[j] - min);
    min = Math.min(min, arr[j]);
  }
  console.log(maxv);
};

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 !== "";
  // });

  const lines = "7 3 2 4 1 5 3 6".split(" ");
  getMaxv(lines);
});


let content = '';
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', buf => {
  content += buf;
});

process.stdin.on('end', () => {
  const [, ...nums] = content
    .trim()
    .split('\n')
    .map(n => +n);

  let max = null;
  let min = nums[0];
  for (let i = 1; i < nums.length; i++) {
    const bNum = nums[i];
    min = min > nums[i - 1] ? nums[i - 1] : min;
    const d = bNum - min;
    if (max === null || d > max) {
      max = d;
    }
  }

  console.log(max);
});


'use strict';

const main = input => {
  input = input.split('\n');
  const N = Number(input[0]);
  const A = input[1]
    .trim()
    .split(' ')
    .map(Number);
  bubbleSort(A, N);
};

function bubbleSort(A, N) {
  let flag = true;
  let count = 0;
  while (flag) {
    flag = false;
    let i = 0;
    for (let j = N - 1; j >= i + 1; --j) {
      if (A[j - 1] > A[j]) {
        const tmp = A[j];
        A[j] = A[j - 1];
        A[j - 1] = tmp;
        flag = true;
        ++count;
      }
    }
    ++i;
  }
  console.log(A.join(' '));
  console.log(count);
}

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

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


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

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

const solve = arr => {
    const helper = (xs, stack) => {
        if (xs.length === 0) return stack[0];
        const hd = xs[0];
        const tl = xs.slice(1);
        if (hd === '+') {
            const snd = stack.pop();
            const fst = stack.pop();
            stack.push(fst + snd);
        } else if (hd === '-') {
            const snd = stack.pop();
            const fst = stack.pop();
            stack.push(fst - snd);
        } else if (hd === '*') {
            const snd = stack.pop();
            const fst = stack.pop();
            stack.push(fst * snd);
        } else {
            stack.push(parseFloat(hd));
        }
        return helper(tl, stack);
    };

    return helper(arr, []);
};

console.log(solve(line[0].split(' ')));

Reverse Polish notation is a notation where every operator follows all of its operands. For example, an expression (1+2)*(5+4) in the conventional Polish notation can be represented as 1 2 + 5 4 + * in the Reverse Polish notation. One of advantages of the Reverse Polish notation is that it is parenthesis-free.

Write a program which reads an expression in the Reverse Polish notation and prints the computational result.

An expression in the Reverse Polish notation is calculated using a stack. To evaluate the expression, the program should read symbols in order. If the symbol is an operand, the corresponding value should be pushed into the stack. On the other hand, if the symbols is an operator, the program should pop two elements from the stack, perform the corresponding operations, then push the result in to the stack. The program should repeat this operations.

Input

An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character.

You can assume that +, - and * are given as the operator and an operand is a positive integer less than 106

Output

Print the computational result in a line.

Constraints

2 ≤ the number of operands in the expression ≤ 100

1 ≤ the number of operators in the expression ≤ 99

-1 × 109 ≤ values in the stack ≤ 109

Sample Input 1

1 2 +

Sample Output 1

3

Sample Input 2

1 2 + 3 4 - *

Sample Output 2

-3

Notes

Template in C


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var Arr=(input.trim()).split("\n");
var t=(Arr[0].split(" "))[1]-0;
Arr.shift();
var T=0;
var i=0;
while(Arr.length!=0){
   var arr=Arr[0].split(" ");
   Arr.shift();
   var a=arr[0];
   var b=arr[1]-0;
   if(b-t<=0){
      console.log(a+" "+(T+b));
      T+=b;
   }else{
      Arr.push(a+" "+(b-t));
      T+=t;
   }
}

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


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

var line = lines.shift();
var tmp = line.split(' ');
var n = tmp[0];
var q = tmp[1] - 0;

var queue = [];
lines.forEach(function(l) {
	tmp = l.split(' ');
	queue.push({name: tmp[0], time: tmp[1] - 0});
});

var passed = 0;
while (queue.length > 0) {
	var process = queue.shift();

	if (process.time <= q) {
		passed += process.time;
		console.log(process.name + ' ' + passed);
	} else {
		passed += q;
		process.time -= q;
		queue.push(process);
	}
}


function DoublyLinkedList() {
    this.length = 0;
    this.head = null;
    this.tail = null;
}
DoublyLinkedList.prototype={
    add: function(value){
        var node={value:value,next:null,previous:null,}
        if(this.length==0){this.head=node;this.tail=node;}
        else {this.tail.next=node;node.previous=this.tail;this.tail=node;}
        this.length++;
    },
    insert: function(value){
        var node={value:value,next:null,previous:null,}
        if(this.length==0){this.head=node;this.tail=node;}
        else{this.head.previous=node;node.next=this.head;this.head=node;}
        this.length++;
    },
    getNode: function(index){
        var node=this.head;
        var i=0;
        while(i++<index){node=node.next;}
        return node;
    },
    remove: function(index){
        var node=this.head;
        var i=0;
        if(index==0){
            this.head=node.next;
            if(this.head==null){this.tail=null;}
            else{this.head.previous=null;}
        }
        else if(index==this.length-1){
            node=this.tail;
            this.tail=node.previous;
            this.tail.next=null;
        }
        else{
            while(i++<index){node=node.next;}
            node.previous.next=node.next;
            node.next.previous=node.previous;
        }
        this.length--;
    },
    delete: function(value){
         for(var i=0;i<list.length;i++){
            if(list.getNode(i).value==value){list.remove(i);break;}
         }
    },
    deleteFirst: function(){
        var node=this.head;
         this.head=node.next;
         if(this.head==null){this.tail=null;}
         else{this.head.previous=null;}
         this.length--;
    },
    deleteLast: function(){
         var node=this.tail;
         this.tail=node.previous;
         this.tail.next=null;
         this.length--;
    },
    printList: function(){
         var str="";
         for(var i=0;i<list.length;i++){str+=list.getNode(i).value+" ";}
         console.log(str.slice(0,-1));
    }
};
var list = new DoublyLinkedList();

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 arr=Arr[i].split(" ");
   switch (arr[0]){
      case "insert":list.insert(arr[1]-0);break;
      case "delete":list.delete(arr[1]-0);break;
      case "deleteFirst":list.deleteFirst();break;
      case "deleteLast":list.deleteLast();break;
   }
}
list.printList();

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


function DoublyLink(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
}

function DoublyLinkedList() {
    this.first = null;
    this.last = null;
}

DoublyLinkedList.prototype.insert = function(link) {
    if (this.first) {
        this.first.prev = link;
        link.next = this.first;
        this.first = link;
        return;
    }
    this.first = link;
    this.last = link;
};

DoublyLinkedList.prototype.delete = function(link) {
    var l = this.find(link);
    if (!l) {
        return;
    }
    var prev = l.prev;
    var next = l.next;

    if (l.prev) {
        l.prev.next = l.next;
        if (!l.next) {
            this.last = l.prev;
        }
    }
    if (l.next) {
        l.next.prev = l.prev;
        if (!l.prev) {
            this.first = l.next;
        }
    }
};

DoublyLinkedList.prototype.deleteFirst = function() {
    if (!this.first) {
        return;
    }
    if (!this.first.next) {
        this.first = null;
        this.last = null;
        return;
    }
    this.first.next.prev = null;
    this.first = this.first.next;
}

DoublyLinkedList.prototype.deleteLast = function() {
    if (!this.last) {
        return;
    }
    if (!this.last.prev) {
        this.first = null;
        this.last = null;
        return;
    }
    this.last.prev.next = null;
    this.last = this.last.prev;
}

DoublyLinkedList.prototype.find = function(link) {
    var l = this.first;
    while (l) {
        if (l.value === link.value) {
            return l;
        }
        l = l.next;
    }
    return null;
};

DoublyLinkedList.prototype.list = function() {
    var a = [];
    var l = this.first;
    while (l) {
        a.push(l);
        l = l.next;
    }
    return a;
};

(function(input) {
    var p = input.split('\n');
    var n = Number(p.shift());
    var cs = p.slice(0, n);
    var l = new DoublyLinkedList();
    cs.forEach(function(e) {
        l = command(l, e);
    });
    //console.log(l.list());
    console.log(l.list().map(function(e) {
        return e.value;
    }).join(' '));
})(require('fs').readFileSync('/dev/stdin', 'utf8'));

function command(list, c) {
    var a = c.split(' ');
    var com = a.shift();
    var arg = Number(a.shift());
    switch (com) {
        case 'insert':
            var l = new DoublyLink(arg);
            list.insert(l);
            break;
        case 'delete':
            var l = new DoublyLink(arg);
            list.delete(l);
            break;
        case 'deleteFirst':
            list.deleteFirst();
            break;
        case 'deleteLast':
            list.deleteLast();
            break;
    }
    return list;
}


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

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

const data = {
    pond : [],
    stack : []
};

const results = line[0].split('').reduce((acc, x, i) => {
    if (x === '\\') {
        acc.stack.push(i);
    } else if (x === '/' && acc.stack.length > 0) {
        const k = acc.stack.pop();
        const hd = acc.pond.filter(xs => xs[0] >= k);
        const tl = acc.pond.filter(xs => xs[0] < k);

        const sum = [k, hd.map(xs => xs[1]).reduce((acc, x) => acc + x, 0) + (i - k)]
        tl.push(sum);
        acc.pond = tl;
    }

    return acc;
}, data);

console.log(results.pond.reduce((acc, x) => acc + x[1], 0));
console.log(`${results.pond.length} ${results.pond.map(x => x[1].toString()).join(' ')}`);

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

Areas on the Cross-Section Diagram

Your task is to simulate a flood damage.

For a given cross-section diagram, reports areas of flooded sections.

Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides.
For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.

Input

A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".

output

Report the areas of floods in the following format:

$A$

$k$ $L_1$ $L_2$ ... $L_k$

In the first line, print the total area $A$ of created floods.

In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.

Constraints

$1 \leq$ length of the string $\leq 20,000$

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\

Sample Output 2

35
5 4 2 1 19 9


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

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

const data = {
    pond : [],
    stack : []
};

const results = line[0].split('').reduce((acc, x, i) => {
    if (x === '\\') {
        acc.stack.push(i);
    } else if (x === '/' && acc.stack.length > 0) {
        const k = acc.stack.pop();
        const hd = acc.pond.filter(xs => xs[0] >= k);
        const tl = acc.pond.filter(xs => xs[0] < k);

        const sum = [k, hd.map(xs => xs[1]).reduce((acc, x) => acc + x, 0) + (i - k)]
        tl.push(sum);
        acc.pond = tl;
    }

    return acc;
}, data);

const sum = results.pond.reduce((acc, x) => acc + x[1], 0);
const l = results.pond.length;

console.log(sum);
console.log(`${l}${l > 0 ? ' ' + results.pond.map(x => x[1].toString()).join(' ') : ''}`);


(function main() {
  let line = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('');
  let height_list = [0];
  let current_height = 0;
  line.forEach(function(e, i){
      if (e == '\\') current_height -= 1
      else if (e == '_') current_height += 0
      else current_height += 1
      height_list.push(current_height);
  });

  // console.log(height_list.join(','));
  let sum = 0;
  let holes = [];
  for (;height_list.length > 1;) {
    let h = makeHole(height_list);
    if (h > 0) {
      sum += h;
      holes.push(h);
      // console.log(h, height_list.join(','));
    }
  }

  console.log(sum);
  console.log(holes.length && holes.length + ' ' + holes.join(' '));
})();

function makeHole(list) {
    begin = list.shift();
    if (begin <= list.reduce((a, b) => Math.max(a, b), -100000)) {
      area = 0;
      while (true) {
      if (list.length == 0 || begin <= list[0]) break;
        area += begin - list.shift();
      }
      return area;
    } else {
      return 0;
    }
}


(function() {
    'use strict';

    var fs = require('fs');
    var contents = fs.readFileSync('/dev/stdin', 'utf-8');

    var search = function(contents) {
        var S = [];
        var n = 0;
        var q = 0;
        var C = 0;
        var t = 0;

        var lines = contents.trim().split("\n");
        n = parseInt(lines[0]);
        S.length = n;
        var a = lines[1].split(" ");
        for (var i = 0; i < a.length; i++) {
            S[i] = parseInt(a[i]);
        }

        q = parseInt(lines[2]);
        var T = lines[3].split(" ");
        for (var i = 0; i < q; i++) {
            t = parseInt(T[i]);
            for (var j = 0; j < n; j++) {
                if (t == S[j]) {
                    C++;
                    break;
                }
            }
        }
        console.log(C);
    }
    search(contents);
})();

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


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 = (list, value) => {
  let l = 0;
  let r = list.length;
  while (l < r) {
    const target = Math.floor((l + r) / 2);
    if (list[target] < value) {
      l = target + 1;
    } else if (list[target] > value) {
      r = target;
    } else {
      return 1;
    }
  }
  return 0;
}

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

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


const input = require('fs').readFileSync('/dev/stdin', 'utf8');
const Arr = (input.trim()).split("\n");
const N1 = Number(Arr[0]);
const arr1 = Arr[1].split(" ").map(Number);
const arr2 = Arr[3].split(" ").map(Number);

const summing = (a, b) => a + b;
console.log(arr2.map(key => {
  let mid;
  let left = 0;
  let right = N1;
  if (key < arr1[0] || arr1[N1-1] < key) return 0;
  while (left < right) {
    mid = Math.floor((left + right) / 2);
    if (key < arr1[mid]) right = mid;
    else if (key > arr1[mid]) left = mid + 1;
    else return 1;
  }
  return 0;
}).reduce((a, b) => a + b, 0));


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

    for (var i = 0; i < m.length; i++) {
        //console.info("n = " + i);
        console.log(check(A, 0, m[i]) ? 'yes' : 'no');
        //console.info('##########');
    }

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

function check(A, i, m) {
    //console.info("i = " + i);
    //console.info("m = " + i);
    var a = A[i];
    if (m < a) {
        return false;
    }
    if (m == a) {
        return true;
    }
    if (i == A.length - 1) {
        return false;
    }
    i++;
    return check(A, i, m - a) || check(A, i, m);
}

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


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

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

const pos = (x, y) => {
    return { x : x, y : y};
};

// Pos -> Pos -> (Pos, Pos)
const div = (p1, p2, n) => {
    if (n === 0) return [];
    const th = pos((p1.x + p2.x) / 3, (p1.y + p2.y) / 3);
    const l = Math.sqrt(Math.pow(th.x, 2) + Math.pow(th.y, 2));
    const cos = Math.cos(Math.PI / 3.0);
    const sin = Math.sin(Math.PI / 3.0);

    const s = pos((2 * p1.x + p2.x) / 3, (2 * p1.y + p2.y) / 3);
    const t = pos((p1.x + 2 * p2.x) / 3, (p1.y + 2 * p2.y) / 3);
    const u = pos( (t.x - s.x) * cos - (t.y - s.y) * sin + s.x
                 , (t.x - s.x) * sin - (t.y - s.y) * cos + s.y
                 );

    return div(p1, s, n - 1)
               .concat(s)
               .concat(div(s, u, n - 1))
               .concat(u)
               .concat(div(u, t, n - 1))
               .concat(t)
               .concat(div(t, p2, n - 1));
};

const solve = (n) => {
    if (n === 0) return [pos(0.0, 0.0), pos(100.0, 0.0)];
    return [pos(0.0, 0.0), ...div(pos(0.0, 0.0), pos(100.0, 0.0), n), pos(100.0, 0.0)];
};
solve(parseInt(line[0]))
    .forEach(p => {
        console.log(p.x.toFixed(8), p.y.toFixed(8));
    });

Koch Curve

Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n.

The Koch curve is well known as a kind of fractals.

You can draw a Koch curve in the following algorithm:

Divide a given segment (p1, p2) into three equal segments.

Replace the middle segment by the two sides of an equilateral triangle (s, u, t) of the same length as the segment.

Repeat this procedure recursively for new segments (p1, s), (s, u), (u, t), (t, p2).

You should start (0, 0), (100, 0) as the first segment.

Input

An integer n is given.

Output

Print each point (x, y) of the Koch curve. Print a point in a line. You should start the point(0, 0), which is the endpoint of the first segment and end with the point (100, 0), the other endpoint so that you can draw the Koch curve as an unbroken line. Each solution should be given as a decimal with an arbitrary number of fractional digits, and with an absolute error of at most 10-4.

Constraints

0 ≤ n ≤ 6

Sample Input 1

1

Sample Output 1

0.00000000 0.00000000
33.33333333 0.00000000
50.00000000 28.86751346
66.66666667 0.00000000
100.00000000 0.00000000

Sample Input 2

2

Sample Output 2

0.00000000 0.00000000
11.11111111 0.00000000
16.66666667 9.62250449
22.22222222 0.00000000
33.33333333 0.00000000
38.88888889 9.62250449
33.33333333 19.24500897
44.44444444 19.24500897
50.00000000 28.86751346
55.55555556 19.24500897
66.66666667 19.24500897
61.11111111 9.62250449
66.66666667 0.00000000
77.77777778 0.00000000
83.33333333 9.62250449
88.88888889 0.00000000
100.00000000 0.00000000

Notes


const line = require('fs').readFileSync('/dev/stdin', 'utf-8').split('\n');

const csort = (arr) => {
    const k = arr.reduce((acc, x) => acc < x ? x : acc);
    const c = [...Array(k+1)].map(_ => 0);
    const result = [...Array(arr.length)];
    for (let i = 0; i < arr.length; i++) {
        c[arr[i]]++;
    }

    for (let i = 1; i <= k; i++) {
        c[i] += c[i-1];
    }

    for (let i = arr.length-1; i >= 0; i--) {
        result[c[arr[i]]-1] = arr[i];
        c[arr[i]]--;
    }

    return result;
};

const data = line[1].split(' ').map(Number);
console.log(csort(data).join(' '));

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


class Card {
  constructor(mark, value) {
    this.mark = String(mark);
    this.value = Number(value);
  }

  equals(other) { return this.value === other.value && this.mark === other.mark; }

  compareTo(other) {
    if (this.value === other.value) return 0;
    else if (this.value < other.value) return -1;
    else return 1;
  }

  toString() { return `${this.mark} ${this.value}` }
}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n');
  const n = Number(lines.shift());
  let arr = lines.map(r => r.split(' ')).map(c => new Card(c[0], c[1]));
  const quick_arr = Array.from(arr);

  quickSort(quick_arr, 0, n - 1);
  arr.map((e, idx) => ({val: e, idx: idx}))
      .sort((a, b) => a.val.compareTo(b.val) || a.idx - b.idx)
      .map(e => e.val);

  console.log(arr.every((card, i) => card.equals(quick_arr[i]))
      ? 'Stable' : 'Not stable');
  console.log(quick_arr.join('\n'));
})();

function quickSort(arr, p, r) {
  const partition = function(arr, p, r) {
     let x  = arr[r];
     let i = p - 1;
     for (let j = p; j < r; j++) {
       if (arr[j].compareTo(x) <= 0) {
         i++;
         [arr[i], arr[j]] = [arr[j], arr[i]];
       }
     }
     [arr[i + 1], arr[r]] = [arr[r], arr[i + 1]];
     return i + 1;
  }

  quickSort = function(arr, p, r) {
    if (p < r) {
      let q = partition(arr, p, r);
      quickSort(arr, p, q - 1);
      quickSort(arr, q + 1, r);
    }
  }
  quickSort(arr, p, r);
}

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also 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 lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

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

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


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

const inputs = input.trim().split('\n');
const n = Number(inputs.shift());
const adj = inputs.map((s) => s.split(' ').map(Number));

class Node {
  constructor(id) {
    this.id = id;
    this.parentId = -1;
    this.children = [];
  }
  add(node) {
    node.parentId = this.id;
    this.children.push(node);
  }
  isRoot() {
    return this.parentId === -1;
  }
  getType() {
    return this.isRoot() ? 'root' : this.children.length ? 'internal node' : 'leaf';
  }
  calc(depth) {
    this.depth = depth++;
    this.children.forEach(child => child.calc(depth));
  }
  toString() {
    return 'node ' + this.id + ': ' + [
      'parent = ' + this.parentId,
      'depth = ' + this.depth,
      this.getType(),
      '[' + this.children.map(child => child.id).join(', ') + ']',
    ].join(', ');
  }
}

class Tree {
  constructor() {
    this.map = new Map();
  }
  getNode(id) {
    this.map.has(id) || this.map.set(id, new Node(id));
    return this.map.get(id);
  }
  getRoot() {
    for (let i = 0; i < this.map.size; i++) {
      const node = this.map.get(i);
      if (node.isRoot()) {
        return node;
      }
    }
  }
  calc() {
    const root = this.getRoot();
    root.calc(0);
  }
  print() {
    for (let i = 0; i < this.map.size; i++) {
      const node = this.map.get(i);
      console.log(node.toString());
    }
  }
}

const tree = new Tree();
adj.forEach(([u, k, ...vk]) => {
  const parent = tree.getNode(u);
  vk.forEach(v => {
    const node = tree.getNode(v);
    parent.add(node);
  });
});

tree.calc();
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.


let inputString = '';

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
process.stdin.on('end', function() {
    const input = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    printNodes(Number(input.shift()), input);
});

const printNodes = (size, nodeInfoArr) => {
  const nodeArr = Array
    .from({ length: size }, generateInitialValue);
  const rootCandidates = {};
  for (let i=0; i<size; i++) {
    const [
      id,
      leftChild,
      rightChild,
    ] = nodeInfoArr[i]
      .split(' ')
      .map((s) => Number(s));

    let type = 'leaf';

    if (leftChild !== -1) {
      type = 'internal node';
      nodeArr[id].degree++;
      nodeArr[leftChild].parent = id;
      nodeArr[leftChild].sibling = rightChild;
      delete rootCandidates[leftChild];
    }

    if (rightChild !== -1) {
      type = 'internal node';
      nodeArr[id].degree++;
      nodeArr[rightChild].parent = id;
      nodeArr[rightChild].sibling = leftChild;
      delete rootCandidates[rightChild];
    }

    nodeArr[id].leftChild = leftChild;
    nodeArr[id].rightChild = rightChild;
    nodeArr[id].type = type;

    if (nodeArr[id].parent === -1) {
      rootCandidates[id] = true;
    } else {
      delete rootCandidates[id];
    }

    // console.log(`i: ${i}, ${JSON.stringify(nodeArr[id])}`);
  }

  // console.log(Object.keys(rootCandidates));
  const rootId = Object.keys(rootCandidates)[0];
  nodeArr[rootId].type = 'root';

  fillDepth(rootId, nodeArr);

  fillHeight(nodeArr);

  nodeArr.forEach(printNode);
};

const generateInitialValue = (_, index) => {
  return {
    id: index,
    leftChild: -1,
    rightChild: -1,
    parent: -1,
    sibling: -1,
    degree: 0,
    depth: 0,
    height: 0,
    type: 'leaf',
  };
};

const fillDepth = (id, nodeArr, depth = 0) => {
  nodeArr[id].depth = depth;
  const {
    leftChild,
    rightChild,
  } = nodeArr[id];
  if (leftChild !== -1) {
    fillDepth(leftChild, nodeArr, depth + 1);
  }
  if (rightChild !== -1) {
    fillDepth(rightChild, nodeArr, depth + 1);
  }
};

const fillHeight = (nodeArr) => {
  for (let i=0; i<nodeArr.length; i++) {
    const { id } = nodeArr[i];
    nodeArr[id].height = getHeight(id, nodeArr);
  }
}

const getHeight = (id, nodeArr) => {
  const {
    leftChild,
    rightChild,
  } = nodeArr[id];

  let leftHeight = 0;
  if (leftChild !== -1) {
    leftHeight = getHeight(leftChild, nodeArr) + 1;
  }

  let rightHeight = 0;
  if (rightChild !== -1) {
    rightHeight = getHeight(rightChild, nodeArr) + 1;
  }

  return Math.max(leftHeight, rightHeight);
};

const printNode = (node) => {
  console.log(`node ${node.id}: parent = ${node.parent}, sibling = ${node.sibling}, degree = ${node.degree}, depth = ${node.depth}, height = ${node.height}, ${node.type}`);
};

Binary Tree

A rooted binary tree is a tree with a root node in which every node has at most two children.

Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:

node ID of u

parent of u

sibling of u

the number of children of u

depth of u

height of u

node type (root, internal node or leaf)

If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.

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

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 is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.

Output

Print the information of each node in the following format:

node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type

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

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

deg, dep and h are the number of children, depth and height of the node respectively.

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.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 25

Sample Input 1

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

Sample Output 1

node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

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;
  }
}

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

  static get Node() { return _Node; }

  insert(key) {
    this.root = new BinaryTree.Node(key, null, null, null);
    this.insert = (key) => {
      let x = this.root, y;
      let newNode = new BinaryTree.Node(key, null, null, null);
      while (x !== null) {
        y = x;
        x = x[key < x.key ? 'left' : 'right'];
      }
      newNode.parent = y;
      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.map((line) => line.split(' ')).forEach(function(cmd) {
    switch(cmd[0].charAt(0)) {
    case 'i': tree.insert(Number(cmd[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, 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, null, null);
    this.insert = (key) => {
      let x = this.root, y;
      let newNode = new BinaryTree.Node(key, null, null);
      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();
    }
  });
})();