<?php
for($i = 0; $i < 10; $i++){
    $array[] = trim(fgets(STDIN));
    }

rsort($array);

for($i = 0; $i < 3; $i++)
    echo $array[$i]."\n";

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

List of Top 3 Hills

There is a data which provides heights (in meter) of mountains. The data is only for ten mountains.

Write a program which prints heights of the top three mountains in descending order.

Input

Height of mountain 1
Height of mountain 2
Height of mountain 3
.
.
Height of mountain 10

Constraints

0 ≤ height of mountain (integer) ≤ 10,000

Output

Height of the 1st mountain
Height of the 2nd mountain
Height of the 3rd mountain

Sample Input 1

1819
2003
876
2840
1723
1673
3776
2848
1592
922

Output for the Sample Input 1

3776
2848
2840

Sample Input 2

100
200
300
400
500
600
700
800
900
900

Output for the Sample Input 2

900
900
800

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.


<?php
  while($line=fgets(STDIN)){
    $num[]=$line;
  }
  foreach($num as $ele){
    $ele2=explode(" ",$ele);
    echo strlen($ele2[0]+$ele2[1])."\n";
  }

Digit Number

Write a program which computes the digit number of sum of two integers a and b.

Input

There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF.

Constraints

0 ≤ a, b ≤ 1,000,000

The number of datasets ≤ 200

Output

Print the number of digits of a + b for each data set.

Sample Input

5 7
1 99
1000 999

Output for the Sample Input

2
3
4


<?php
while(list($a,$b)=fscanf(STDIN,"%d %d")){
    echo strlen($a+$b),PHP_EOL;
}


Is it a Right Triangle?

Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.

Input

Input consists of several data sets. In the first line, the number of data set, N is given. Then, N lines follow, each line corresponds to a data set. A data set consists of three integers separated by a single space.

Constraints

1 ≤ length of the side ≤ 1,000

N ≤ 1,000

Output

For each data set, print "YES" or "NO".

Sample Input

3
4 3 5
4 3 6
8 8 8

Output for the Sample Input

YES
NO
NO


<?php
$n=fgets(STDIN);

for($i=0;$i<$n;$i++){
  list($a,$b,$c)=explode(' ',fgets(STDIN));
  $a*=$a;
  $b*=$b;
  $c*=$c;
  if($a+$b==$c){echo 'YES',PHP_EOL;continue;}
  if($a+$c==$b){echo 'YES',PHP_EOL;continue;}
  if($b+$c==$a){echo 'YES',PHP_EOL;continue;}
  echo 'NO',PHP_EOL;
}


Simultaneous Equation

Write a program which solve a simultaneous equation:

ax + by = c

dx + ey = f

The program should print x and y for given a, b, c, d, e and f (-1,000 ≤ a, b, c, d, e, f ≤ 1,000). You can suppose that given equation has a unique solution.

Input

The input consists of several data sets, 1 line for each data set. In a data set, there will be a, b, c, d, e, f separated by a single space. The input terminates with EOF.

Output

For each data set, print x and y separated by a single space. Print the solution to three places of decimals. Round off the solution to three decimal places.

Sample Input 1

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

Output for the Sample Input 1

-1.000 2.000
1.000 4.000

Sample Input 2

2 -1 -3 1 -1 -3
2 -1 -3 -9 9 27

Output for the Sample Input 2

0.000 3.000
0.000 3.000


<?php
fscanf( STDIN, "%s", $str );
for($i=strlen($str)-1;0<=$i;$i--) echo $str[$i];
?>

Reverse Sequence

Write a program which reverses a given string str.

Input

str (the size of str ≤ 20) is given in a line.

Output

Print the reversed str in a line.

Sample Input

w32nimda

Output for the Sample Input

admin23w


Sum of 4 Integers

Write a program which reads an integer n and identifies the number of combinations of a, b, c and d (0 ≤ a, b, c, d ≤ 9) which meet the following equality:

a + b + c + d = n

For example, for n = 35, we have 4 different combinations of (a, b, c, d): (8, 9, 9, 9), (9, 8, 9, 9), (9, 9, 8, 9), and (9, 9, 9, 8).

Input

The input consists of several datasets. Each dataset consists of n (1 ≤ n ≤ 50) in a line. The number of datasets is less than or equal to 50.

Output

Print the number of combination in a line.

Sample Input

35
1

Output for the Sample Input

4
4


<?php

$million = pow(10, 6);
$arr = array(0, 0) + array_fill(2, $million - 1, 1);
for ($i = 2, $len = sqrt($million); $i <= $len; $i++) {
    if (!$arr[$i]) {
        continue;
    }

    for ($j = $i, $len2 = $million / $i; $j <= $len2; $j++) {
        $arr[$i * $j] = 0;
    }
}
$primes = array_keys(array_filter($arr, function ($val) {
    return $val;
}));

while (($line = trim(fgets(STDIN))) !== '') {
    sscanf($line, '%d', $n);
    $cnt = 0;
    foreach ($primes as $i => $m) {
        if ($n < $m) {
            break;
        }
        $cnt++;
    }
    echo $cnt, PHP_EOL;
}

Prime Number

Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. 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.

Input

Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.

The number of datasets is less than or equal to 30.

Output

For each dataset, prints the number of prime numbers.

Sample Input

10
3
11

Output for the Sample Input

4
2
5


<?php
for(;fscanf(STDIN,'%d', $x);) {
    $cnt = 0;
    for ($i=1; $i<=$x; $i++) {
        if (isprime($i)) $cnt++;
    }
    echo $cnt, PHP_EOL;
}

function isprime($x) {

    if ($x === 2)
        return true;

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

    $max = ceil(sqrt($x));
    for ($i=3; $i <= $max; $i+=2) {
        if ($x % $i === 0) {
            return false;
        }
    }

    return true;
}


?php
$inputArray = array();
while (!feof(STDIN)) {
  $input = trim(fgets(STDIN));
  if (empty($input)) {
    break;
  }
  array_push($inputArray, $input);
}

foreach ($inputArray as $input) {
  $count=0;
  for ($i = 2; $i <= $input; $i++) {
    if (isSosu($i)) {
      $count++;
    }
  }
  echo $count . "\n";
}

function isSosu($num) {
  $count = 0;
  for ($i = 2; $i < $num; $i++) {
    if ($num % $i == 0) {
      $count++;
    }
  }
  if ($count == 0) {
    return true;
  } else {
    return false;
  }
}


<?php
while($line = trim(fgets(STDIN))){
    $count = 1;
    for($i = 3;$i < $line;$i+=2){
        if($line % $i == 0){
            continue;
        }
        $count++;
    }
    echo $count."\n";
}


<?php

$arr = array();
while($line = fgets(STDIN)){
	$in = intval($line);
	if($in == 0){
		$x = array_pop($arr);
		echo $x."\n";
	}else{
		array_push($arr, $in);
	}
}

Switching Railroad Cars

This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks.

We can simulate the movement (comings and goings) of the cars as follow:

An entry of a car is represented by its number.

An exit of a car is represented by 0

For example, a sequence

1
6
0
8
10

demonstrates that car 1 and car 6 enter to the rail tracks in this order, car 6 exits from the rail tracks, and then car 8 and car 10 enter.

Write a program which simulates comings and goings of the cars which are represented by the sequence of car numbers. The program should read the sequence of car numbers and 0, and print numbers of cars which exit from the rail tracks in order. At the first, there are no cars on the rail tracks. You can assume that 0 will not be given when there is no car on the rail tracks.

Input

car number
car number or 0
car number or 0
.
.
.
car number or 0

The number of input lines is less than or equal to 100.

Output

For each 0, print the car number.

Sample Input

1
6
0
8
10
0
0
0

Output for the Sample Input

6
10
8
1


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

Integral

Write a program which computes the area of a shape represented by the following three lines:

$y = x^2$

$y = 0$

$x = 600$

It is clear that the area is $72000000$, if you use an integral you learn in high school. On the other hand, we can obtain an approximative area of the shape by adding up areas of many rectangles in the shape as shown in the following figure:

$f(x) = x^2$

The approximative area $s$ where the width of the rectangles is $d$ is:

area of rectangle where its width is $d$ and height is $f(d)$ $+$

area of rectangle where its width is $d$ and height is $f(2d)$ $+$

area of rectangle where its width is $d$ and height is $f(3d)$ $+$

...

area of rectangle where its width is $d$ and height is $f(600 - d)$

The more we decrease $d$, the higer-precision value which is close to $72000000$ we could obtain. Your program should read the integer $d$ which is a divisor of $600$, and print the area $s$.

Input

The input consists of several datasets. Each dataset consists of an integer $d$ in a line. The number of datasets is less than or equal to 20.

Output

For each dataset, print the area $s$ in a line.

Sample Input

20
10

Output for the Sample Input

68440000
70210000


<?php
$input = '3 6 9 7 5';
$a = explode(' ', $input);
arsort($a);
echo implode(' ' , $a);
?>

Sorting Five Numbers

Write a program which reads five numbers and sorts them in descending order.

Input

Input consists of five numbers a, b, c, d and e (-100000 ≤ a, b, c, d,e ≤ 100000). The five numbers are separeted by a space.

Output

Print the ordered numbers in a line. Adjacent numbers should be separated by a space.

Sample Input

3 6 9 7 5

Output for the Sample Input

9 7 6 5 3


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

Physical Experiments

Ignoring the air resistance, velocity of a freely falling object $v$ after $t$ seconds and its drop $y$ in $t$ seconds are represented by the following formulas:

$ v = 9.8 t $

$ y = 4.9 t^2 $

A person is trying to drop down a glass ball and check whether it will crack. Your task is to write a program to help this experiment.

You are given the minimum velocity to crack the ball. Your program should print the lowest possible floor of a building to crack the ball. The height of the $N$ floor of the building is defined by $5 \times N - 5$.

Input

The input consists of multiple datasets. Each dataset, a line, consists of the minimum velocity v (0 < v < 200) to crack the ball. The value is given by a decimal fraction, with at most 4 digits after the decimal point. The input ends with EOF. The number of datasets is less than or equal to 50.

Output

For each dataset, print the lowest possible floor where the ball cracks.

Sample Input

25.4
25.4

Output for the Sample Input

8
8


<?php
$list = explode("\n",trim(fgets(STDIN)));
$count = array_count_values($list);
$max = max($count);
$num = array_keys($count,$max);
$getans = array();

foreach($num as $value){
  $getans[] = $value;
}
asort($getans);
$ans = implode("\n", $getans);
echo $ans;

//var_dump($num);
?>

Mode Value

Your task is to write a program which reads a sequence of integers and prints mode values of the sequence.
The mode value is the element which occurs most frequently.

Input

A sequence of integers ai (1 ≤ ai ≤ 100). The number of integers is less than or equals to 100.

Output

Print the mode values. If there are several mode values, print them in ascending order.

Sample Input

5
6
3
5
8
7
5
3
9
7
3
4

Output for the Sample Input

3
5

For example, 3 and 5 respectively occur three times, 7 occurs two times, and others occur only one. So, the mode values are 3 and 5.


<?php
$maxlen = "";
$counts = array();

$strs = explode(" ", trim(fgets(STDIN)));
foreach($strs as $str) {
    $counts[$str] = isset($counts[$str]) ? -~$counts[$str] : 1;
    $maxlen < count($str) && $maxlen = $str;
}

arsort($counts);
echo key($counts), " ", $maxlen, PHP_EOL;

English Sentence

Your task is to write a program which reads a text and prints two words. The first one is the word which is arise most frequently in the text. The second one is the word which has the maximum number of letters.

The text includes only alphabetical characters and spaces. A word is a sequence of letters which is separated by the spaces.

Input

A text is given in a line. You can assume the following conditions:

The number of letters in the text is less than or equal to 1000.

The number of letters in a word is less than or equal to 32.

There is only one word which is arise most frequently in given text.

There is only one word which has the maximum number of letters in given text.

Output

The two words separated by a space.

Sample Input

Thank you for your mail and your lectures

Output for the Sample Input

your lectures


<?php
// Here your code !
while ($line = fgets(STDIN)) {
    $num = 1;
    $count = 0;
    if ($line != 0) {
        for ($i = $line; $i > 0; $i--) {
            $num *= $i;
        }
        while ($num > 0) {
            $first = substr($num, -1);
            $num = substr($num, 0, -1);
            if ($first == 0) {
                $count++;
            } else {
                break;
            }
        }
    }
    echo $count;
}
?>

階乗 II

n! = n × (n − 1) × (n − 2) × ... × 3 × 2 × 1

を n の階乗といいます。例えば、12 の階乗は

12! = 12 × 11 × 10 × 9 × 8 × 7 × 6 × 5 × 4 × 3 × 2 × 1 = 479001600

となり、末尾に 0 が 2 つ連続して並んでいます。

整数 n を入力して、n! の末尾に連続して並んでいる 0 の数を出力するプログラムを作成してください。ただし、n は 20000 以下の正の整数とします。

Input

複数のデータが与えられます。各データに n (n ≤ 20000) が１行に与えられます。n が 0 の時入力の最後とします。

データの数は 20 を超えません。

Output

各データに対して n! の末尾に連続して並んでいる 0 の数を１行に出力して下さい。

Sample Input

2
12
10000
0

Output for the Sample Input

0
2
2499


<?php

define('MAX', 110000);
$table = new SplFixedArray(MAX);
$primes = new SplFixedArray(10001);
$primes[0] = 0;
$i = 2;
$p_i = 1;
while ($p_i <= 10000 && $i < MAX) {
    $primes[$p_i] = $primes[$p_i - 1] + $i;
    $p_i++;
    for ($j = $i; $j < MAX; $j += $i) {
        $table[$j] = -1;
    }
    while ($i < MAX && $table[$i] === -1) {
        $i++;
    }
}

while (true) {
    fscanf(STDIN, '%d', $n);
    if ($n === 0) {
        break;
    }
    echo $primes[$n] . PHP_EOL;
}

素数の和

p(i) を小さい方から i 番目の素数とします。例えば、7 は、2, 3, 5, 7 と小さい方から 4 番目の素数なので、p(4) = 7 です。

n が与えられたとき、i = 1 から n までの p(i) の和 s

s = p(1) + p(2) + .... + p(n)

を出力するプログラムを作成してください。例えば、n = 9 のとき、s = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 = 100 となります。

Input

複数のデータセットが与えられます。各データセットに整数 n (n ≤ 10000) が与えられます。n が 0 のとき入力の最後とします。データセットの数は 50 を超えません。

Output

各データセットの n に対して、s を１行に出力して下さい。

Sample Input

2
9
0

Output for the Sample Input

5
100


<?php
	while(true) {
		$stdin = trim(fgets(STDIN));
		if($stdin === '') {
			break;
		}
		$val = explode(',', $stdin);
		$number = $val[0];
		$weight = $val[1];
		$height = $val[2];

		$bmi = $weight / ($height * $height);
		if ($bmi >= 25) {
			echo $number . "\n";
		}
	}

?>

BMI

肥満は多くの成人病の原因として挙げられています。過去においては、一部の例外を除けば、高校生には無縁なものでした。しかし、過度の受験勉強等のために運動不足となり、あるいはストレスによる過食症となることが、非現実的なこととはいえなくなっています。高校生にとっても十分関心を持たねばならない問題になるかもしれません。

そこで、あなたは、保健室の先生の助手となって、生徒のデータから肥満の疑いのある生徒を探し出すプログラムを作成することになりました。

方法は BMI (Body Mass Index) という数値を算出する方法です。BMIは次の式で与えられます。

BMI = 22 が標準的で、25 以上だと肥満の疑いがあります。

各々の生徒の体重、身長の情報から BMI を算出し、25 以上の生徒の学籍番号を出力するプログラムを作成してください。

入力

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

s1,w1,h1
s2,w2,h2
...
...

si (1 ≤ si ≤ 2,000)、wi (1 ≤ wi ≤ 200)、hi (1.0 ≤ hi ≤ 2.0) はそれぞれ、i 番目の生徒の学籍番号（整数）、体重（実数）、身長（実数）を表します。

生徒の数は 50 を超えません。

出力

BMI が 25 以上の生徒の学籍番号を、入力された順番にそれぞれ１行に出力します。

Sample Input

1001,50.0,1.60
1002,60.0,1.70
1003,70.0,1.80
1004,80.0,1.70
1005,90.0,1.60

Output for the Sample Input

1004
1005


西暦和暦変換

西暦で表された年月日を、元号を用いた和暦に変換し、その年月日を出力するプログラムを作成してください。入力は例に示すように 3 つの整数であり、順に西暦年、月、日です。これを、出力例に示すように変換してください。なお、明治以前の年月日が入力された場合は「pre-meiji」と表示してください。

各年号の最初の年は「元年」ではなく「１年」と出力することとします。

元号

期間

meiji

1868. 9. 8 〜 1912. 7.29

taisho

1912. 7.30 〜 1926.12.24

showa

1926.12.25 〜 1989. 1. 7

heisei

1989. 1. 8 〜

入力

複数のデータが与えられます。各データとして年、月、日を表す３つの整数が空白区切りで１行に与えられます。

入力の終わりまで処理してください。データの数は 50 を超えません。

出力

空白区切りの元号、年、月、日、または「pre-meiji」を１行に出力してください。

Sample Input

2005 9 3
1868 12 2
1868 9 7

Output for the Sample Input

heisei 17 9 3
meiji 1 12 2
pre-meiji


<?php
$stdin = trim(fgets(STDIN));

$words = preg_split("/[\s,\.]/", $stdin);
$compWords = array();
for ($i = 0; $i < count($words); $i++) {
  if (strlen($words[$i]) > 2 && strlen($words[$i]) < 7) {
    $compWords[] = $words[$i];
  }
}
print implode(' ', $compWords);
?>

検索エンジン

インターネットの検索エンジン、例えば、Google などでは、世界中のウェブページを自動で収捨して分類し、巨大なデータベースを作成します。また、ユーザが入力した検索キーワードを解析して、データベース検索のための問い合わせ文を作成します。

いずれの場合も、効率的な検索を実現するために複雑な処理を行っていますが、とりあえずの基本は全て文章からの単語の切り出しです。

ということで、文章からの単語の切り出しに挑戦してください。今回は以下の通り、単語区切りが明確な英語の文章を対象とします。

対象となる文章　：　改行を含まない 1024 文字以下の英語の文章

区切り文字 ：　いずれも半角で空白、ピリオド、カンマのみ

切り出す単語　：　3 から 6 文字の単語（2文字以下や7文字以上の単語は無視）

入力

区切り文字及び英数字で構成される英文が１行（すべて半角）に与えられます。

出力

空白文字１文字（半角）で区切られた単語を１行に出力してください。

Sample Input

Rain, rain, go to Spain.

Output for the Sample Input

Rain rain Spain

Sample Input 2

Win today's preliminary contest and be qualified to visit University of Aizu.

Output for the Sample Input 2

Win and visit Aizu


博士が愛した符号

博士 : ピーター君、ついにやったよ。

ピーター : どうしました、デビッド博士？またくだらない発明ですか？

博士 : この表だよ、この表。

文字

符号

（空白）

101

'

000000

,

000011

-

10010001

.

010001

?

000001

A

100101

B

10011010

文字

符号

C

0101

D

0001

E

110

F

01001

G

10011011

H

010000

I

0111

J

10011000

文字

符号

K

0110

L

00100

M

10011001

N

10011110

O

00101

P

111

Q

10011111

R

1000

文字

符号

S

00110

T

00111

U

10011100

V

10011101

W

000010

X

10010010

Y

10010011

Z

10010000

ピーター : なんですか? この表は。

博士 : いいから、言う通りにしてみなさい。まず、お前の名前を紙に書いてごらん。

ピーター : はい"PETER POTTER" っと。

博士 : そうしたら、１文字ずつ、この表の「符号」に置き換えるのだよ。

ピーター : えーと"P" を「111」にして"E" を「110」して…結構面倒ですね。

111 110 00111 110 1000 101 111 00101 00111 00111 110 1000

になりました。なんだか、バーコードみたいですね。

博士 : よろしい。そうしたら、置き換えた文字列を全部つなげて、５文字ごとに区切ってみなさい。

ピーター : はいはい、つなげて区切ると。

11111 00011 11101 00010 11110 01010 01110 01111 10100 0

こんな感じになりました。けど、最後の「0」だけのやつはどうしますか?

博士 : ０を付け加えて５文字にしておいてくれ。

ピーター : えーと最後が０が1個だけだから０をあと４つ加えてやればいいんですね。できました。

11111 00011 11101 00010 11110 01010 01110 01111 10100 00000

博士 : 次はこの表を使うのだ。

符号

文字

00000

A

00001

B

00010

C

00011

D

00100

E

00101

F

00110

G

00111

H

符号

文字

01000

I

01001

J

01010

K

01011

L

01100

M

01101

N

01110

O

01111

P

符号

文字

10000

Q

10001

R

10010

S

10011

T

10100

U

10101

V

10110

W

10111

X

符号

文字

11000

Y

11001

Z

11010

（空白）

11011

.

11100

,

11101

-

11110

'

11111

?

ピーター : これをどう使うんですか…そうか!今度は符号から文字に置き換えるのか!

博士 : そうそう。「11111」だったら「?」に、「00011」だったら「D」にとやってゆけばいいんだよ。

ピーター : これは単純ですね……えーと「?D-C'KOPUA」になりました。でも意味不明ですよ。

博士 : 文字数を数えてごらん。

ピーター : １０文字ですよ。あっ、「PETER POTTER」は１２文字だったのに２文字減っています。

博士 : そう、この表を使えば文字を減らすことができるのだよ。じゃあ今度はこの文章で同じことをやっ
てごらん。

PETER PIPER PICKED A PECK OF PICKLED PEPPERS. A PECK OF PICKLED PEPPERS
PETER PIPER PICKED. IF PETER PIPER PICKED A PECK OF PICKLED PEPPERS, WHERE'S
THE PECK OF PICKLED PEPPERS PETER PIPER PICKED?

ピーター : ぎょぎょ、行が分かれていますが、どうするんですか?

博士 : 紙の都合で３行になってしまったが、改行文字のかわりに空白がある長い１行だと思っておくれ。

ピーター : はいはい。行と行の間にあるのは空白だと。しかし面倒だな……。

博士 : だったらプログラムにやらせればいいではないか。

ということで、ピーターの代わりに、読み込んだ文字列を符号に変換し出力するプログラムを作成してください。

入力

複数のデータセットが与えられます。各データセットに文字列１行（表に含まれる文字からなる）が与えられます。文字列に含まれる文字の数は 1 文字以上 100 文字以下です。

データセットの数は 200 を超えません。

出力

各データセットごとに、変換後の文字列を１行に出力してください。

Sample Input

PETER POTTER

Output for the Sample Input

?D-C'KOPUA


<?php

class Node {
	public $left;
	public $right;
	public $value;
	public $largest;

	public function __construct($value) {
		$this->value = $value;
	}

	public function max_value() {
		if ($this->largest !== null) {
			return $this->largest;
		}
		if (is_null($this->left) && is_null($this->right)) {
			return $this->value;
		}
		$left  = is_null($this->left)  ? -1 : $this->left->max_value();
		$right = is_null($this->right) ? -1 : $this->right->max_value();

		return $this->largest = $this->value + max($left, $right);
	}
}

$diamond = array();

while ($line = trim(fgets(STDIN))) {
	$diamond[] = explode(',', $line);
}

$nodes = array();
for ($i = 0; $i < count($diamond); $i++) {
	for ($j = 0; $j < count($diamond[$i]); $j++) {
		$nodes[$i][$j] = new Node($diamond[$i][$j]);
	}
}

for ($i = 0; $i < count($nodes); $i++) {
	for ($j = 0; $j < count($nodes[$i]); $j++) {
		$n = $nodes[$i][$j];
		if ($i < count($diamond)/2 - 1) {
			$n->left  = isset($nodes[$i + 1][$j])     ? $nodes[$i + 1][$j]     : null;
			$n->right = isset($nodes[$i + 1][$j + 1]) ? $nodes[$i + 1][$j + 1] : null;
		} else {
			$n->left  = isset($nodes[$i + 1][$j - 1]) ? $nodes[$i + 1][$j - 1] : null;
			$n->right = isset($nodes[$i + 1][$j])     ? $nodes[$i + 1][$j]     : null;
		}
	}
}

$top = $nodes[0][0];

echo $top->max_value() . "\n";

最短経路

図１に例示するように整数（0 以上 99 以下）をひしがたに並べます。このような、ひしがたを表すデータを読み込んで、一番上からスタートして一番下まで次のルールに従って進むとき、通過する整数の和の最大値を出力するプログラムを作成してください。

各ステップで、対角線上の左下か対角線上の右下に進むことができます。

例えば図1の例では、図2に示すように、7,3,8,7,5,7,8,3,7を選んで通ったとき、その和は最大の 55 （7+3+8+7+5+7+8+3+7=55） となります。

Input

入力例に示すように、カンマで区切られた整数の並びが、ひし形状に与えられます。各行に空白文字は含まれません。入力例は図１に対応しています。
データの行数は 100 行未満です。

Output

ルールに従って通過する整数の和の最大値を１行に出力します。

Sample Input

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

Sample Output

55


うるう年

西暦 a 年から b 年までの間にあるすべてのうるう年を出力するプログラムを作成してください。

うるう年の条件は、次のとおりとします。ただし、0 < a ≤ b < 3,000 とします。与えられた期間にうるう年がない場合には "NA"と出力してください。

西暦年が 4 で割り切れる年であること。

ただし、100 で割り切れる年はうるう年としない。

しかし、400 で割り切れる年はうるう年である。

Input

複数のデータセットが与えられます。各データセットの形式は以下のとおりです：

a b

a, b がともに 0 のとき入力の終了とします。データセットの数は 50 を超えません。

Output

データセットごとに、西暦または NA を出力してください。

データセットの間に１つの空行を入れてください。

Sample Input

2001 2010
2005 2005
2001 2010
0 0

Output for the Sample Input

2004
2008

NA

2004
2008


<?php

$playNum = trim(fgets(STDIN));
$pointA = 0;
$pointB = 0;

for($count = 0; $count < $playNum; $count++){
    $pointA += ining();
    $pointB += ining();
}
echo $pointA;
echo $pointB;

function ining(){
    $point = 0;
    $outNum = 0;
    $field = array(0,0,0);
    while(true){
        $result = trim(fgets(STDIN));
        if($result == "HIT"){
            if($field[2] === 1){
                $point ++;
            }
            $field[2] = $field[1];
            $field[1] = $field[0];
            $field[0] = 1;

        }else if($result == "HOMERUN"){
            $point = $field[0] + $field[1] + $field[2] + 1;
            $field = array_fill(0, 3, 0);
        }else if($result == "OUT"){
            $outNum++;
            if($outNum === 3){
               return $point;
            }
        }
    }
}

Baseball Simulation

Ichiro likes baseball and has decided to write a program which simulates baseball.

The program reads events in an inning and prints score in that inning. There are only three events as follows:

Single hit

put a runner on the first base.

the runner in the first base advances to the second base and the runner in the second base advances to the third base.

the runner in the third base advances to the home base (and go out of base) and a point is added to the score.

Home run

all the runners on base advance to the home base.

points are added to the score by an amount equal to the number of the runners plus one.

Out

The number of outs is increased by 1.

The runners and the score remain stationary.

The inning ends with three-out.

Ichiro decided to represent these events using "HIT", "HOMERUN" and "OUT", respectively.

Write a program which reads events in an inning and prints score in that inning. You can assume that the number of events is less than or equal to 100.

Input

The input consists of several datasets. In the first line, the number of datasets n is given. Each dataset consists of a list of events (strings) in an inning.

Output

For each dataset, prints the score in the corresponding inning.

Sample Input

2
HIT
OUT
HOMERUN
HIT
HIT
HOMERUN
HIT
OUT
HIT
HIT
HIT
HIT
OUT
HIT
HIT
OUT
HIT
OUT
OUT

Output for the Sample Input

7
0


<?php

while (($line = trim(fgets(STDIN))) !== '0 0') {
    sscanf($line, '%d %d', $H, $W);
    $map = new SplFixedArray($H);
    $visited = array();
    for ($i = 0; $i < $H; $i++) {
        $map[$i] = new SplFixedArray($W);
        $line = trim(fgets(STDIN));
        foreach (str_split($line) as $j => $ch) {
            $map[$i][$j] = $ch;
        }
    }

    $p = '0 0';
    $result = 'LOOP';
    while (!in_array($p, $visited)) {
        sscanf($p, '%d %d', $x, $y);
        $visited[] = $p;
        switch ($map[$y][$x]) {
            case '>':
                $p = sprintf('%d %d', $x + 1, $y);
                break;

            case '<':
                $p = sprintf('%d %d', $x - 1, $y);
                break;

            case '^':
                $p = sprintf('%d %d', $x, $y - 1);
                break;

            case 'v':
                $p = sprintf('%d %d', $x, $y + 1);
                break;

            default:
                $result = $p;
                break 2;
        }
    }

    echo $result, PHP_EOL;
}

Magic Tile

There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles:

Tile with a east-pointing arrow

Tile with a west-pointing arrow

Tile with a south-pointing arrow

Tile with a north-pointing arrow

Tile with nothing

Once a person steps onto a tile which has an arrow, the mystic force makes the person go to the next tile pointed by the arrow. If the next tile has an arrow, the person moves to the next, ans so on. The person moves on until he/she steps onto a tile which does not have the arrow (the tile with nothing). The entrance of the room is at the northwest corner.

Your task is to write a program which simulates the movement of the person in the room. The program should read strings which represent the room and print the last position of the person.

The input represents the room as seen from directly above, and up, down, left and right side of the input correspond to north, south, west and east side of the room respectively. The horizontal axis represents x-axis (from 0 to W-1, inclusive) and the vertical axis represents y-axis (from 0 to H-1, inclusive). The upper left tile corresponds to (0, 0).

The following figure shows an example of the input:

10 10
>>>v..>>>v
...v..^..v
...>>>^..v
.........v
.v<<<<...v
.v...^...v
.v...^<<<<
.v........
.v...^....
.>>>>^....

Characters represent tiles as follows:

'>': Tile with a east-pointing arrow
'<': Tile with a west-pointing arrow
'^': Tile with a north-pointing arrow
'v': Tile with a south-pointing arrow
'.': Tile with nothing

If the person goes in cycles forever, your program should print "LOOP". You may assume that the person never goes outside of the room.

Input

The input consists of multiple datasets. The input ends with a line which contains two 0. Each dataset consists of:

H W
H lines where each line contains W characters

You can assume that 0 < W, H < 101.

Output

For each dataset, print the coordinate (X, Y) of the person or "LOOP" in a line. X and Y should be separated by a space.

Sample Input

10 10
>>>v..>>>v
...v..^..v
>>>>>>^..v
.........v
.v<<<<...v
.v.v.^...v
.v.v.^<<<<
.v.v.....v
.v...^...v
.>>>>^....
6 10
>>>>>>>>>v
.........v
.........v
>>>>v....v
^...v....v
^<<<<<<<<<
0 0

Output for the Sample Input

5 7
LOOP


<?php
$n = trim(fgets(STDIN));

for ($i = 0; $i < $n; ++$i) {
  list($h, $m) = explode(':', trim(fgets(STDIN)));
  $dig_h = $h * 30 + $m * 0.5;
  $dig_m = $m * 6;
  if ($dig_h >= 360) { $dig_h -= 360; }
  $df = abs($dig_h - $dig_m);
  if ($df > 180) { $df = 360 - $df; }

//  echo $df.':';
  if ($df < 30) {
    echo "alert\n";
  } else if ($df < 90) {
    echo "warning\n";
  } else {
    echo "safe\n";
  }
}

時計の短い針と長い針

原始スローライフ主義組織「アカルイダ」から、いたずらの予告状が届きました。アカルイダといえば、要人の顔面にパイを投げつけたりするいたずらで有名ですが、最近では火薬を用いてレセプション会場にネズミ花火をまき散らすなど、より過激化してきました。予告状は次の文面です。

---パソコン ヒトの時間を奪う。良くない。
時計の短い針と長い針 出会うころ、アカルイダ 正義行う。
スローライフ 偉大なり。

たどたどしくてよく解らないのですが、時計の短針と長針とが重なったころにいたずらを決行するという意味のようです。

このいたずらを警戒するため、時刻を入力として、短針と長針が近い場合は "alert"、遠い場合は "safe"、それ以外の場合は "warning" と出力するプログラムを作成してください。ただし、「近い」とは短針と長針の角度が 0° 以上 30° 未満の場合をいい、「遠い」とは 90° 以上 180° 以下の場合をいいます。なお、時刻は 00:00 以上 11:59 以下とします。

Input

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

n
hh1:mm1
hh2:mm2
:
hhn:mmn

1 行目に判定する時刻の個数 n（1 ≤ n ≤ 10000）、2 行目以降に i 番目の時刻 hhi:mmi がそれぞれ１行に与えられます。

Output

i 番目の時刻の判定結果 safe、warning、または alert を順番にそれぞれ１行に出力してください。

Sample Input

4
02:15
06:01
11:55
10:40

Output for the Sample Input

alert
safe
alert
warning


観音堂

一郎君の家の裏山には観音堂があります。この観音堂まではふもとから 30 段の階段があり、一郎君は、毎日のように観音堂まで遊びに行きます。一郎君は階段を１足で３段まで上がることができます。遊んでいるうちに階段の上り方の種類（段の飛ばし方の個数）が非常にたくさんあることに気がつきました。

そこで、一日に 10 種類の上り方をし、すべての上り方を試そうと考えました。しかし数学を熟知しているあなたはそんなことでは一郎君の寿命が尽きてしまうことを知っているはずです。

一郎君の計画が実現不可能であることを一郎君に納得させるために、階段の段数 n を入力とし、一日に 10 種類の上り方をするとして、一郎君がすべての上り方を実行するのに要する年数を出力するプログラムを作成してください。一年は 365 日として計算してください。一日でも必要なら一年とします。365 日なら 1 年であり、366 日なら 2 年となります。

Input

複数のデータセットの並びが入力として与えられます。入力の終わりはゼロひとつの行で示されます。
各データセットとして、段数を表す１つの整数 n (1 ≤ n ≤ 30) が１行に与えられます。

データセットの数は 30 を超えません。

Output

データセットごとに一郎君がすべての上り方を実行するのに必要な年数（整数）を１行に出力します。

Sample Input

1
10
20
25
0

Output for the Sample Input

1
1
34
701


<?php

$file_handle = fopen('php://stdin', "r");

//wfs
function wfs() {
	global $sec;
	global $ary_start;
	global $goal_flag;

	$queue[0] = $ary_start;			//スタートを$queueに入れて開始
	$queue_size = count($queue[0]);	//キューの長さを取得
	$queue[0]['sec'] = 0;			//スタート時の秒数(階層の深さ)を入れる
	while (!empty($queue)) {		//$queueが1つ以上あればループ
	   $cur = array_shift($queue);	//配列$queueの頭から１つ取り出す。

	   //終了条件。全ての配列が同じ色なら終了
	   $cnt = 0;	//カウント
	   for($i=0; $i<$queue_size; $i++){
	       if ($cur[$i] !== $cur[0]){ break; }
	       $cnt++;
	   }
	   if ($cnt === $queue_size) {
	       $goal_flag = 1;
	       $sec = $cur['sec'];	//ゴールした時の秒数
	       break;	//色がすべて同じならwhileを抜ける
	   }

	   //探索
	    for($i=0; $i<$queue_size-1; $i++){
	    	if ($cur[$i] !== $cur[$i+1]){	//隣接する体節の色が違う場合
    			$new = $cur;
    			$new['sec'] = $cur['sec'] + 1;
	    		//変化する色ごとに場合分け
	    		if ($cur[$i] !== 'r' && $cur[$i+1] !== 'r'){
	    			$new[$i] = 'r';  $new[$i+1] = 'r';
	    		} else if ($cur[$i] !== 'g' && $cur[$i+1] !== 'g'){
	    			$new[$i] = 'g';  $new[$i+1] = 'g';
	    		} else {
	    			$new[$i] = 'b';  $new[$i+1] = 'b';
	    		}
	    		$str = toString($new);
	    		if (empty($visited[$str])){
		    		array_push($queue, $new);
				    $visited[$str] = 1;
				}
	    	}
	    }
	}
}

//再訪防止用。配列のキーに文字列を設定するために使用
function toString($ary){
	$str = '';
	foreach ($ary as $key => $val){
		if (is_numeric($key)) {		//配列のキーが数値ならば（secがあるので）
			$str = $str.$val;
		}
	}
	return $str;
}

while (1){
	//変数の初期化
	$sec = 0;
	$goal_flag = 0;

	//ファイル読み込み
	$stdin = trim(fgets($file_handle));
	//終了条件
	if ($stdin == '0'){
		break;
	}
	$ary_start = str_split($stdin);

	//探索
	wfs();

	//出力
	if ($goal_flag === 1){
		echo $sec;
	} else {
		echo 'NA';
	}
	echo PHP_EOL;
}

fclose($file_handle);

ふしぎな虫

会津生物学研究所のA博士は、とある南の島でふしぎな虫を発見しました。形は芋虫のように細長いのですが、ひとつの体節が玉のような形をしているので、糸でつないだビーズ玉のように見えます。ふしぎなのは体の色に様々なバリエーションがあることと、なかには時間がたつにつれて体の色が変っていく虫がいることでした。どの虫の体節の色も赤か緑か青のどれかに限られるようですが、1 秒ごとに体節の色が変わっていき、最後にはすべての体節が同じ色になって落ち着く場合もあれば、いつまで待ってもずっと色が変わりつづける場合もあるようでした。

調べていくうちに、ふだんはすべての体節が同じ色をしているのですが、何かに驚いたりして興奮した後は体節の色が勝手に変わってしまうことがわかりました。一度体節の色が変わってしまうと、ふたたびすべての体節が同じ色になるまではずっと色が変わり続けることがわかりました。

A博士はこの虫を何匹も捕まえて興奮させてみては、色が変わる様子を興味深く観察していましたが、やがて色が変化している最中の色の変わり方には次のような規則性があることに気がつきました。

色が変わるのは、隣り合っている色違いの 2つの体節のペア 1組だけが変わり、他の体節の色は変わらない。ただし、そのようなペアが複数あるときに、どのペアの色が変わるかはあらかじめ予測できない。

そのようなペアは、2つの体節の色のどちらでもない色に同時に変わる(たとえば、緑と赤の体節が隣り合っているときは、それらが同時に青に変わる)。

虫の色の変化を、2秒後まですべて書いたものが上の図です。図の上段のような色をした虫がいるとします。このとき、隣り合った色違いの体節のペアは 3組あるので、1秒後には中段に並べて描いた 3通りの色のどれかに変わります。1秒後に中段左側の 2つのように変わったときには、2秒後にすべての体節が緑色になることができます(図の下段の左側から 2番目)。 それに対して、1秒後に中段の1番右のように変わったときには、2秒後にすべての体節が同じ色に変わることはありません。

博士は、目の前にいる虫の体節がすべて同じ色になる可能性があるのか、あるとしたらそうなるのは最短で何秒後なのかを予測することにしました。

目の前にいる虫の体節の色の並びを入力とし、その虫の体節がすべて同じ色になるのに要する最短の時間を秒単位で出力するプログラムを作成してください。ただし、同じ色になる可能性がないときは「NA(半角英大文字)」と出力してください。また、虫の体節の色の並びは2 以上 10 以下のr(赤)、g(緑)、b(青)からなる文字列で表されます。

Input

複数のデータセットの並びが入力として与えられます。入力の終わりはゼロひとつの行で示されま
す。各データセットとして、 虫の体節の情報を表す１つの文字列が１行に与えられます。

データセットの数は 100 を超えません。

Output

データセット毎に、すべての体節の色が同じになるまでに要する最小時間 (秒単位の整数) または NA を１行に出力します。

Sample Input

rbgrg
rbbgbbr
bgr
bgrbrgbr
bggrgbgrr
gbrggrbggr
rrrrr
bgbr
0

Output for the Sample Input

5
7
1
6
NA
8
0
4


ヒットアンドブロー

太郎君と花子さんはヒットアンドブローで遊ぶことにしました。ヒットアンドブローのルールは、以下の通りです。

出題者と回答者に分かれて行う。

出題者は、重複した数を含まない 4 桁の数字(正解)を決める。

回答者は、その 4 桁の数字(回答)を言い当てる。

回答に対して、出題者はヒットとブローの数でヒントを与える。

回答と正解を比べて、数と桁位置の両方が同じであることをヒットと呼び、数だけが同じで桁位置が異なることをブローと呼ぶ。たとえば、正解が 1234 で、回答が 1354 なら、出題者は「2 ヒット、1 ブロー」というヒントを与え、正解までこれを繰り返す。

出題者と回答者は交代してゲームを行い、より少ない回答で正解を言い当てた方を勝ちとする。

太郎君と花子さんは、ヒットの数とブローの数をその都度判断することが少し面倒に感じているようです。そんな二人のために、ヒットの数とブローの数が即座に分かるプログラムを作成してあげましょう。

正解 r と回答 a を入力とし、ヒットの数とブローの数を出力するプログラムを作成してください。r、a はそれぞれ 0 から 9 の数字 4 つからなる数字の列です。

Input

複数のデータセットの並びが入力として与えられます。入力の終わりはゼロふたつの行で示されます。各データセットとして、r と a が空白区切りで１行に与えられます。

データセットの数は 12000 を超えません。

Output

入力データセットごとに、ヒットの数とブローの数を１行に出力します。

Sample Input

1234 5678
1234 1354
1234 1234
1230 1023
0123 1234
0 0

Output for the Sample Input

0 0
2 1
4 0
1 3
0 3


<?php

$student_number = [];
for ($i = 0; $i < 28; $i++) {
    $student_number[] = intval(trim(fgets(STDIN)));
}

for ($i = 1; $i < 31; $i++) {
    if (!in_array($i, $student_number)) echo $i . PHP_EOL;
}

未提出者は誰だ

問題

JOI大学のM教授はプログラミングの授業を担当している．クラスには30人の受講生がいて各受講生には1番から30番までの出席番号がふられている．この授業の課題を28人の学生が提出した．提出した28人の出席番号から提出していない2人の出席番号を求めるプログラムを作成せよ．

入力

入力は28行あり，各行には提出者の出席番号（1以上30以下）が1つずつ書かれている．入力される出席番号に重複はないが，どのような順に入力されるかはわからない．

出力

出力は2行からなる． 1行目に2人の未提出者の出席番号のうち小さいほうを， 2行目に大きいほうを出力せよ．

入出力例

入力例 1

3
1
4
5
7
9
6
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

出力例 1

2
8

入力例 2

9
30
6
12
10
20
21
11
7
5
28
4
18
29
17
19
27
13
16
26
14
23
22
15
3
1
24
25

出力例 2

2
8

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


Problem B: Cleaning Robot

Dr. Asimov, a robotics researcher, loves to research, but hates houseworks and his house were really dirty. So, he has developed a cleaning robot.

As shown in the following figure, his house has 9 rooms, where each room is identified by an alphabet:

The robot he developed operates as follows:

If the battery runs down, the robot stops.

If not so, the robot chooses a direction from four cardinal points with the equal probability, and moves to the room in that direction. Then, the robot clean the room and consumes 1 point of the battery.

However, if there is no room in that direction, the robot does not move and remains the same room. In addition, there is a junk room in the house where the robot can not enter, and the robot also remains when it tries to enter the junk room. The robot also consumes 1 point of the battery when it remains the same place.

A battery charger for the robot is in a room. It would be convenient for Dr. Asimov if the robot stops at the battery room when its battery run down.

Your task is to write a program which computes the probability of the robot stopping at the battery room.

Input

The input consists of several datasets. Each dataset consists of:

n
s t b

n is an integer that indicates the initial battery point. s, t, b are alphabets respectively represent the room where the robot is initially, the battery room, and the junk room.

The input ends with a dataset which consists of single 0 for n. Your program should not output for this dataset.

Output

For each dataset, print the probability as a floating point number in a line. The answer may not have an error greater than 0.000001.

Constraints

Judge data includes at most 100 data sets.

n ≤ 15

s, t, b are distinct.

Sample Input

1
E A C
1
E B C
2
E A B
0

Output for the Sample Input

0.00000000
0.25000000
0.06250000


<?php

function dfs($v, $count, $sum, $n, $k, $s) {
  if ($count == $k) {
    if ($sum == $s) return 1;
    else return 0;
  }
  if ($v > $n || $sum > $s) return 0;

  $res = 0;

  for ($i = $v + 1; $i <= $n; $i++) {
    $res += dfs($i, $count + 1, $sum + $i, $n, $k, $s);
  }

  return $res;
}

while (fscanf(STDIN, "%d%d%d", $n, $k, $s) && ($n | $k | $s)) {
  print dfs(0, 0, 0, $n, $k, $s) . "\n";
}

Problem A: Equal Sum Sets

Let us consider sets of positive integers less than or equal to n. Note that all elements of a set are different. Also note that the order of elements doesn't matter, that is, both {3, 5, 9} and {5, 9, 3} mean the same set.

Specifying the number of set elements and their sum to be k and s, respectively, sets satisfying the conditions are limited. When n = 9, k = 3 and s = 23, {6, 8, 9} is the only such set. There may be more than one such set, in general, however. When n = 9, k = 3 and s = 22, both {5, 8, 9} and {6, 7, 9} are possible.

You have to write a program that calculates the number of the sets that satisfy the given conditions.

Input

The input consists of multiple datasets. The number of datasets does not exceed 100.

Each of the datasets has three integers n, k and s in one line, separated by a space. You may assume 1 ≤ n ≤ 20, 1 ≤ k ≤ 10 and 1 ≤ s ≤ 155.

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

Output

The output for each dataset should be a line containing a single integer that gives the number of the sets that satisfy the conditions. No other characters should appear in the output.

You can assume that the number of sets does not exceed 231 - 1.

Sample Input

9 3 23
9 3 22
10 3 28
16 10 107
20 8 102
20 10 105
20 10 155
3 4 3
4 2 11
0 0 0

Output for the Sample Input

1
2
0
20
1542
5448
1
0
0


<?php

while ($str = trim(fgets(STDIN))) {
    $nm = explode(" ", $str);
    $count = $nm[0];
    $limit = $nm[1];

    if($count==0 and $limit==0) {
        break;
    }

    $str = trim(fgets(STDIN));
    $prices = explode(" ", $str);

    $maxSum = -1;
    for ($i=0; $i<$count; $i++) {
        for ($j=0; $j<$count; $j++) {
            $sum = $prices[$i] + $prices[$j];
            if ($sum <= $limit) {
                $maxSum = max($maxSum, $sum);
            }
        }
    }

    $result = $maxSum ?: "NONE";
    echo $result."\n";
}

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


<?php
$n_people = intval(fgets(STDIN));
while ($n_people != 0) {

    $input_line = rtrim(fgets(STDIN));
    $number = preg_split("/[\s,]+/", $input_line);
    // 10 20 30 60 文字列配列
    $income = [];
    for ($i = 0; $i < $n_people; $i++){
        // 配列の作りかた
        $income[] = intval($number[$i]);
        // 10 20 30 60 「数字」列配列
    }

    $avg = array_sum($income) / $n_people;

    $count = 0;
    for ($i = 0; $i < $n_people; $i++) {
        if ($income[$i] <= $avg) {
            $count += 1;
        }
    }
    print $count;
    print "\n";
    $n_people = intval(fgets(STDIN));
}

Income Inequality

We often compute the average as the first step
in processing statistical data.
Yes, the average is a good tendency measure of data,
but it is not always the best.
In some cases, the average may hinder the understanding
of the data.

For example, consider the national income of a country.
As the term income inequality suggests,
a small number of people earn a good portion of the gross national income
in many countries.
In such cases, the average income computes much higher than the
income of the vast majority.
It is not appropriate to regard the average as the income of typical people.

Let us observe the above-mentioned phenomenon in some concrete data.
Incomes of n people, a1, ... ,
an, are given.
You are asked to write a program that reports the number of people
whose incomes are less than or equal to the average
(a1 + ... + an) / n.

Input

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

n

a1 a2 ... an

A dataset consists of two lines.
In the first line, the number of people n is given.
n is an integer satisfying 2 ≤ n ≤ 10 000.
In the second line, incomes of n people are given.
ai (1 ≤ i ≤ n) is the income
of the i-th person.
This value is an integer greater than or equal to 1 and
less than or equal to 100 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, output the number of people whose incomes are
less than or equal to the average.

Sample Input

7
15 15 15 15 15 15 15
4
10 20 30 60
10
1 1 1 1 1 1 1 1 1 100
7
90 90 90 90 90 90 10
7
2 7 1 8 2 8 4
0

Output for the Sample Input

7
3
9
1
4


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


Problem A: Sum of Consecutive Integers

あなたは数か月に渡る受験戦争を勝ち抜き，晴れてICPC大学に入学することができた．入学手続きの日，大学のキャンパス内では熱狂的なサークルの勧誘活動が行われており，あなたは大量のパンフレットを受け取って帰ってきた．部屋に戻ってきたあなたは受け取ったパンフレットの中から気になる一枚を見つけた．そのパンフレットは大学の広報部から渡されたものだった．

パンフレットには以下のような問題が記されていた．

和が N となるような，連続する2つ以上の正の整数の組み合わせは，何組存在するでしょうか？例えば， 9 は 2+3+4 と 4+5 の 2通りの組み合わせがあります．

この問題の答えが気になったあなたは，プログラムを書いてその答えを調べることにした．したがって，あなたの仕事は，入力として与えられる正の整数 N に対して，問題の答えを出力するプログラムを書くことである．

Input

入力はデータセットの並びである．各データセットはひとつの整数 N からなる一行である．ここで 1 ≤ N ≤ 1000 である．

入力の終りは，ひとつのゼロからなる一行で示される．

Output

出力は，入力の各データセットの表す正の整数に対する問題の答えを，入力データセットの順序通りに並べたものである．それ以外の文字が出力にあってはならない．

Sample Input

9
500
0

Output for the Sample Input

2
3


<?php

fscanf(STDIN,"%d\n",$n);
echo ceil(log($n,3))."\n";

?>

Problem A: 雅先生の地球侵略日誌

クァークゴ帝国遠征軍は、地球侵略をもくろむ悪の組織である。彼らは侵略者の伝統にのっとり、日
本の東京周辺をターゲットに、毎週１体のペースで怪人を送りこみ続けていた。しかし、そのたびに
人類戦隊アースファイブと名乗る５人の戦士があらわれ、街で暴れまわっていた怪人はあっさりと倒
されてしまうのであった。

ワルザード・スルー（地球名：源雅）は、そんな現状を本気で憂いている、クァークゴ帝国遠征軍の
女幹部である。彼女は、毎週の敗北から何も学ぼうとしない司令官や、どこかズレた発明を繰り返す
天才科学者らの下で、頭の痛い日々を過ごしていた。

そんな中、次の作戦は吸血怪人ドラキュラスを日本に送りこむことに決まった。ドラキュラスは、血
を吸った人間をドラキュラスに変えてしまう恐るべき怪人である。ドラキュラスに血を吸われた人間
もまた、他の人間の血を吸って仲間のドラキュラスを増やしていく。こうして地球全土をドラキュラ
スで埋めつくしてしまおうという作戦だ。

これを聞いたワルザードは、すぐに悟った。この作戦は、幼稚園バスの乗っ取りのような普段やって
いるセコい作戦とは訳が違う。あのダメ司令官が立案したものにしては珍しく、本当に地球を征服で
きる可能性を秘めていると。

倍々ゲームの勢いは恐ろしい。地上に降りたったドラキュラスは、またたく間に仲間の数を増やして
いった。このまま行けば地球侵略は目と鼻の先だと思われた。だがその瞬間、ワルザードの脳裏を、
強烈にいやな予感が走り抜けた。まさか、この怪人、オリジナルが倒されると仲間も全滅するなんて
ことはないよな？

慌ててドラキュラスを設計開発した科学者を問いつめたところ、やはりワルザードの危惧していた通
りだった。オリジナルのドラキュラスがやられると、血を吸われた人間はすべて元に戻るように設計
してあるのだという。ふざけんなよ開発者。どうしてそんな余計な機能をつけた！

ワルザードは、開発担当者に飛び膝蹴りをきめると、すぐさまオリジナルの回収作業にとりかかっ
た。いくらオリジナルと偽物は見た目がまったく同じだといっても、このままでは、駆けつけたアー
スファイブに何かしらの理由でオリジナルを見抜かれて敗北するのが目に見えている。

開発者の話によると、ドラキュラス化した人間の重さはすべて同じだが、オリジナルのドラキュラス
はそれよりも少しだけ重いらしい。それならば、天秤ばかりを使えばオリジナルを見つけることがで
きるはずだ。アースファイブがあらわれる前に、できるだけ早くオリジナルのドラキュラスを見つけ
て回収しなければ。

Input

N

入力の１行目には、整数 N（2 ≤ N ≤ 2,000,000,000）が書かれている。これは、オリジナルと偽物を合わせたドラキュラスの数をあらわす。

Output

天秤ばかりを使ってN 体のドラキュラスの中から１体のオリジナルを見つけるには、最悪の場合で
も天秤ばかりを何回使えれば十分か。その最小値を出力せよ。ただし、天秤ばかりの左と右の皿に、
それぞれ何体かのドラキュラスを乗せて重さを比較することを、１回とカウントする。

Sample Input 1

8

Sample Output 1

2

Sample Input 2

30

Sample Output 2

4

Sample Input 3

2000000000

Sample Output 3

20


Insertion Sort

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

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

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

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

Input

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

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

Output

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

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 2 4 6 1 3

Sample Output 1

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

Sample Input 2

3
1 2 3

Sample Output 2

1 2 3
1 2 3
1 2 3

Hint

Template in C


<?php

class Caluculate {

    public function getAnswer() {
        $n = trim(fgets(STDIN));
        $count = 0;

        for ($i = 0; $i < $n; $i++) {
            $num = (int) fgets(STDIN);
            if ($this->isPrime($num)) $count++;
        }

        echo $count . PHP_EOL;
    }
}

class CheckPrimeNumber extends Caluculate {

    public function isPrime($num) {

        if ($num == 2) {
            return true;
        } elseif ( $num < 2 or $num % 2 == 0) {
            return false;
        } else {
            $start = 3;
            while ($start <= sqrt($num) + 1) {
                if ($num % $start == 0) {
                    return false;
                }
                $start += 2;
            }
            return true;
        }
    }
}

$rate = new CheckPrimeNumber();
$rate->getAnswer();

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


<?php

class CalculateSum {

    public function getAnswer()
    {
        $n = trim(fgets(STDIN));
        $count = 0;

        for ($i = 0; $i < $n; $i++) {
            $num = (int) fgets(STDIN);

            if ($this->isPrime($num)) {
                $count++;
            }
        }

        echo $count . PHP_EOL;
    }
}

class CheckPrimeNumbers extends CalculateSum {

    public function isPrime($num)
    {
        if ($num == 2) {
            return true;
        } elseif ( $num < 2 or $num % 2 == 0) {
            return false;
        } else {
            $start = 3;
            while ($start <= sqrt($num)) {
                if ($num % $start == 0) {
                    return false;
                }
                $start += 2;
            }
            return true;
        }
    }
}

$rate = new CheckPrimeNumbers();
$rate->getAnswer();


<?php
	$n = trim( fgets( STDIN ) );
	$nums = [];
	for( $i=0; $i<$n; $i++ ) {
		array_push( $nums, intval( trim( fgets( STDIN ) ) ) );
	}
	$profit = 1-1000000000;
	$min = $nums[0];
	for( $i=1; $i<$n; $i++ ) {
		$d = $nums[$i]-$min;
		if( $profit < $d ) {
			$profit = $d;
		}
		if( $nums[$i] < $min ) {
			$min = $nums[$i];
		}
	}

	print $profit;
?>

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


<?php
fscanf(STDIN, '%d', $N);
$line = trim(fgets(STDIN));
$arr = explode(' ', $line);

$bubbleArr = BubbleSort($arr,$N);
echo(implode(' ',$bubbleArr).PHP_EOL."Stable".PHP_EOL);
$selectionArr = SelectionSort($arr,$N);
echo implode(" ",$selectionArr) . PHP_EOL;
isStable($bubbleArr, $selectionArr);

function BubbleSort($arr,$N)
{
    for ($i = 0; $i<$N; ++$i) {
        for ($j = $N-1; $j>$i; --$j) {
            if ($arr[$j][1] < $arr[$j-1][1]) {
                $tmp = $arr[$j];
                $arr[$j] = $arr[$j - 1];
                $arr[$j - 1] = $tmp;
            }
        }
    }

    return $arr;
}

function SelectionSort($arr, $N){
    for ($i=0; $i<$N; ++$i){
        $mini = $i;
        for ($j=$i; $j<$N; ++$j){
            if ($arr[$j][1] < $arr[$mini][1]){
                $mini = $j;
            }
        }
        if($mini!=$i){
            $tmp = $arr[$i];
            $arr[$i] = $arr[$mini];
            $arr[$mini] = $tmp;
        }
    }
    return $arr;
}

function isStable($bubbleArr, $selectionArr){
    $result = array_diff_assoc($bubbleArr, $selectionArr);
    if(count($result)==0){
        echo("Stable".PHP_EOL);
    } else {
        echo("Not stable".PHP_EOL);
    }
}

Stable Sort

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

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

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

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

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

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

Input

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

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

Output

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

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

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

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

Constraints

1 ≤ N ≤ 36

Sample Input 1

5
H4 C9 S4 D2 C3

Sample Output 1

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

Sample Input 2

2
S1 H1

Sample Output 2

S1 H1
Stable
S1 H1
Stable


<?php

class Answer
{
    public $data_stacked = array();
    public $data_arr;
    public $top;

    public function __construct()
    {
        $this->top = 0;
        $data = trim(fgets(STDIN));
        $this->data_arr = explode(' ', $data);
    }

    public function isEmpty()
    {
        return $this->top == 0;
    }

    public function isFull()
    {
        return $this->top > 10**6 - 1;
    }

    public function push($data)
    {
        if ($this->isFull()) {
            echo 'overflow';
        }

        $this->top++;
        $this->data_stacked[$this->top] = $data;
    }

    public function pop()
    {
        if ($this->isEmpty()) {
            echo 'underflow';
        }

        $this->top--;
        return $this->data_stacked[$this->top + 1];
    }

    public function getAnswer()
    {
        $data_arr = $this->data_arr;
        while (current($data_arr) != false) {
            if ($data_arr[key($data_arr)] == "+") {
                $tmp = $this->pop();
                $this->data_stacked[$this->top] = $this->data_stacked[$this->top] + $tmp;
            } elseif ($data_arr[key($data_arr)] == "-") {
                $tmp = $this->pop();
                $this->data_stacked[$this->top] = $this->data_stacked[$this->top] - $tmp;
            } elseif ($data_arr[key($data_arr)] == "*") {
                $tmp = $this->pop();
                $this->data_stacked[$this->top] = $this->data_stacked[$this->top] * $tmp;
            } else {
                $this->push($data_arr[key($data_arr)]);
            }

            next($data_arr);
        }
        echo $this->data_stacked[1] . "\n";
    }
}

$answer = new Answer();
$answer->getAnswer();

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


<?php

class Simulator
{
    public $queue = array();
    public $n_processes;
    public $quantum;

    public function __construct()
    {
        fscanf(STDIN, "%d", $this->n_processes);
        while ($this->n_processes > 0) {
            fscanf(STDIN, "%s %d", $operation, $key);
            $this->doOperation($operation, $key);
            $this->n_processes -= 1;
        }
    }

    public function doOperation($operation, $key)
    {
        switch ($operation) {
            case 'insert':
                array_unshift($this->queue, $key);
                break;
            case 'delete':
                unset($this->queue[array_search($key, $this->queue)]);
                break;
            case 'deleteFirst':
                unset($this->queue[0]);
                break;
            case 'deleteLast':
                array_pop($this->queue);
                break;
        }
    }

    public function getAnswer()
    {
        // echo implode(' ', $this->queue) . "\n";
        echo implode(' ', array_map('intval', $this->queue)) . "\n";
    }
}

$answer = new Simulator();
$answer->getAnswer();

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


<?php

class Simulator
{
    public $queue = array();
    public $n_processes;
    public $quantum;

    public function __construct()
    {
        fscanf(STDIN, "%d", $this->n_processes);
        while ($this->n_processes > 0) {
            fscanf(STDIN, "%s %d", $operation, $key);
            $this->doOperation($operation, $key);
            $this->n_processes -= 1;
        }
    }

    public function doOperation($operation, $key)
    {
        switch ($operation) {
            case 'insert':
                array_unshift($this->queue, $key);
                break;
            case 'delete':
                unset($this->queue[array_search($key, $this->queue)]);
                break;
            case 'deleteFirst':
                unset($this->queue[0]);
                break;
            case 'deleteLast':
                array_pop($this->queue);
                break;
        }
    }

    public function getAnswer()
    {
        // var_dump(array_values($this->queue));
        echo implode(' ', array_values($this->queue)) . "\n";
    }
}

$answer = new Simulator();
$answer->getAnswer();


<?php

class Operator
{
    private $operated_keys;
    private $operations_count;

    public function doOperations()
    {
        fscanf(STDIN, '%d', $this->operations_count);
        $this->operated_keys = new \SplDoublyLinkedList();
        for (;$this->operations_count > 0;$this->operations_count -= 1) {
            $operation = explode(' ', trim(fgets(STDIN)));
            if ($operation[0] === 'insert') {
                $this->operated_keys->unshift($operation[1]);
            } elseif ($operation[0] === 'deleteFirst') {
                $this->operated_keys->shift();
            } elseif ($operation[0] === 'deleteLast') {
                $this->operated_keys->pop();
            } elseif ($operation[0] === 'delete') {
                foreach ($this->operated_keys as $key => $element) {
                    if ($element === $operation[1]) {
                        $this->operated_keys->offsetUnset($key);
                        break;
                    }
                }
            }
        }
    }

    public function getAnswer()
    {
        $keys_operated = array();

        while (count($this->operated_keys) > 0) {
            $keys_operated[] = $this->operated_keys->shift();
        }
        echo implode(' ', $keys_operated), PHP_EOL;
    }
}

$operator = new Operator();
$operator->doOperations();
$operator->getAnswer();


<?php
$lengthA = (int) fgets(STDIN);
$stdinA = explode(" ",fgets(STDIN));

$lengthKey = (int) fgets(STDIN);
$stdinKey = explode(" ",fgets(STDIN));

$count = 0;

for($j=0; $j<$lengthKey; ++$j){
    $result = linearSearch($stdinA, $stdinKey[$j], $lengthA);
    if($result == 1){
        $count++;
    }
}

echo trim($count) . PHP_EOL;

function linearSearch($stdin, $key, $N){
    $i=0;
    while($stdin[$i] != $key){
        $i++;
        // NotFound
        if($i==$N){
            return 0;
        }
    }
    return 1;

}

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


<?php

function input() {
    return trim(fgets(STDIN));
}
function input_array() {
    return explode(' ', input());
}

$cnt;

function merge(&$A, $left, $mid, $right) {
    global $cnt;
    $n1 = $mid - $left;
    $n2 = $right - $mid;
    for ($i = 0; $i < $n1; $i++) {
        $L[$i] = $A[$left + $i];
    }
    for ($i = 0; $i < $n2; $i++) {
        $R[$i] = $A[$mid + $i];
    }
    $L[$n1] = INF;
    $R[$n2] = INF;
    $i = $j = 0;
    for ($k = $left; $k < $right; $k++) {
        $cnt++;
        if ($L[$i] <= $R[$j]) {
            $A[$k] = $L[$i++];
        } else {
            $A[$k] = $R[$j++];
        }
    }
}

function mergeSort(&$A, $left, $right) {
    if ($left + 1 < $right) {
        $mid = floor(($left + $right) / 2);
        mergeSort($A, $left, $mid);
        mergeSort($A, $mid, $right);
        merge($A, $left, $mid, $right);
    }
}

input();
$A = array_map(function($numeric_string) {
    return (int)$numeric_string;
}, input_array());

mergeSort($A, 0, count($A));

echo implode(' ', $A) . "\n";
echo "{$cnt}\n";

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


<?php

myMain($argv);

class Util
{
    private static $isDebug = false;
    private static $startTime;

    public static function input($isSplitSpace = false)
    {
        $input = trim(fgets(STDIN));
        if (!$isSplitSpace) {
            return $input;
        }

        return explode(' ', $input);
    }

    public static function arrToStr($arr)
    {
        return implode(",", $arr);
    }

    public static function enablingDebug()
    {
        self::$isDebug = true;
        self::$startTime = time();
    }

    public static function DebugLog($text, $isReturn = true)
    {
        if (self::$isDebug) {
            echo $text;
            if ($isReturn) {
                echo PHP_EOL;
            }
        }
    }

    public static function varDump($obj)
    {
        if (self::$isDebug) {
            var_dump($obj);
        }
    }

    public static function arrFirst($arr)
    {
        if (empty($arr) || !is_array($arr)) {
            return null;
        }

        return current($arr);
    }

    public static function printBench()
    {
        if (!self::$isDebug) {
            return;
        }

        echo sprintf(" Time: %.3f s" . PHP_EOL, time() - self::$startTime);
    }
}

function myMain($argv)
{
    if (!empty($argv[1])) {
        Util::enablingDebug();
    }

    // START
    list($n) = Util::input(true);

    // init
    $a = new Point(0, 0);
    $b = new Point(100, 0);

    Point::stackPoint($a);
    koch($n, $a, $b);
    Point::stackPoint($b);

    Point::printPointList();

    // bench
    Util::printBench();
}

class Point
{
    public $x;
    public $y;

    /** @var Point[] */
    private static $_pointList = [];

    public static function stackPoint(Point $p)
    {
        self::$_pointList[] = $p;
    }

    public static function printPointList()
    {
        foreach (self::$_pointList as $p) {
            echo $p->x . " " . $p->y . PHP_EOL;
        }
    }

    public function __construct($x, $y)
    {
        $this->x = $x;
        $this->y = $y;
    }
}

function koch($n, Point $a, Point $b)
{
    if ($n <= 0) {
        return;
    }

//    $s = new Point(
//        abs($b->x - $a->x) / 3 * 1 + $a->x,
//        abs($b->y - $a->y) / 3 * 1 + $a->y
//    );
//
//    $t = new Point(
//        abs($b->x - $a->x) / 3 * 2 + $a->x,
//        abs($b->y - $a->y) / 3 * 2 + $a->y
//    );

    $s = new Point(
        (2.0 * $a->x + 1.0 * $b->x) / 3,
        (2.0 * $a->y + 1.0 * $b->y) / 3
    );

    $t = new Point(
        (1.0 * $a->x + 2.0 * $b->x) /3,
        (1.0 * $a->y + 2.0 * $b->y) /3
    );

    $u = round60($s, $t);

    koch($n - 1, $a, $s);
    Point::stackPoint($s);

    koch($n - 1, $s, $u);
    Point::stackPoint($u);

    koch($n - 1, $u, $t);
    Point::stackPoint($t);

    koch($n - 1, $t, $b);
}

// $a を起点として、$bを60度回転させた座標を返す
function round60(Point $a, Point $b)
{
    $rad60 = pi() / 3;
    $cx = ($b->x - $a->x) * cos($rad60) - ($b->y - $a->y) * sin($rad60) + $a->x;
    $cy = ($b->x - $a->x) * sin($rad60) + ($b->y - $a->y) * cos($rad60) + $a->y;

    return new Point($cx, $cy);
}

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


<?php
solve1();

// 自力解
function solve1(){
	$n = (int)trim(fgets(STDIN));

	$list = [];
	for ($i=0; $i < $n; $i++) {
		$input = explode(' ', trim(fgets(STDIN)));
		if ($input[0] === 'insert') {
			$node = new BTreeNode((int)$input[1]);
			$list[$node->getId()] = $node;
			insertNode($list, $node);
		}elseif ($input[0] === 'delete') {
			$list = deleteNode($list, (int)$input[1]);
			// var_dump($list);
		}elseif ($input[0] === 'find') {
			if (findNode($list, (int)$input[1])) {
				echo 'yes' . PHP_EOL;
			}else{
				echo 'no' . PHP_EOL;
			}
		}else{
			// $root = getRoot($list);
			// if ($root != NULL) {
			// 	inorderWalk($list, $root);
			// 	echo PHP_EOL;
			// 	preorderWalk($list, $root);
			// 	echo PHP_EOL;
			// }else{
			// 	echo PHP_EOL;
			// 	echo PHP_EOL;
			// }
			var_dump($list);
		}
	}
}

function getRoot($list){
	$p = NULL;
	if (count($list) > 0) {
		$p = $list[array_keys($list)[0]]->getId();
		while (true) {
			$tmp = $list[$p]->getParentId();
			if ($tmp === NULL) {
				break;
			}
			$p = $tmp;
		}
	}
	return $p;
}
function insertNode($list, $node){
	$parent = NULL;
	$cur = getRoot($list);
	while ($cur != NULL) {
		$parent = $cur;
		if ($node->getId() < $list[$parent]->getId()) {
			$cur = $list[$parent]->getLeft();
		}else{
			$cur = $list[$parent]->getRight();
		}
	}
	if ($parent !== $node->getId()) {
		$node->setParentId($parent);
		if ($parent !== NULL) {
			if ($node->getId() < $list[$parent]->getId()) {
				$list[$parent]->setLeft($node->getId());
			}else{
				$list[$parent]->setRight($node->getId());
			}
		}
	}

}

function findNode($list, $target){
	$cur = getRoot($list);
	while ($cur != NULL) {
		if ($list[$cur]->getId() === $target) {
			break;
		}
		$parent = $cur;
		if ($target < $list[$parent]->getId()) {
			$cur = $list[$parent]->getLeft();
		}else{
			$cur = $list[$parent]->getRight();
		}
	}
	return ($cur != NULL);
}

function deleteNode($list, $target){
	if (isset($list[$target])) {
		$children = $list[$target]->getChildren();
		if (count($children) < 2) {
			$successor = $target;
		} else {
			$successor = getSuccessor($list, $target);
		}
		$parent = $list[$successor]->getParentId();

		if ($list[$successor]->hasLeft()) {
			$child = $list[$successor]->getLeft();
		}else{
			$child = $list[$successor]->getRight();
		}
		if ($child !== NULL) {
			$list[$child]->setParentId($parent);
		}

		if ($parent == NULL) {
			# code...
		} elseif ($successor === $list[$parent]->getLeft()) {
			$list[$parent]->setLeft($child);
		}else{
			$list[$parent]->setRight($child);
		}

		if ($successor !== $target) {
			$list[$target]->setId($successor);
			$list[$successor] = $list[$target];
			if ($list[$successor]->hasLeft()) {
				$left = $list[$successor]->getLeft();
				$list[$left]->setParentId($successor);
			}
			if ($list[$successor]->hasRight()) {
				$right = $list[$successor]->getRight();
				$list[$right]->setParentId($successor);
			}
		}
		unset($list[$target]);
	}
	return $list;
}

function getSuccessor($list, $id){
	if ($list[$id]->hasRight()) {
		return getMinimum($list, $list[$id]->getRight());
	}
	$parent = $list[$id]->getParentId();
	while ($parent !== NULL && $id === $list[$parent]->getRight()) {
		$id = $parent;
		$parent = $parent->getParentId();
	}
	return $parent;
}

function getMinimum($list, $id){
	while ($list[$id]->hasLeft()) {
		$id = $list[$id]->getLeft();
	}
	return $id;
}

function preorderWalk($list, $id){
	echo ' ' . $id;
	if ($list[$id]->hasLeft()) {
		preorderWalk($list, $list[$id]->getLeft());
	}
	if ($list[$id]->hasRight()) {
		preorderWalk($list, $list[$id]->getRight());
	}
}

function inorderWalk($list, $id){
	if ($list[$id]->hasLeft()) {
		inorderWalk($list, $list[$id]->getLeft());
	}
	echo ' ' . $id;
	if ($list[$id]->hasRight()) {
		inorderWalk($list, $list[$id]->getRight());
	}
}

class BTreeNode
{
	private $id;
	private $depth = 0;
	private $height = 0;
	private $parent_id = NULL;
	private $left = NULL;
	private $right = NULL;

	function __construct($id)
	{
		$this->id = $id;
	}
	function setParentId($p_id){
		$this->parent_id = $p_id;
	}
	function setLeft($l_id){
		$this->left = $l_id;
	}
	function setRight($r_id){
		$this->right = $r_id;
	}
	function setId($id){
		$this->id = $id;
	}
	function getId(){
		return $this->id;
	}
	function getParentId(){
		return $this->parent_id;
	}
	function getLeft(){
		return $this->left;
	}
	function getRight(){
		return $this->right;
	}
	function hasChild(){
		return ($this->left !== NULL) || ($this->right !== NULL);
	}
	function getChildren(){
		$children = [];
		if ($this->hasLeft()) {
			$children[] = $this->left;
		}
		if ($this->hasRight()) {
			$children[] = $this->right;
		}
		return $children;
	}
	function getAnotherChild($c_id){
		$c = NULL;
		if ($this->getLeft() === $c_id) {
			$c = $this->getRight();
		}elseif ($this->getRight() === $c_id) {
			$c = $this->getLeft();
		}
		return $c;
	}
	function hasLeft(){
		return $this->left !== NULL;
	}
	function hasRight(){
		return $this->right !== NULL;
	}
	function setDepth($d){
		$this->depth = $d;
	}
	function addDepth(){
		$this->depth += 1;
	}
	function getDepth(){
		return $this->depth;
	}
	function setHeight($h){
		$this->height = $h;
	}
	function getHeight(){
		return $this->height;
	}
}

Binary Search Tree III

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

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

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

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

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

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

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

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

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

Input

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

Output

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

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

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

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

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

The keys in the binary search tree are all different.

Sample Input 1

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

Sample Output 1

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

Reference

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


<?php
solve1();

// 自力解
function solve1(){
	$h = (int)trim(fgets(STDIN));
	$input = explode(' ', trim(fgets(STDIN)));
	$data = [];
	for ($i=0; $i < $h; $i++) {
		$data[$i+1] = (int)$input[$i];
	}
	$start = (int)floor($h/2);
	for ($i=$start; $i > 0; $i--) {
		$data = maxHeapify($data, $i);
	}
	foreach ($data as $v) {
		echo ' ' . $v;
	}
	echo PHP_EOL;
}

function maxHeapify($array, $i){
	$h = count($array);
	$l_idx = 2 * $i;
	$r_idx = (2 * $i) + 1;
	$largest = $i;
	if ($l_idx <= $h && $array[$l_idx] > $array[$i]) {
		$largest = $l_idx;
	}
	if ($r_idx <= $h && $array[$r_idx] > $array[$largest]) {
		$largest = $r_idx;
	}

	if ($largest !== $i) {
		$tmp = $array[$largest];
		$array[$largest] = $array[$i];
		$array[$i] = $tmp;
		$array = maxHeapify($array, $largest);
	}
	return $array;
}

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

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 3 2 4 1

Reference

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


Distance

Write a program which calculates the distance between two points P1(x1, y1) and P2(x2, y2).

Input

Four real numbers x1, y1, x2 and y2 are given in a line.

Output

Print the distance in real number. The output should not contain an absolute error greater than 10-4.

Sample Input

0 0 1 1

Sample Output

1.41421356


<?php

while (true) {
    fscanf(STDIN, '%d', $n);

    if (0 == $n) {
        break;
    }

    $format = join(' ', array_map(function () { return '%f'; }, range(1, $n)));
    $nums = fscanf(STDIN, $format);

    $m = array_sum($nums) / $n;
    $s = sqrt(array_sum(array_map(function ($i) use ($m) { return pow($i - $m, 2); }, $nums)) / $n);

    echo "$s\n";
}

Standard Deviation

You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.

The variance α2 is defined by

α2 = (∑ni=1(si - m)2)/n

where m is an average of si.

The standard deviation of the scores is the square root of their variance.

Input

The input consists of multiple datasets. Each dataset is given in the following format:

n
s1 s2 ... sn

The input ends with single zero for n.

Output

For each dataset, print the standard deviation in a line. The output should not contain an absolute error greater than 10-4.

Constraints

n ≤ 1000

0 ≤ si ≤ 100

Sample Input

5
70 80 100 90 20
3
80 80 80
0

Sample Output

27.85677655
0.00000000


<?php
while(true){
    $n = trim(fgets(STDIN));
    if($n == 0) break;
    $s = explode(" ",trim(fgets(STDIN)));
    $m = array_sum($s) / $n;
    $t = 0;
    foreach($s as $v){
        $t += pow(($v-$m),2);
    }
    $al = sqrt($t / $n);
    echo sprintf("%.5f",$al)."\n";
}


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

Distance II

Your task is to calculate the distance between two $n$ dimensional vectors $x = \{x_1, x_2, ..., x_n\}$ and $y = \{y_1, y_2, ..., y_n\}$.

The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance.

\[
D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)^{\frac{1}{p}}
\]

It can be the Manhattan distance

\[
D_{xy} = |x_1 - y_1| + |x_2 - y_2| + ... + |x_n - y_n|
\]

where $p = 1 $.

It can be the Euclidean distance

\[
D_{xy} = \sqrt{(|x_1 - y_1|)^{2} + (|x_2 - y_2|)^{2} + ... + (|x_n - y_n|)^{2}}
\]

where $p = 2 $.

Also, it can be the Chebyshev distance

\[
D_{xy} = max_{i=1}^n (|x_i - y_i|)
\]

where $p = \infty$

Write a program which reads two $n$ dimensional vectors $x$ and $y$, and calculates Minkowski's distance where $p = 1, 2, 3, \infty$ respectively.

Input

In the first line, an integer $n$ is given. In the second and third line, $x = \{x_1, x_2, ... x_n\}$ and $y = \{y_1, y_2, ... y_n\}$ are given respectively. The elements in $x$ and $y$ are given in integers.

Output

Print the distance where $p = 1, 2, 3$ and $\infty$ in a line respectively.
The output should not contain an absolute error greater than 10-5.

Constraints

$1 \leq n \leq 100$

$0 \leq x_i, y_i \leq 1000$

Sample Input

3
1 2 3
2 0 4

Sample Output

4.000000
2.449490
2.154435
2.000000


<?php

class Dice
{
  public $top = 0;
  public $bottom = 0;
  public $north = 0;
  public $east = 0;
  public $south = 0;
  public $west = 0;

  public function toNorth()
  {
    $t = $this->top;
    $this->top = $this->south;
    $this->south = $this->bottom;
    $this->bottom = $this->north;
    $this->north = $t;
  }

  public function toEast()
  {
    $t = $this->top;
    $this->top = $this->west;
    $this->west = $this->bottom;
    $this->bottom = $this->east;
    $this->east = $t;
  }

  public function toSouth()
  {
    $t = $this->top;
    $this->top = $this->north;
    $this->north = $this->bottom;
    $this->bottom = $this->south;
    $this->south = $t;
  }

  public function toWest()
  {
    $t = $this->top;
    $this->top = $this->east;
    $this->east = $this->bottom;
    $this->bottom = $this->west;
    $this->west = $t;
  }

  public function spin()
  {
    $n = $this->north;
    $this->north = $this->west;
    $this->west = $this->south;
    $this->south = $this->east;
    $this->east = $n;
  }

  public function toBottom()
  {
    $this->toNorth();
    $this->toNorth();
  }

  public function toTop($x)
  {
    if ($x == $this->north) $this->toSouth();
    elseif ($x == $this->east) $this->toWest();
    elseif ($x == $this->south) $this->toNorth();
    elseif ($x == $this->west) $this->toEast();
    elseif ($x == $this->bottom) $this->toBottom();
  }
}

$dice = new Dice();
$n = explode(" ", trim(fgets(STDIN)));
$dice->top = $n[0];
$dice->south = $n[1];
$dice->east = $n[2];
$dice->west = $n[3];
$dice->north = $n[4];
$dice->bottom = $n[5];

$q = trim(fgets(STDIN));

for ($i = 0; $i < $q; $i++) {
  list($a, $b) = explode(" ", trim(fgets(STDIN)));
  $dice->toTop($a);
  while ($b != $dice->south) $dice->spin();
  echo $dice->east . "\n";
}

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

Dice II

Construct a dice from a given sequence of integers in the same way as Dice I.

You are given integers on the top face and the front face after the dice was rolled in the same way as Dice I. Write a program to print an integer on the right side face.

Input

In the first line, six integers assigned to faces are given in ascending order of their corresponding labels.
In the second line, the number of questions $q$ is given.

In the following $q$ lines, $q$ questions are given. Each question consists of two integers on the top face and the front face respectively.

Output

For each question, print the integer on the right side face.

Constraints

$0 \leq $ the integer assigned to a face $ \leq 100$

The integers are all different

$1 \leq q \leq 24$

Sample Input

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

Sample Output

3
5
6


<?php
  $x = (int)trim(fgets(STDIN));
  echo $x*$x*$x;

 ?>

X Cubic

Write a program which calculates the cube of a given integer x.

Input

An integer x is given in a line.

Output

Print the cube of x in a line.

Constraints

1 ≤ x ≤ 100

Sample Input 1

2

Sample Output 1

8

Sample Input 2

3

Sample Output 2

27


<?php

$x = trim(fgets(STDIN));

echo pow($x,3),PHP_EOL;


<?php
// Here your code !

$x = file_get_contents('php://stdin');

echo $x ** 3;

?>


<?php
  $input = trim(fgets(STDIN));
  echo $input*$input*$input;
?>


<?php
function xCubic($x)
{
    if(1<=$x && $x<=100){
        return $x*$x*$x;
    }
}
?>


<?php
$stdin = trim(fgets(STDIN));
pow($stdin, 3);
?>


<?php
$stdin = trim(fgets(STDIN));
$result = pow($stdin, 3);

echo $result;
?>


<?php
$x=trim(fgets(STDIN));
print $x*$x*$x."\n";
?>


<?php
$input = trim(fgets(STDIN));
$num = explode(" ",$input);
$erea = $num[0] * $num[1];
$side = ($num[0] + $num[1]) * 2;
echo "$erea $side",PHP_EOL;
?>

Rectangle

Write a program which calculates the area and perimeter of a given rectangle.

Input

The length a and breadth b of the rectangle are given in a line separated by a single space.

Output

Print the area and perimeter of the rectangle in a line. The two integers should be separated by a single space.

Constraints

1 ≤ a, b ≤ 100

Sample Input 1

3 5

Sample Output 1

15 16


<?php
$input = fgets(STDIN);
$array = explode(" ", $input);
$result1 = $array[0] * $array[1];
$result2 = $array[0] + $array[0] + $array[1] + $array[1];
echo $result1." ".$result2;
?>


<?php
fscanf(STDIN, "%d %d", $a, $b);

$menseki = $a * $b;
$nagasa = $a * 2 + $b * 2;
echo "{$menseki} {$nagasa}\n";


<?php
list($a, $b) = explode(" ", fgets(STDIN));
printf("%d %d\n", $a*$b, 2*($a+$b));


<?php
$seconds = trim(fgets(STDIN));
$hours = floor($seconds / 3600);
$minutes = floor($seconds % 3600 / 60);
$seconds = floor($seconds % 60);
echo "{$hours}:{$minutes}:{$seconds}";
?>

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

Watch

Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.

Input

An integer $S$ is given in a line.

Output

Print $h$, $m$ and $s$ separated by ':'. You do not need to put '0' for a value, which consists of a digit.

Constraints

$0 \leq S \leq 86400$

Sample Input 1

46979

Sample Output 1

13:2:59


<?php

$input =trim(fgets(STDIN));

$h = floor($input / 3600);
$m =floor($input % 3600 / 60);
$s =floor($input % 3600 % 60);

echo"$h:$m:$s";


<?php

function getTime($seconds, &$hour, &$minute, &$second){
    $leftSeconds=$seconds%86400;
    $hour=$leftSeconds/3600;
    $minute=($leftSeconds%3600)/60;
    $second=$leftSeconds%60;
}

$input=trim(fgets(STDIN));

$hour=0;
$minute=0;
$second=0;
getTime($input, $hour, $minute, $second);

echo floor($hour).":".floor($minute).":",floor($second);
?>


<?php
$num = fgets(STDIN);
echo intval($num/3600).":".intval($num/60%60).":".intval($num%60);
?>


<?php

$time = trim(fgets(STDIN));

$second = $time % 60;

$min = ($time - $second) % 3600 / 60;

$hour = intval(($time - $second) / 3600);

echo "$hour:$min:$second\n";


<?php

    $inp = trim(fgets(STDIN));

    $hour = floor($inp / 3600);
    $min = floor(($inp / 60) % 60);
    $sec = $inp % 60;

    echo $hour . ":" . $min . ":" . $sec . PHP_EOL;


<?php
$num = explode(" ", trim(fgets(STDIN)));
if ($num[0] == $num[1]) {
	print("a == b");
}else if ($num[0] < $num[1]) {
	print("a < b");
}else {
	print("a > b");
}

Small, Large, or Equal

Write a program which prints small/large/equal relation of given two integers a and b.

Input

Two integers a and b separated by a single space are given in a line.

Output

For given two integers a and b, print

a < b

if a is less than b,

a > b

if a is greater than b, and

a == b

if a equals to b.

Constraints

-1000 ≤ a, b ≤ 1000

Sample Input 1

1 2

Sample Output 1

a < b

Sample Input 2

4 3

Sample Output 2

a > b

Sample Input 3

5 5

Sample Output 3

a == b


<?php
$input=trim(fgets(STDIN));
$array_data=explode(" ", $input);
$a=$array_data[0];
$b=$array_data[1];
if($a==$b){
	echo "a==b";
}elseif($a=$b){
	echo "a>b";
}elseif($a<$b){
	echo "b>a";
}

?>


<?php
  $input = trim(fgets(STDIN));
  $line2 = explode(' ', $input);

  if($line2[0] < $line2[1]){
    echo $line2[0]." < ".$line2[1];
  }else if($line2[0] > $line2[1]){
    echo $line2[0]." > ".$line2[1];
  }else{
    echo $line2[0]." == ".$line2[1];
  }
?>


<?php
    $array = explode(' ',trim(fgets(STDIN)));
    $x = $array[0];
    $y = $array[1];
    if($x<$y){
        echo "a < b";
    }else if($x>$y){
        echo "a > b";
    }else{
        echo "a == b";
    }
 ?>


<?php

$line = fgets(STDIN);

$lines = explode(" ", $line);

$lines[0] = trim($lines[0]);
$lines[1] = trim($lines[1]);

if ($lines[0] < $lines[1]){
    echo "a < b";
}elseif ($lines[0] > $lines[1]){
    echo "a > b";
}else{
    echo "a == b";
}
?>


<?php

    function compare($a, $b){

        if($a < $b){

            return "a < b";

        }else if($a > $b){

            return "a > b";

        }else if($a == $b){

            return "a == b";
        }

    }

    $num = preg_split('/ /', trim(fgets(STDIN)));

    echo(compare($num[0], $num[1]));

?>


<?php
$line = trim(fgets(STDIN));
$num = explode(" ", $line);
if($num[0] < $num[1] && $num[1] < $num[2]){
    $ans = "はい";
}else{
    $ans = "いいえ";
}
echo $ans."<br>";
?>

Range

Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".

Input

Three integers a, b and c separated by a single space are given in a line.

Output

Print "Yes" or "No" in a line.

Constraints

0 ≤ a, b, c ≤ 100

Sample Input 1

1 3 8

Sample Output 1

Yes

Sample Input 2

3 8 1

Sample Output 2

No


<?php
if (basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
  while ($line = fgets(STDIN)) {
      list($a, $b, $c) = explode(' ', $line);
      $a = (int)$a;
      $b = (int)$b;
      $c = (int)$c;
      echo $a < $b && $b < $c ? 'Yes' : 'No';
  }
}
?>


<?php
$y=explode(' ',trim(fgets(STDIN)));
$a=(int)$y[0];
$b=(int)$y[1];
$c=(int)$y[2];
if($a<$b){
  if($b<$c){echo "Yes\n";exit;}
}
echo "No\n";


Sorting Three Numbers

Write a program which reads three integers, and prints them in ascending order.

Input

Three integers separated by a single space are given in a line.

Output

Print the given integers in ascending order in a line. Put a single space between two integers.

Constraints

1 ≤ the three integers ≤ 10000

Sample Input 1

3 8 1

Sample Output 1

1 3 8


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

Circle in a Rectangle

Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given.

Input

Five integers $W$, $H$, $x$, $y$ and $r$ separated by a single space are given in a line.

Output

Print "Yes" if the circle is placed inside the rectangle, otherwise "No" in a line.

Constraints

$ -100 \leq x, y \leq 100$

$ 0 < W, H, r \leq 100$

Sample Input 1

5 4 2 2 1

Sample Output 1

Yes

Sample Input 2

5 4 2 4 1

Sample Output 2

No


<?php
$input = explode(' ', trim(fgets(STDIN)));
$rectanglePosWidth = $input[0];
$rectanglePosHeight = $input[1];
$circlePosWidth = $input[2];
$circlePosHeight = $input[3];
$circleRadius = $input[4];

if (judgeCircleIncludInRectangleForWidth($circlePosWidth, $circleRadius, $rectanglePosWidth) && judgeCircleIncludInRectangleForHeight($circlePosHeight, $circleRadius, $rectanglePosHeight)) {
    echo 'Yes', PHP_EOL;
} else {
    echo 'No', PHP_EOL;
}

function judgeCircleIncludInRectangleForWidth($circlePosWidth, $circleRadius, $rectanglePosWidth)
{
    return 0 <= ($circlePosWidth - $circleRadius) && ($circlePosWidth + $circleRadius) <= $rectanglePosWidth;
}

function judgeCircleIncludInRectangleForHeight($circlePosHeight, $circleRadius, $rectanglePosHeight)
{
    return  0 <= ($circlePosHeight - $circleRadius) && ($circlePosHeight + $circleRadius) <= $rectanglePosHeight;
}


<?php
$stdin = trim(fgets(STDIN));
(int)$input = explode(" ", $stdin);

$w = abs($input[0]);
$h = abs($input[1]);
$x = abs($input[2]);
$y = abs($input[3]);
$r = abs($input[4]);

if($w - $x - $r >= 0 && $h - $y - $r >= 0) echo 'Yes';
else echo 'No';
?>


<?php

for ($i = 1; true; $i++) {
    fscanf(STDIN, "%d", $x);
    if (0 == $x) break;

    printf("Case %d: %d\n", $i, $x);
}

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


<?php
  $ary = array();
  while (true) {
    $st = trim(fgets(STDIN));
    if ($st == "0") {
      break;
    }
    array_push($ary, $st);
  }
  $i = 1;
  foreach ($ary as $val) {
    print ("Case " . $i . ": " . $val . "\n");
    $i++;
  }
  unset($val);
?>


<?php
$b = 0;
while(true) {
  $a = trim(fgets(STDIN));
  if ($a) {
    echo 'Case ' . (++$b) . ': ' . $a . PHP_EOL;
  } else {
    break;
  }
}


<?php
$input = trim(fgets(STDIN));
$x =1;
while($input!==0){
 echo ("Case ".$x.":");
 echo  (" ".$input);
$input = trim(fgets(STDIN));
$x++;
}
exit;
?>


<?php
  $view = "Case %s : %s";
 $cnt = 1;;
while(true){
     $input = trim(fgets(STDIN));
     echo "Case {$cnt}: {$input}";
     $cnt++;
      if($input == 0) break;
}

?>


<?php
 $cnt = 1;
while(true){
     $input = trim(fgets(STDIN));
  echo 'Case '.$cnt.': '.$input."\n";
     $cnt++;
      if($input == 0) break;
}

?>


<?php

    $i = 1;

    while(true){

        $x = intval(fgets(STDIN));

        if($x == 0){

            break;

        }else{

            echo("Case " . $i . ": " . $x . "\n");
            $i++;

        }
    }
?>


<?php
// Your code here!
    // $input_line = trim(fgets(STDIN));

    // $num = explode(" ",$input_line);

    // $W = intval($num[0]);
    // $H = intval($num[1]);
    // $x = intval($num[2]);
    // $y = intval($num[3]);
    // $r = intval($num[4]);

    $i=0;
    while($input_line = intval(trim(fgets(STDIN)))){
        $i++;
        if($input_line == 0){
            break;
        }
        echo "Case $i: $input_line";
        echo "\n";
    }

?>


Swapping Two Numbers

Write a program which reads two integers x and y, and prints them in ascending order.

Input

The input consists of multiple datasets. Each dataset consists of two integers x and y separated by a single space.

The input ends with two 0 (when both x and y are zero). Your program should not process for these terminal symbols.

Output

For each dataset, print x and y in ascending order in a line. Put a single space between x and y.

Constraints

0 ≤ x, y ≤ 10000

the number of datasets ≤ 3000

Sample Input

3 2
2 2
5 3
0 0

Sample Output

2 3
2 2
3 5


<?php
$to_i = function($s){return (int)$s;};
for(;;) {
    $d = array_map($to_i, explode(" ", (fgets(STDIN))));
    if($d == array(0, 0)) break;
    sort($d);
    echo(implode(" ", $d));
    echo("\n");
}


<?php

$stdin = trim(fgets(STDIN));
$number = explode(" ", $stdin);

$a = intval($number[0]);
$b = intval($number[1]);
$c = intval($number[2]);

$count = 0;
for ($i=$a; $i <$b ; $i++) {
    if ($c % $i == 0) $count++;
}
echo "$count\n";

How Many Divisors?

Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b.

Input

Three integers a, b and c are given in a line separated by a single space.

Output

Print the number of divisors in a line.

Constraints

1 ≤ a, b, c ≤ 10000

a ≤ b

Sample Input 1

5 14 80

Sample Output 1

3


<?php
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
$c = trim(fgets(STDIN));

$counter = 0;
for ($i=$a; $i<=$b ; $i++) {
    if($c%$i == 0) $counter++;
}

echo $counter;


<?php
$input = explode(" ",trim(fgets(STDIN)));
$a = intval($input[0]);
$b = intval($input[1]);
$c = intval($input[2]);
$cnt = 0;
for($i=$a;$i<=$b;$i++){
    if($c%$i===0){
        $cnt++;
    }
}
echo $cnt;
?>


A/B Problem

Write a program which reads two integers a and b, and calculates the following values:

a ÷ b: d (in integer)

remainder of a ÷ b: r (in integer)

a ÷ b: f (in real number)

Input

Two integers a and b are given in a line.

Output

Print d, r and f separated by a space in a line. For f, the output should not contain an absolute error greater than 10-5.

Constraints

1 ≤ a, b ≤ 109

Sample Input 1

3 2

Sample Output 1

1 1 1.50000


Circle

Write a program which calculates the area and circumference of a circle for given radius r.

Input

A real number r is given.

Output

Print the area and circumference of the circle in a line. Put a single space between them. The output should not contain an absolute error greater than 10-5.

Constraints

0 < r < 10000

Sample Input 1

2

Sample Output 1

12.566371 12.566371

Sample Input 2

3

Sample Output 2

28.274334 18.849556


<?php

while( fscanf(STDIN, "%d %s %d", $a, $op, $b)){

    if($op == "?")
        break;

        switch($op){
            case "+": $c = $a + $b; break;
            case "-": $c = $a - $b; break;
            case "*": $c = $a * $b; break;
            case "/": $c = $a / $b; break;
        }
        echo $c."\n";
}

Simple Calculator

Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.

The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.

Input

The input consists of multiple datasets. Each dataset is given in the following format.

a op b

The input ends with a dataset where op = '?'. Your program should not process for this dataset.

Output

For each dataset, print the value in a line.

Constraints

0 ≤ a, b ≤ 20000

No divisions by zero are given.

Sample Input 1

1 + 2
56 - 18
13 * 2
100 / 10
27 + 81
0 ? 0

Sample Output 1

3
38
26
10
108