<?php
class Circle {
    var $r;

    function __construct() {
        fscanf(STDIN, "%d", $this->r);
    }

    function __invoke() {
        return pow($this->r, 2);
    }
}

$obj = new Circle();
echo $obj();

Score : 300 points

Problem Statement

There are N towns in a coordinate plane. Town i is located at coordinates (x_i, y_i). The distance between Town i and Town j is \sqrt{\left(x_i-x_j\right)^2+\left(y_i-y_j\right)^2}.

There are N! possible paths to visit all of these towns once. Let the length of a path be the distance covered when we start at the first town in the path, visit the second, third, \dots, towns, and arrive at the last town (assume that we travel in a straight line from a town to another). Compute the average length of these N! paths.

Constraints

2 \leq N \leq 8

-1000 \leq x_i \leq 1000

-1000 \leq y_i \leq 1000

\left(x_i, y_i\right) \neq \left(x_j, y_j\right) (if i \neq j)

(Added 21:12 JST) All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
:
x_N y_N

Output

Print the average length of the paths.
Your output will be judges as correct when the absolute difference from the judge's output is at most 10^{-6}.

Sample Input 1

3
0 0
1 0
0 1

Sample Output 1

2.2761423749

There are six paths to visit the towns: 1 → 2 → 3, 1 → 3 → 2, 2 → 1 → 3, 2 → 3 → 1, 3 → 1 → 2, and 3 → 2 → 1.

The length of the path 1 → 2 → 3 is \sqrt{\left(0-1\right)^2+\left(0-0\right)^2} + \sqrt{\left(1-0\right)^2+\left(0-1\right)^2} = 1+\sqrt{2}.

By calculating the lengths of the other paths in this way, we see that the average length of all routes is:

\frac{\left(1+\sqrt{2}\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)+\left(2\right)+\left(1+\sqrt{2}\right)}{6} = 2.276142...

Sample Input 2

2
-879 981
-866 890

Sample Output 2

91.9238815543

There are two paths to visit the towns: 1 → 2 and 2 → 1. These paths have the same length.

Sample Input 3

8
-406 10
512 859
494 362
-955 -475
128 553
-986 -885
763 77
449 310

Sample Output 3

7641.9817824387


<?php
// $n = (int)trim(fgets(STDIN));
$input = explode(' ', trim(fgets(STDIN)));

// $start = microtime(true);
$x = (int)$input[0];
$y = (int)$input[1];

$mod = 1000000007;
$sum = 0;
// $i+1, $j+2を何回やるか？
$y_max = (int)floor($y / 2);
for ($i=0; $i <= $y_max; $i++) {
	$x_1 = $i;
	$y_1 = $i * 2;
	// $i+2, $j+1の繰り返しでたどり着けるか？
	if ($x - $x_1 >= 0 && $y - $y_1 >= 0 && $x - $x_1 === ($y - $y_1) * 2) {
		$reach_turn = $i + ($y - $y_1);
		$sum += ModComb::singleComb($reach_turn, $i, $mod);
		$sum %= $mod;
		// 回数の組み合わせとしては1通りしかないはずなのでbreak
		break;
	}
}
// $end = microtime(true);
// echo $end - $start . PHP_EOL;
echo $sum;

/**
 * フェルマーの小定理を利用した組み合わせ計算クラス
 * https://qiita.com/ofutonfuton/items/92b1a6f4a7775f00b6ae
 * $modで組み合わせ爆発を抑制している
 */
class ModComb
{
	// 事前計算テーブル
	private $f_table  = [1]; // $n! % $mod
	private $if_table = [1]; // $k!の($mod-2)乗 % $mod
	// 十分大きな素数にする
	private $mod = 0;

	public function __construct($max = 10000, $mod = 1000000007){
		$this->mod = $mod;
		// 事前計算
		$this->calcFactorial($max);
	}

	// 組み合わせ計算（nCm）
	public function comb($n, $m){
		if ($n === 0 && $m === 0) {
			return 1;
		}
		if ($n < $m || $n < 0) {
			return 0;
		}
		if (!isset($this->f_table[$n])) {
			$this->calcFactorial($n);
		}
		return ($this->if_table[$n - $m] * $this->if_table[$m] % $this->mod) * $this->f_table[$n] % $this->mod;
	}

	// logNで組み合わせを算出する
	public static function singleComb($n, $m, $mod){
		if ($n === 0 && $m === 0) {
			return 1;
		}
		if ($n < $m || $n < 0) {
			return 0;
		}
		$f_n    = self::singleFact($n, $mod);
		$if_n_m = self::sigleBinPow(self::singleFact($n-$m, $mod), $mod-2, $mod) % $mod;
		$if_m   = self::sigleBinPow(self::singleFact($m, $mod), $mod-2, $mod) % $mod;
		return ($if_n_m * $if_m % $mod) * $f_n % $mod;
	}

	private static function singleFact($n, $mod){
		$table = [];
		for ($i=0; $i < $n; $i++) {
			$table[$i] = $i+1;
		}
		$idx = 1;
		while ($idx <= $n) {
			$span = $idx<<1;
			for ($i=0; $i < $n; $i+=$span) {
				if ($idx + $i < $n) {
					$table[$i] = ($table[$i] * $table[$i+$idx]) % $mod;
				}
			}
			$idx = $idx<<1;
		}
		return $table[0];
	}

	private static function sigleBinPow($x, $n, $mod){
		$ans = 1;
		$bin = decbin($n);
		$cur_pos = strlen($bin) -1;
		while ($cur_pos >= 0) {
			if ($bin[$cur_pos] == '1') {
				$ans = ($ans * $x) % $mod;
			}
			$x = ($x * $x) % $mod;
			--$cur_pos;
		}
		return $ans;
	}

	// 順列計算（nPm）
	public function perm($n, $m){
		if ($n < $m) {
			return 0;
		}
		if (!isset($this->f_table[$n])) {
			$this->calcFactorial($n);
		}
		return ($this->if_table[$n - $m] % $this->mod) * $this->f_table[$n] % $this->mod;
	}

	// 重複組合せ計算（nHm）
	public function dupc($n, $m){
		if ($n === 0 && $m === 0) {
			return 1;
		}
		if ($n < 0 || $m === 0) {
			return 0;
		}
		if (!isset($this->f_table[$n + $m - 1])) {
			$this->calcFactorial($n + $m - 1);
		}
		return ($this->if_table[$n - 1] * $this->if_table[$m] % $this->mod) * $this->f_table[$n + $m - 1] % $this->mod;
	}

	// 既存の事前計算結果テーブルの末尾から$maxまでの階乗までtableを拡張する。
	private function calcFactorial($max){
		$already = count($this->f_table);
		for($i = $already; $i <= $max; $i++){
			$this->f_table[$i] = $this->f_table[$i-1] * $i % $this->mod;
			$this->if_table[$i] = $this->if_table[$i-1] * $this->binPow($i, $this->mod-2) % $this->mod;
		}
	}

	// $xの$n乗を2進数で高速に計算する
	// これを単体で利用する場合、コンストラクタの$maxは低めで良い
	public static function binPow($x, $n){
		$ans = 1;
		$bin = decbin($n);
		$cur_pos = strlen($bin) -1;
		while ($cur_pos >= 0) {
			if ($bin[$cur_pos] == '1') {
				$ans = ($ans * $x) % $this->mod;
			}
			$x = ($x * $x) % $this->mod;
			--$cur_pos;
		}
		return $ans;
	}
}

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

Score : 400 points

Problem Statement

There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.

When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).

In how many ways can the knight reach the square (X, Y)?

Find the number of ways modulo 10^9 + 7.

Constraints

1 \leq X \leq 10^6

1 \leq Y \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X Y

Output

Print the number of ways for the knight to reach (X, Y) from (0, 0), modulo 10^9 + 7.

Sample Input 1

3 3

Sample Output 1

2

There are two ways: (0,0) \to (1,2) \to (3,3) and (0,0) \to (2,1) \to (3,3).

Sample Input 2

2 2

Sample Output 2

0

The knight cannot reach (2,2).

Sample Input 3

999999 999999

Sample Output 3

151840682

Print the number of ways modulo 10^9 + 7.

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
	fscanf(STDIN, "%d %d", $n, $t);

	// 食べる時間
	$data = array();
	// 食べ終わった料理
	$a_already = array();
	$total_time = 0;
	for ($i = 0; $i < $n; $i++) {
		fscanf(STDIN, "%d %d", $a,$b);
        $data[$i]["TIME"] = $a;
      	$data[$i]["SATISFACTION"] = $b;
      	$data[$i]["SATISFACTION_PER_TIME"] = $b / $a;
      	$total_time += $a;
	}
	$limit = $t - 0.5;

	foreach( $data as $key => $row ) {
    	$tmp_time_array[$key] = $row["TIME"];
		$tmp_per_array[$key] = $row["SATISFACTION"];
	}
	array_multisort( $tmp_per_array, SORT_DESC, $tmp_time_array, SORT_ASC, $data);

	$total = 0;
	$total2 = 0;
	$time = 0;
	// 単位時間あたりの満足度が高い順に食べる
	foreach ($data as $key => $val) {
      if ($limit < $time) {
        $total2 = $total;
        $time2 = $time;
        $data2 = $data;
        foreach( $data2 as $key => $row ) {
          $tmp_time_array2[$key] = $row["TIME"];
          $tmp_per_array2[$key] = $row["SATISFACTION_PER_TIME"];
		}
        array_multisort( $tmp_time_array2, SORT_ASC, $tmp_per_array2, SORT_DESC,  $data2);
      	foreach ($data2 as $key2 => $val2) {
            if ($limit < $time2) break;
        	$total2 += $val2["SATISFACTION"];
			$time2 += $val2["TIME"];
            unset($data2[$key2]);
        }
        break;
      }
      $total += $val["SATISFACTION"];
      $time += $val["TIME"];
      unset($data[$key]);
    }
	if ($total2 != 0 && $total < $total2) {
      echo $total2;
    } else {
      echo $total;
    }

Score : 500 points

Problem Statement

Takahashi is at an all-you-can-eat restaurant.

The restaurant offers N kinds of dishes. It takes A_i minutes to eat the i-th dish, whose deliciousness is B_i.

The restaurant has the following rules:

You can only order one dish at a time. The dish ordered will be immediately served and ready to eat.

You cannot order the same kind of dish more than once.

Until you finish eating the dish already served, you cannot order a new dish.

After T-0.5 minutes from the first order, you can no longer place a new order, but you can continue eating the dish already served.

Let Takahashi's happiness be the sum of the deliciousness of the dishes he eats in this restaurant.

What is the maximum possible happiness achieved by making optimal choices?

Constraints

2 \leq N \leq 3000

1 \leq T \leq 3000

1 \leq A_i \leq 3000

1 \leq B_i \leq 3000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N T
A_1 B_1
:
A_N B_N

Output

Print the maximum possible happiness Takahashi can achieve.

Sample Input 1

2 60
10 10
100 100

Sample Output 1

110

By ordering the first and second dishes in this order, Takahashi's happiness will be 110.

Note that, if we manage to order a dish in time, we can spend any amount of time to eat it.

Sample Input 2

3 60
10 10
10 20
10 30

Sample Output 2

60

Takahashi can eat all the dishes within 60 minutes.

Sample Input 3

3 60
30 10
30 20
30 30

Sample Output 3

50

By ordering the second and third dishes in this order, Takahashi's happiness will be 50.

We cannot order three dishes, in whatever order we place them.

Sample Input 4

10 100
15 23
20 18
13 17
24 12
18 29
19 27
23 21
18 20
27 15
22 25

Sample Output 4

145


<?php
$n = (int)trim(fgets(STDIN));
$mod = 998244353;
$input = explode(' ', trim(fgets(STDIN)));
if ((int)$input[0] !== 0) {
	echo 0;
	exit();
}

$list = [];
for ($i=0; $i < $n; $i++) {
	$list[$i] = 0;
}
foreach ($input as $v) {
	$list[(int)$v] += 1;
}
// var_dump($list);
$cnt = 0;
foreach ($list as $k => $v) {
	if ($k === 0 && $v !== 1) {
		echo 0;
		exit();
	}
	if ($k === 0) {
		$prev = 1;
		$cnt = 1;
	}else{
		if ($v !== 0 && $prev === 0) {
			exit();
		}
		$cnt = ($cnt * (pow($prev, $v) % $mod)) % $mod;
		$prev = $v;
	}
}
echo $cnt;

Score : 300 points

Problem Statement

Given is an integer sequence D_1,...,D_N of N elements. Find the number, modulo 998244353, of trees with N vertices numbered 1 to N that satisfy the following condition:

For every integer i from 1 to N, the distance between Vertex 1 and Vertex i is D_i.

Notes

A tree of N vertices is a connected undirected graph with N vertices and N-1 edges, and the distance between two vertices are the number of edges in the shortest path between them.

Two trees are considered different if and only if there are two vertices x and y such that there is an edge between x and y in one of those trees and not in the other.

Constraints

1 \leq N \leq 10^5

0 \leq D_i \leq N-1

Input

Input is given from Standard Input in the following format:

N
D_1 D_2 ... D_N

Output

Print the answer.

Sample Input 1

4
0 1 1 2

Sample Output 1

2

For example, a tree with edges (1,2), (1,3), and (2,4) satisfies the condition.

Sample Input 2

4
1 1 1 1

Sample Output 2

0

Sample Input 3

7
0 3 2 1 2 2 1

Sample Output 3

24


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

$check = false;
for($i=1; $i<=9; $i++) {
  for($j=1; $j<=9; $j++) {
    if($i*$j == $n) {
      $check = true;
    break;
    }
  }
}
if($check == true) echo "Yes";
else echo "No";<?php
fscanf(STDIN, "%d", $n);

$check = false;
for($i=1; $i<=9; $i++) {
  for($j=1; $j<=9; $j++) {
    if($i*$j == $n) {
      $check = true;
    break;
    }
  }
}
if($check == true) echo "Yes";
else echo "No";

Score : 200 points

Problem Statement

Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together.

Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print Yes; if it cannot, print No.

Constraints

1 \leq N \leq 100

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N can be represented as the product of two integers between 1 and 9 (inclusive), print Yes; if it cannot, print No.

Sample Input 1

10

Sample Output 1

Yes

10 can be represented as, for example, 2 \times 5.

Sample Input 2

50

Sample Output 2

No

50 cannot be represented as the product of two integers between 1 and 9.

Sample Input 3

81

Sample Output 3

Yes


<?php
fscanf(STDIN, "%d", $data);
$result = "No";
for ($i = 1; $i < 10; $i++)
{
  for ($j = 1; $j < 10; $j++)
  {
    if($i * $j == $data) {
      $result = "Yes";
      break;
    }
  }
}

echo $result;

?>


Score : 300 points

Problem Statement

Takahashi is standing on a multiplication table with infinitely many rows and columns.

The square (i,j) contains the integer i \times j. Initially, Takahashi is standing at (1,1).

In one move, he can move from (i,j) to either (i+1,j) or (i,j+1).

Given an integer N, find the minimum number of moves needed to reach a square that contains N.

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the minimum number of moves needed to reach a square that contains the integer N.

Sample Input 1

10

Sample Output 1

5

(2,5) can be reached in five moves. We cannot reach a square that contains 10 in less than five moves.

Sample Input 2

50

Sample Output 2

13

(5, 10) can be reached in 13 moves.

Sample Input 3

10000000019

Sample Output 3

10000000018

Both input and output may be enormous.


Score : 400 points

Problem Statement

Takahashi has a water bottle with the shape of a rectangular prism whose base is a square of side a~\mathrm{cm} and whose height is b~\mathrm{cm}. (The thickness of the bottle can be ignored.)

We will pour x~\mathrm{cm}^3 of water into the bottle, and gradually tilt the bottle around one of the sides of the base.

When will the water be spilled? More formally, find the maximum angle in which we can tilt the bottle without spilling any water.

Constraints

All values in input are integers.

1 \leq a \leq 100

1 \leq b \leq 100

1 \leq x \leq a^2b

Input

Input is given from Standard Input in the following format:

a b x

Output

Print the maximum angle in which we can tilt the bottle without spilling any water, in degrees.
Your output will be judged as correct when the absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

2 2 4

Sample Output 1

45.0000000000

This bottle has a cubic shape, and it is half-full. The water gets spilled when we tilt the bottle more than 45 degrees.

Sample Input 2

12 21 10

Sample Output 2

89.7834636934

This bottle is almost empty. When the water gets spilled, the bottle is nearly horizontal.

Sample Input 3

3 1 8

Sample Output 3

4.2363947991

This bottle is almost full. When the water gets spilled, the bottle is still nearly vertical.


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

$ans = 0;
$ans = $a - 2 * $b;
if ($ans >= 0) {
  echo $ans;
} else {
  echo 0;
}

Score : 100 points

Problem Statement

The window of Takahashi's room has a width of A. There are two curtains hung over the window, each of which has a horizontal length of B. (Vertically, the curtains are long enough to cover the whole window.)

We will close the window so as to minimize the total horizontal length of the uncovered part of the window.
Find the total horizontal length of the uncovered parts of the window then.

Constraints

1 \leq A \leq 100

1 \leq B \leq 100

A and B are integers.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the total horizontal length of the uncovered parts of the window.

Sample Input 1

12 4

Sample Output 1

4

We have a window with a horizontal length of 12, and two curtains, each of length 4, that cover both ends of the window, for example. The uncovered part has a horizontal length of 4.

Sample Input 2

20 15

Sample Output 2

0

If the window is completely covered, print 0.

Sample Input 3

20 30

Sample Output 3

0

Each curtain may be longer than the window.


<?php
fscanf(STDIN, "%d %d", $a, $b);
echo max(0, $a - $b * 2);


<?php
list($a,$b)=explode(" ",trim(fgets(STDIN)));
echo max(0,$a-$b*2);


<?php
fscanf(STDIN, "%d", $n);
$d = explode(',', fgets(STDIN));
$count = 0;
for($i=0; $i<$n; $i++){
	for($j=1; $j<$n; $j++){
		$count = $count + ($d[$i]*$d[$j]);
	}
}
echo $count;

Score : 200 points

Problem Statement

It's now the season of TAKOYAKI FESTIVAL!

This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i.

As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points.

There are \frac{N \times (N - 1)}{2} ways to choose two from the N takoyaki served in the festival. For each of these choices, find the health points restored from eating the two takoyaki, then compute the sum of these \frac{N \times (N - 1)}{2} values.

Constraints

All values in input are integers.

2 \leq N \leq 50

0 \leq d_i \leq 100

Input

Input is given from Standard Input in the following format:

N
d_1 d_2 ... d_N

Output

Print the sum of the health points restored from eating two takoyaki over all possible choices of two takoyaki from the N takoyaki served.

Sample Input 1

3
3 1 2

Sample Output 1

11

There are three possible choices:

Eat the first and second takoyaki. You will restore 3 health points.

Eat the second and third takoyaki. You will restore 2 health points.

Eat the first and third takoyaki. You will restore 6 health points.

The sum of these values is 11.

Sample Input 2

7
5 0 7 8 3 3 2

Sample Output 2

312


<?php
fscanf(STDIN, "%s", $count);
$source = fgets(STDIN);
$takos = explode(" ",$source);
$result = 0;

for($i = 0; $i < $count; $i++)
{
    $temp = 0;
    for($j = 1; $i+$j < $count; $j++)
    {
        $temp += $takos[$i+$j];
    }
    $result += $takos[$i]*$temp;
}

echo($result);


<?php

fscanf(STDIN, "%d", $n);
fscanf(STDIN, "%s", $s);
$s = str_split($s);

$cnt = 1;
$tmp = $s[0];
for ($i = 1; $i < $n; ++$i) {
    if ($s[$i] !== $tmp) {
        ++$cnt;
        $tmp = $s[$i];
    }
}

echo $cnt, PHP_EOL;

Score : 300 points

Problem Statement

There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.

Adjacent slimes with the same color will fuse into one larger slime without changing the color. If there were a slime adjacent to this group of slimes before fusion, that slime is now adjacent to the new larger slime.

Ultimately, how many slimes will be there?

Constraints

1 \leq N \leq 10^5

|S| = N

S consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

N
S

Output

Print the final number of slimes.

Sample Input 1

10
aabbbbaaca

Sample Output 1

5

Ultimately, these slimes will fuse into abaca.

Sample Input 2

5
aaaaa

Sample Output 2

1

All the slimes will fuse into one.

Sample Input 3

20
xxzaffeeeeddfkkkkllq

Sample Output 3

10


<?php

	$str1 = fgets(STDIN);
	$str = fgets(STDIN);
	$array = str_split($str);

	$cnt = 0;
	$previous = '';

	foreach ($array as $char) {
		if ($char === $previous) {
			continue;
		} else {
			$cnt++;
		}
		$previous = $char;
	}

	echo $cnt;
?>


<?php
$n = int();
$lArray = ints();
sort($lArray);
//echo implode(" ", $lArray),"\n";
$c = 0;
for($i = 2; $i < $n; $i++){
  for($j = 1; $j < $i; $j++){
    $min = $lArray[$i] - $lArray[$j];

    $k = bsl($lArray, $min);
    $add = $j - $k - 1;
    $c+=max($add,0);
//    echo $lArray[$i]," ",$lArray[$j]," ",$min," ",$add," j=$j k=$k add=$add\n";
  }
}
echo $c;
function mbsl($nums, $target){
  static $map;
  if(!isset($map[$target])){
    $map[$target] = bsl($nums, $target);
  }
  return $map[$target];
}
function bsl($nums, $target) {
    $size = count($nums);
    $min = 0;
    $max = $size - 1;
    while(true){
        $center = floor(($min + $max) / 2);
        $centerValue = $nums[$center];
        if($target == $centerValue){
            return $center;
        }elseif($target > $centerValue){
            $min = $center + 1;
        }else{
            $max = $center;
        }
        if($min == $max){
            $center = floor(($min + $max) / 2);
            $centerValue = $nums[$center];
            if($centerValue == $target){
                return $center;
            }elseif($centerValue < $target){
                return $center;
            }else{
                return $center-1;
            }
        }
    }
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}

Score : 400 points

Problem Statement

Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.

He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:

a < b + c

b < c + a

c < a + b

How many different triangles can be formed? Two triangles are considered different when there is a stick used in only one of them.

Constraints

All values in input are integers.

3 \leq N \leq 2 \times 10^3

1 \leq L_i \leq 10^3

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 ... L_N

Constraints

Print the number of different triangles that can be formed.

Sample Input 1

4
3 4 2 1

Sample Output 1

1

Only one triangle can be formed: the triangle formed by the first, second, and third sticks.

Sample Input 2

3
1 1000 1

Sample Output 2

0

No triangles can be formed.

Sample Input 3

7
218 786 704 233 645 728 389

Sample Output 3

23


<?php
$N = intval(fgets(STDIN));
for($i = 0; $i < $N; $i++)$map[] = trim(fgets(STDIN));

$max = -1;
for($i = 0; $i < $N; $i++){
    $visited = array_fill(0, $N, 0);
    $distance = array_fill(0, $N, 300);
    $current = [$i];
    $visited[$i] = 1;
    $d = 0;
    $distance[$i] = $d;
    while($current){
        $d++;
        $next = [];
        foreach($current as $c){
            for($j = 0; $j < $N; $j++){
                if($map[$c][$j] == "1"){
                    if(!$visited[$j]){
                        $visited[$j] = 1;
                        $distance[$j] = $d;
                        $next[] = $j;
                    }elseif($distance[$j] == $d-2 || $distance[$j] == $d){
                    }else{
                        continue 4;
                    }
                }
            }
        }
        $current = $next;
    }
    if($d > $max){
        $max = $d;
    }
}
echo $max,"\n";

Score : 500 points

Problem Statement

Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S.
If S_{i,j} is 1, there is an edge connecting Vertex i and j; otherwise, there is no such edge.

Determine whether it is possible to divide the vertices into non-empty sets V_1, \dots, V_k such that the following condition is satisfied. If the answer is yes, find the maximum possible number of sets, k, in such a division.

Every edge connects two vertices belonging to two "adjacent" sets. More formally, for every edge (i,j), there exists 1\leq t\leq k-1 such that i\in V_t,j\in V_{t+1} or i\in V_{t+1},j\in V_t holds.

Constraints

2 \leq N \leq 200

S_{i,j} is 0 or 1.

S_{i,i} is 0.

S_{i,j}=S_{j,i}

The given graph is connected.

N is an integer.

Input

Input is given from Standard Input in the following format:

N
S_{1,1}...S_{1,N}
:
S_{N,1}...S_{N,N}

Output

If it is impossible to divide the vertices into sets so that the condition is satisfied, print -1.
Otherwise, print the maximum possible number of sets, k, in a division that satisfies the condition.

Sample Input 1

2
01
10

Sample Output 1

2

We can put Vertex 1 in V_1 and Vertex 2 in V_2.

Sample Input 2

3
011
101
110

Sample Output 2

-1

Sample Input 3

6
010110
101001
010100
101000
100000
010000

Sample Output 3

4


<?php
    // get inputs from stdin
    $input = intval(fgets(STDIN));
    // when value is 1
    if($input === 1) {
        echo 1;

    }
    // when value is odd
    else if($input % 2 === 1) {
        echo ((intval($input/2) + 1)/$input);
    }

    // when value is even
    else {
        echo 0.5;
    }

Score : 100 points

Problem Statement

Given is an integer N.

Takahashi chooses an integer a from the positive integers not greater than N with equal probability.

Find the probability that a is odd.

Constraints

1 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the probability that a is odd.
Your output will be considered correct when its absolute or relative error from the judge's output is at most 10^{-6}.

Sample Input 1

4

Sample Output 1

0.5000000000

There are four positive integers not greater than 4: 1, 2, 3, and 4. Among them, we have two odd numbers: 1 and 3. Thus, the answer is \frac{2}{4} = 0.5.

Sample Input 2

5

Sample Output 2

0.6000000000

Sample Input 3

1

Sample Output 3

1.0000000000


<?php

fscanf(STDIN, "%s", $count);
//$source = fgets(STDIN);
//$matterials = explode(" ", $source);
if($count %= 0)
{
	echo("0.5");
}
else
{
	echo((($count+1)/2)/$count);
}


<?php

class Scanner
{
    private $arr = [];
    private $count = 0;
    private $pointer = 0;

    public function next()
    {
        if ($this->pointer >= $this->count) {
            $str = trim(fgets(STDIN));
            $this->arr = explode(' ', $str);
            $this->count = count($this->arr);
            $this->pointer = 0;
        }
        $result = $this->arr[$this->pointer];
        ++$this->pointer;

        return $result;
    }

    public function hasNext()
    {
        return $this->pointer < $this->count;
    }

    public function nextInt()
    {
        return (int) $this->next();
    }

    public function nextDouble()
    {
        return (float) $this->next();
    }
}

$sc = new Scanner();
$n = $sc->nextInt();
$k = $sc->nextInt();
$sum = 0;

for($i=0;$i<$n;$i++){
    $height = $sc->nextInt();
    if($height >= $k){
        ++$sum;
    }
}

echo $sum.PHP_EOL;

Score : 200 points

Problem Statement

N friends of Takahashi has come to a theme park.

To ride the most popular roller coaster in the park, you must be at least K centimeters tall.

The i-th friend is h_i centimeters tall.

How many of the Takahashi's friends can ride the roller coaster?

Constraints

1 \le N \le 10^5

1 \le K \le 500

1 \le h_i \le 500

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the number of people among the Takahashi's friends who can ride the roller coaster.

Sample Input 1

4 150
150 140 100 200

Sample Output 1

2

Two of them can ride the roller coaster: the first and fourth friends.

Sample Input 2

1 500
499

Sample Output 2

0

Sample Input 3

5 1
100 200 300 400 500

Sample Output 3

5


<?php
$num=trim(fgets(STDIN));
$heights=trim(fgets(STDIN));
$num=explode(" ",$num);
$heights=explode(" ",$heights);
$count=0;
foreach($heights as $height){
	if($height>$num[1]){
    	$count+=1;
    }
}
echo $count;


<?php
list($N, $K) = explode(' ', trim(fgets(STDIN)));
$heights = explode(' ', trim(fgets(STDIN)));

$num = 0;
foreach ($heights as $item) {
    if ($item >= $K) {
        $num++;
    }
}
echo $num;


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

$arr=explode(' ',trim(fgets(STDIN)));
asort($arr);

$k_arr=array_keys($arr);

for($i=0;$i<$n;$i++){
	echo ($k_arr[$i]+1);
	if($i<>$n){
		echo " ";
	}
}

?>

Score : 300 points

Problem Statement

Takahashi is a teacher responsible for a class of N students.

The students are given distinct student numbers from 1 to N.

Today, all the students entered the classroom at different times.

According to Takahashi's record, there were A_i students in the classroom when student number i entered the classroom (including student number i).

From these records, reconstruct the order in which the students entered the classroom.

Constraints

1 \le N \le 10^5

1 \le A_i \le N

A_i \neq A_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print the student numbers of the students in the order the students entered the classroom.

Sample Input 1

3
2 3 1

Sample Output 1

3 1 2

First, student number 3 entered the classroom.

Then, student number 1 entered the classroom.

Finally, student number 2 entered the classroom.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

1 2 3 4 5

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

8 2 4 5 6 7 3 1


<?php
//error_reporting(0);
$N = trim(fgets(STDIN));
//list($N,$K) =  explode(" ",trim(fgets(STDIN)));
$A = explode(" ",trim(fgets(STDIN)));

asort($A);

foreach($A as $k=>$v) {
  printf("%d ",$k+1);
}
printf("\n");


<?php
fscanf(STDIN, "%d %d", $a, $b);
$fixA = ceil(sqrt($a));
$fixB = ceil(sqrt($b));
$init = 2;
while ($a !== 1) {
$i = $init; while ($i < $fixA) {
if ($a % $i == 0) {
$resultA[] = $i;
$a /= $i;
break;
} $i++;
}
$init = $i; }
$resultA = array_unique($resultA);

$init = 2;
while ($b !== 1) {
$i = $init; while ($i < $fixB) {
if ($b % $i == 0) {
$resultB[] = $i;
$b /= $i;
break;
} $i++;
}
$init = $i; }
$resultB = array_unique($resultB);

$primeNumber = array_intersect($resultA, $resultB);

echo count($primeNumber) + 1;

Score : 400 points

Problem Statement

Given are positive integers A and B.

Let us choose some number of positive common divisors of A and B.

Here, any two of the chosen divisors must be coprime.

At most, how many divisors can we choose?

Definition of common divisor

An integer d is said to be a common divisor of integers x and y when d divides both x and y.

Definition of being coprime

Integers x and y are said to be coprime when x and y have no positive common divisors other than 1.

Definition of dividing

An integer x is said to divide another integer y when there exists an integer \alpha such that y = \alpha x.

Constraints

All values in input are integers.

1 \leq A, B \leq 10^{12}

Input

Input is given from Standard Input in the following format:

A B

Output

Print the maximum number of divisors that can be chosen to satisfy the condition.

Sample Input 1

12 18

Sample Output 1

3

12 and 18 have the following positive common divisors: 1, 2, 3, and 6.

1 and 2 are coprime, 2 and 3 are coprime, and 3 and 1 are coprime, so we can choose 1, 2, and 3, which achieve the maximum result.

Sample Input 2

420 660

Sample Output 2

4

Sample Input 3

1 2019

Sample Output 3

1

1 and 2019 have no positive common divisors other than 1.


<?php
// $n = (int)trim(fgets(STDIN));
$input = explode(' ', trim(fgets(STDIN)));

$a = (int)$input[0];
$b = (int)$input[1];

// 最大公約数
$gcd = gcd($a, $b);

// 1
$cnt = 1;
if ($gcd === 1) {
	echo $cnt;
	exit();
}
// 2以上
$tmp = $gcd;
$max = (int)ceil(sqrt($gcd));
for ($i=2; $i <= $max; $i++) {
	$flg = false;
	while ($tmp > 1 && $tmp % $i === 0) {
		// echo $tmp . ' ' . $i . PHP_EOL;
		$tmp = (int)floor($tmp/$i);
		$flg = true;
	}
	if ($flg) {
		$cnt += 1;
	}
}
// 素数だった
if ($tmp === $gcd) {
	$cnt += 1;
}
echo $cnt;

function gcd($m,$n){
	$large = max($m,$n);
	$small = min($m,$n);
	$q = $large % $small;
	if ($q === 0) {
		return $small;
	}else{
		return gcd($small, $q);
	}
}
// 素数判定
// function sieve($n){
// 	$list = range(2, $n);
// 	$result = [1];
// 	for ($i=1; $i < $n; $i++) {
// 		// echo implode(' ', $list) , PHP_EOL;
// 		$tmp_list = [];
// 		$target = array_shift($list);
// 		if (empty($target)) {
// 			break;
// 		}
// 		$result[] = $target;
// 		foreach ($list as $v) {
// 			if ($v % $target !== 0) {
// 				$tmp_list[] = $v;
// 			}
// 		}
// 		$list = $tmp_list;
// 	}
// 	return $result;
// }


Score : 500 points

Problem Statement

We have N locked treasure boxes, numbered 1 to N.

A shop sells M keys. The i-th key is sold for a_i yen (the currency of Japan), and it can unlock b_i of the boxes: Box c_{i1}, c_{i2}, ..., c_{i{b_i}}. Each key purchased can be used any number of times.

Find the minimum cost required to unlock all the treasure boxes. If it is impossible to unlock all of them, print -1.

Constraints

All values in input are integers.

1 \leq N \leq 12

1 \leq M \leq 10^3

1 \leq a_i \leq 10^5

1 \leq b_i \leq N

1 \leq c_{i1} < c_{i2} < ... < c_{i{b_i}} \leq N

Input

Input is given from Standard Input in the following format:

N M
a_1 b_1
c_{11} c_{12} ... c_{1{b_1}}
:
a_M b_M
c_{M1} c_{M2} ... c_{M{b_M}}

Output

Print the minimum cost required to unlock all the treasure boxes.
If it is impossible to unlock all of them, print -1.

Sample Input 1

2 3
10 1
1
15 1
2
30 2
1 2

Sample Output 1

25

We can unlock all the boxes by purchasing the first and second keys, at the cost of 25 yen, which is the minimum cost required.

Sample Input 2

12 1
100000 1
2

Sample Output 2

-1

We cannot unlock all the boxes.

Sample Input 3

4 6
67786 3
1 3 4
3497 1
2
44908 3
2 3 4
2156 3
2 3 4
26230 1
2
86918 1
3

Sample Output 3

69942


<?php
  fscanf(STDIN, "%s", $today);

  switch($today) {
    case 'Sunny':
      echo 'Cloudy';
      break;
    case 'Cloudy':
      echo 'Rainy';
      break;
    case 'Rainy':
      echo 'Sunny';
  }

Score: 100 points

Problem Statement

The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...

Given is a string S representing the weather in the town today. Predict the weather tomorrow.

Constraints

S is Sunny, Cloudy, or Rainy.

Input

Input is given from Standard Input in the following format:

S

Output

Print a string representing the expected weather tomorrow, in the same format in which input is given.

Sample Input 1

Sunny

Sample Output 1

Cloudy

In Takahashi's town, a sunny day is followed by a cloudy day.

Sample Input 2

Rainy

Sample Output 2

Sunny


<?php
$str = ltrim(fgets(STDIN));
if($str == "Sunny")echo "Cloudy";
if($str == "Cloudy")echo "Rainy";
if($str == "Rainy")echo "Sunny";


<?php
fscanf(STDIN,"%s",$s);
if($s=="Sunny"){
echo "Cloudy";
}elseif($s=="cloudy"){
echo "Rainy";
}else{
echo "Sunny";
}


<?php
fscanf(STDIN, "%s", $s);
$weatherArray = array( 'Sunny', 'Cloudy', 'Rainy' );
$weatherIndex = array_search($s, $weatherArray) + 1;
$tomorrowWeather = $weatherArray[$weatherIndex];
echo $tomorrowWeather;
?>


<?PHP
$wether = trim(fgets(STDIN));
if($wether == "Sunny"){
	echo "Cloudy";
}elseif($wether == "Cloudy"){
	echo "Rainy";
}elseif($wether == "Rainy"){
	echo "Sunny";
}
?>


<?php
// input取得パターン（横並び2）
fscanf(STDIN, "%s", $s);
$arr = array('Sunny','Cloudy','Rainy');

$result = array_search($s, $arr);

if($result+1 >= count($arr)){
  $result = 0;
}else{
  $result ++;
}
echo $arr[$result];


<?php
$s = trim(fgets(STDIN));
$whether_array = ["Sunny", "Cloudy", "Rainy"];
echo ($s === "Rainy" ? "Sunny" : $whether_array[array_search($s, $whether_array)+1]) ."\n";


<?php

//標準入力
class Scanner {
  private $arr = [];
  private $count = 0;
  private $pointer = 0;
  public function next() {
      if($this->pointer >= $this->count) {
          $str = trim(fgets(STDIN));
          $this->arr = explode(' ', $str);
          $this->count = count($this->arr);
          $this->pointer = 0;
      }
      $result = $this->arr[$this->pointer];
      $this->pointer++;
      return $result;
  }
  public function hasNext() {
      return $this->pointer < $this->count;
  }
  public function nextInt() {
      return (int)$this->next();
  }
  public function nextDouble() {
      return (double)$this->next();
  }
}

//標準出力
class out {
    public static function println($str = "") {
        echo $str . PHP_EOL;
    }
}

$sc = new Scanner();
$S = $sc->next();

$weather = ['Sunny', 'Cloudy', 'Rainy'];

$ans = $weather[(array_search($S,$weather) + 1) % 3];

echo $ans.PHP_EOL;


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

switch ($stdin) {
    case 'Sunny':
        echo "Cloudy";
        break;
    case 'Cloudy':
        echo "Rainy";
        break;
    case 'Rainy':
        echo "Sunny";
        break;
}


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

if($s == 'Sunny'){
    echo 'Cloudy';
}elseif($s == 'Cloudy'){
    echo 'Rainy';
}else{
    echo 'Sunny';
}
?>


<?php
fscanf(STDIN, "%s", $word);

$arr = str_split($word);

$a = array();
$b = array();

for($i=0;$i<count($arr);$i++) {
  if($i % 2 == 0) {
    array_push($a, $arr[$i]);
  } else {
    array_push($b, $arr[$i]);
  }
}

if(in_array('L', $a) && in_array('R', $b)) {
  echo 'No';
} else {
  echo 'Yes';
}

Score: 200 points

Problem Statement

Takahashi will do a tap dance. The dance is described by a string S where each character is L, R, U, or D. These characters indicate the positions on which Takahashi should step. He will follow these instructions one by one in order, starting with the first character.

S is said to be easily playable if and only if it satisfies both of the following conditions:

Every character in an odd position (1-st, 3-rd, 5-th, \ldots) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th, \ldots) is L, U, or D.

Your task is to print Yes if S is easily playable, and No otherwise.

Constraints

S is a string of length between 1 and 100 (inclusive).

Each character of S is L, R, U, or D.

Input

Input is given from Standard Input in the following format:

S

Output

Print Yes if S is easily playable, and No otherwise.

Sample Input 1

RUDLUDR

Sample Output 1

Yes

Every character in an odd position (1-st, 3-rd, 5-th, 7-th) is R, U, or D.

Every character in an even position (2-nd, 4-th, 6-th) is L, U, or D.

Thus, S is easily playable.

Sample Input 2

DULL

Sample Output 2

No

The 3-rd character is not R, U, nor D, so S is not easily playable.

Sample Input 3

UUUUUUUUUUUUUUU

Sample Output 3

Yes

Sample Input 4

ULURU

Sample Output 4

No

Sample Input 5

RDULULDURURLRDULRLR

Sample Output 5

Yes


<?php

//文字列の入力
fscanf(STDIN,"%",$s);

//文字列を分解
$s = str_split($s);

//文字列の長さを取得
for ($i=1; $i<count($s); $i++) {

    //偶数の文字列目が全てR
    if ($i % 2 == 0 && $s[$i] == "L") {
        echo "No";
        return;

        //奇数の文字列目がLで
    } elseif ($i % 2 == 1 && $s[$i] == "R") {
        echo "No";
        return;
    }
}
echo "Yes";


<?php

fscanf(STDIN, "%s", $input);

$arr1 = str_split($input);
$flag = true;

foreach ($arr1 as $key =>$val){

  //echo $key."/".$val;

  $num = $key+1;

  if($num%2==0) {
	//偶数
    if($val=="R"){
    	$flag = false;
    }
  }else{
  	//奇数
    if($val=="L"){
    	$flag = false;
    }

  }

}

if($flag){
  	echo "Yes";
  }else{
  	echo "No";
  }

?>


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

$array = str_split($S);

$answer = '';

for ($i = 0; $i < count($array); $i++) {
     if ($i % 2 === 0) {
         if($array[$i] === 'R' || $array[$i] === 'U' || $array[$i] === 'D') {
             continue;
         }else {
             $answer = 'No';
             break;
         }
     }else {
         if($array[$i] === 'L' || $array[$i] === 'U' || $array[$i] === 'D') {
             continue;
         }else {
             $answer = 'No';
             break;
         }
     }
}

if(empty($answer)) {
    echo('Yes');
}else {
    echo $answer;
}


Score : 100 points

Problem Statement

Takahashi is going to set a 3-character password.

How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)?

Constraints

1 \leq N \leq 9

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of possible passwords.

Sample Input 1

2

Sample Output 1

8

There are eight possible passwords: 111, 112, 121, 122, 211, 212, 221, and 222.

Sample Input 2

1

Sample Output 2

1

There is only one possible password if you can only use one kind of character.


<?php
$n = trim(fgets(STDIN));
echo $n ** 3,PHP_EOL;


<?php

fscanf(STDIN, "%d", $n);

echo $n**3;


<?php
  $n = trim(fgets(STDIN));
  $arr1 = explode(" ",trim(fgets(STDIN)));
  $arr2 = explode(" ",trim(fgets(STDIN)));
  $arr3 = explode(" ",trim(fgets(STDIN)));
  $sat = 0;
  for($i=0;$i<$n;$i++) {
    $sat += $arr2[$i];
    if($i<$n-1 && $arr1[$i+1]-$arr1[$i] == 1) {
        $sat += $arr3[$arr1[$i]-1];
    }
  }
  echo $sat;

Score : 200 points

Problem Statement

Takahashi went to an all-you-can-eat buffet with N kinds of dishes and ate all of them (Dish 1, Dish 2, \ldots, Dish N) once.

The i-th dish (1 \leq i \leq N) he ate was Dish A_i.

When he eats Dish i (1 \leq i \leq N), he gains B_i satisfaction points.

Additionally, when he eats Dish i+1 just after eating Dish i (1 \leq i \leq N - 1), he gains C_i more satisfaction points.

Find the sum of the satisfaction points he gained.

Constraints

All values in input are integers.

2 \leq N \leq 20

1 \leq A_i \leq N

A_1, A_2, ..., A_N are all different.

1 \leq B_i \leq 50

1 \leq C_i \leq 50

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N
B_1 B_2 ... B_N
C_1 C_2 ... C_{N-1}

Output

Print the sum of the satisfaction points Takahashi gained, as an integer.

Sample Input 1

3
3 1 2
2 5 4
3 6

Sample Output 1

14

Takahashi gained 14 satisfaction points in total, as follows:

First, he ate Dish 3 and gained 4 satisfaction points.

Next, he ate Dish 1 and gained 2 satisfaction points.

Lastly, he ate Dish 2 and gained 5 + 3 = 8 satisfaction points.

Sample Input 2

4
2 3 4 1
13 5 8 24
45 9 15

Sample Output 2

74

Sample Input 3

2
1 2
50 50
50

Sample Output 3

150


<?php
fscanf(STDIN,"%d",$n);
$as=explode(' ',trim(fgets(STDIN)));
$bs=explode(' ',trim(fgets(STDIN)));
$cs=explode(' ',trim(fgets(STDIN)));

$sum = 0;
$add = -1;
foreach ($as as $a) {
  $sum += $bs[$a - 1];
  if ($a - 1 == $add) {
    $sum += $cs[$add - 1];
  }
  $add = $a;
}

echo $sum;


<?php
$N = fgets(STDIN);
$A = explode(' ', trim(fgets(STDIN)));
$B = explode(' ', trim(fgets(STDIN)));
$C = explode(' ', trim(fgets(STDIN)));

$total = 0;
for ($i = 0; $i < $N; $i++) {
    $total += $B[$A[$i] - 1];
    if ($i !== 0) {
        if ($A[$i] - $A[$i - 1] === 1) {
            $total += $C[$A[$i - 1] - 1];
        }
    }
}
echo($total);


<?php
# 数値の入力
fscanf(STDIN, "%d", $data1);
$data2 = fgets(STDIN);
$a = explode(" ", $data2);

$anser = 0;

for($i=0; $i<$data1-2; $i++){
    if($a[$i]>$a[$i+1]){
        $anser += $a[$i+1];
    }else{
        $anser += $a[$i];
    }
}
$anser += $a[$data1-2];

echo $anser;
?>

Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53


<?php
    $num = (int)fgets(STDIN);
    $cond = explode(" ", fgets(STDIN));

$ans = 0;

for($k=0; $k<$num; $k++){
  if($k < $num-1){
      $cond[$k] = (int)$cond[$k];
  }
  if($k <= count($cond)-1){
    if($k === 0){
      $ans += $cond[0];
    }elseif($cond[$k] > $cond[$k-1]){
      $ans += $cond[$k-1];
    }else{
      $ans += $cond[$k];
    }
  }else{
    $ans += $cond[$k-1];
  }
}

echo $ans;


Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136


<?php

fscanf(STDIN,"%d %d",$A,$B);

$count = 0;

//合計口= 個数*口数（１つ）+(口数-個数)

$sum_port = $A;
for($i=0;$i<$B;$i++){
    if($sum_port >= $B){
        echo ($i+1)."\n";
    break;
    }
      $sum_port += $A-1;

}

Score : 200 points

Problem Statement

Takahashi's house has only one socket.

Takahashi wants to extend it with some number of power strips, each with A sockets, into B or more empty sockets.

One power strip with A sockets can extend one empty socket into A empty sockets.

Find the minimum number of power strips required.

Constraints

All values in input are integers.

2 \leq A \leq 20

1 \leq B \leq 20

Input

Input is given from Standard Input in the following format:

A B

Output

Print the minimum number of power strips required.

Sample Input 1

4 10

Sample Output 1

3

3 power strips, each with 4 sockets, extend the socket into 10 empty sockets.

Sample Input 2

8 9

Sample Output 2

2

2 power strips, each with 8 sockets, extend the socket into 15 empty sockets.

Sample Input 3

8 8

Sample Output 3

1


<?php

  $N = trim(fgets(STDIN));

  $H = explode(" ", fgets(STDIN));

  $count = 0;
  $max = 0;

  for ($i = 0; $i < ($N - 1); $i++) {

      if ($H[$i] >= $H[$i + 1]) {

          $count ++;

      } else {

          $max = max($max, $count);
          $count = 0;

      }

  }

  $max = max($max, $count);

echo $max

?>

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right.

The height of the i-th square from the left is H_i.

You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.

Find the maximum number of times you can move.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

Print the maximum number of times you can move.

Sample Input 1

5
10 4 8 7 3

Sample Output 1

2

By landing on the third square from the left, you can move to the right twice.

Sample Input 2

7
4 4 5 6 6 5 5

Sample Output 2

3

By landing on the fourth square from the left, you can move to the right three times.

Sample Input 3

4
1 2 3 4

Sample Output 3

0


<?php
  $n = trim(fgets(STDIN)) ;
  $height = explode(' ',trim(fgets(STDIN))) ;
  $height[-1] = 0 ;
$c = 0 ;
$k = 0 ;
for($i=0;$i<$n;$i++){
if($height[$i] > $height[$i-1]){
$ans[$k] = $c ;
  $c = 0 ;
  $k++ ;
  continue ;
}
  $c++ ;
}
$ans[$k] = $c ;
echo max($ans) ;


Score : 400 points

Problem Statement

For an integer N, we will choose a permutation \{P_1, P_2, ..., P_N\} of \{1, 2, ..., N\}.

Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.

Find the maximum possible value of M_1 + M_2 + \cdots + M_N.

Constraints

N is an integer satisfying 1 \leq N \leq 10^9.

Input

Input is given from Standard Input in the following format:

N

Output

Print the maximum possible value of M_1 + M_2 + \cdots + M_N.

Sample Input 1

2

Sample Output 1

1

When the permutation \{P_1, P_2\} = \{2, 1\} is chosen, M_1 + M_2 = 1 + 0 = 1.

Sample Input 2

13

Sample Output 2

78

Sample Input 3

1

Sample Output 3

0


Score : 500 points

Problem Statement

N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.

The tournament is round-robin format, and there will be N(N-1)/2 matches in total.
Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find the minimum number of days required.

Each player plays at most one matches in a day.

Each player i (1 \leq i \leq N) plays one match against Player A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} in this order.

Constraints

3 \leq N \leq 1000

1 \leq A_{i, j} \leq N

A_{i, j} \neq i

A_{i, 1}, A_{i, 2}, \ldots, A_{i, N-1} are all different.

Input

Input is given from Standard Input in the following format:

N
A_{1, 1} A_{1, 2} \ldots A_{1, N-1}
A_{2, 1} A_{2, 2} \ldots A_{2, N-1}
:
A_{N, 1} A_{N, 2} \ldots A_{N, N-1}

Output

If it is possible to schedule all the matches so that all of the conditions are satisfied, print the minimum number of days required; if it is impossible, print -1.

Sample Input 1

3
2 3
1 3
1 2

Sample Output 1

3

All the conditions can be satisfied if the matches are scheduled for three days as follows:

Day 1: Player 1 vs Player 2

Day 2: Player 1 vs Player 3

Day 3: Player 2 vs Player 3

This is the minimum number of days required.

Sample Input 2

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

Sample Output 2

4

All the conditions can be satisfied if the matches are scheduled for four days as follows:

Day 1: Player 1 vs Player 2, Player 3 vs Player 4

Day 2: Player 1 vs Player 3

Day 3: Player 1 vs Player 4, Player 2 vs Player 3

Day 4: Player 2 vs Player 4

This is the minimum number of days required.

Sample Input 3

3
2 3
3 1
1 2

Sample Output 3

-1

Any scheduling of the matches violates some condition.


Score : 200 points

Problem Statement

Today is August 24, one of the five Product Days in a year.

A date m-d (m is the month, d is the date) is called a Product Day when d is a two-digit number, and all of the following conditions are satisfied (here d_{10} is the tens digit of the day and d_1 is the ones digit of the day):

d_1 \geq 2

d_{10} \geq 2

d_1 \times d_{10} = m

Takahashi wants more Product Days, and he made a new calendar called Takahashi Calendar where a year consists of M month from Month 1 to Month M, and each month consists of D days from Day 1 to Day D.

In Takahashi Calendar, how many Product Days does a year have?

Constraints

All values in input are integers.

1 \leq M \leq 100

1 \leq D \leq 99

Input

Input is given from Standard Input in the following format:

M D

Output

Print the number of Product Days in a year in Takahashi Calender.

Sample Input 1

15 40

Sample Output 1

10

There are 10 Product Days in a year, as follows (m-d denotes Month m, Day d):

4-22

6-23

6-32

8-24

9-33

10-25

12-26

12-34

14-27

15-35

Sample Input 2

12 31

Sample Output 2

5

Sample Input 3

1 1

Sample Output 3

0


<?php

$a = trim(fgets(STDIN));
$nums = explode(' ', trim(fgets(STDIN)));

$sum = 0;
foreach ($nums as $n) {
    $sum += 1 / $n;
}

echo 1 / $sum;

Score : 200 points

Problem Statement

Given is a sequence of N integers A_1, \ldots, A_N.

Find the (multiplicative) inverse of the sum of the inverses of these numbers, \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Constraints

1 \leq N \leq 100

1 \leq A_i \leq 1000

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \ldots A_N

Output

Print a decimal number (or an integer) representing the value of \frac{1}{\frac{1}{A_1} + \ldots + \frac{1}{A_N}}.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
10 30

Sample Output 1

7.5

\frac{1}{\frac{1}{10} + \frac{1}{30}} = \frac{1}{\frac{4}{30}} = \frac{30}{4} = 7.5.

Printing 7.50001, 7.49999, and so on will also be accepted.

Sample Input 2

3
200 200 200

Sample Output 2

66.66666666666667

\frac{1}{\frac{1}{200} + \frac{1}{200} + \frac{1}{200}} = \frac{1}{\frac{3}{200}} = \frac{200}{3} = 66.6666....

Printing 6.66666e+1 and so on will also be accepted.

Sample Input 3

1
1000

Sample Output 3

1000

\frac{1}{\frac{1}{1000}} = 1000.

Printing +1000.0 and so on will also be accepted.


<?php
  $input = (int)fgets(STDIN);

$nums = explode(" ", fgets(STDIN));

foreach($nums as &$num){
	$num = (int)$num;
}
unset($num);

$ans = 0;
foreach($nums as &$num){
	$num = 1 / $num;
  $ans += $num;
}

$ans = 1/ $ans;

echo $ans;


<?php
// Your code here!
$N = (int)fgets(STDIN);
$v = fgets(STDIN);
$v = explode(' ',$v);
$v1 = (int)$v[0];
// echo $v1;
$v2 = (int)$v[1];
$a = ($v1+$v2)/2;
echo $a;
?>

Score : 300 points

Problem Statement

You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i.

When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where x and y are the values of the ingredients consumed, and you can put this ingredient again in the pot.

After you compose ingredients in this way N-1 times, you will end up with one ingredient. Find the maximum possible value of this ingredient.

Constraints

2 \leq N \leq 50

1 \leq v_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
v_1 v_2 \ldots v_N

Output

Print a decimal number (or an integer) representing the maximum possible value of the last ingredient remaining.

Your output will be judged correct when its absolute or relative error from the judge's output is at most 10^{-5}.

Sample Input 1

2
3 4

Sample Output 1

3.5

If you start with two ingredients, the only choice is to put both of them in the pot. The value of the ingredient resulting from the ingredients of values 3 and 4 is (3 + 4) / 2 = 3.5.

Printing 3.50001, 3.49999, and so on will also be accepted.

Sample Input 2

3
500 300 200

Sample Output 2

375

You start with three ingredients this time, and you can choose what to use in the first composition. There are three possible choices:

Use the ingredients of values 500 and 300 to produce an ingredient of value (500 + 300) / 2 = 400. The next composition will use this ingredient and the ingredient of value 200, resulting in an ingredient of value (400 + 200) / 2 = 300.

Use the ingredients of values 500 and 200 to produce an ingredient of value (500 + 200) / 2 = 350. The next composition will use this ingredient and the ingredient of value 300, resulting in an ingredient of value (350 + 300) / 2 = 325.

Use the ingredients of values 300 and 200 to produce an ingredient of value (300 + 200) / 2 = 250. The next composition will use this ingredient and the ingredient of value 500, resulting in an ingredient of value (250 + 500) / 2 = 375.

Thus, the maximum possible value of the last ingredient remaining is 375.

Printing 375.0 and so on will also be accepted.

Sample Input 3

5
138 138 138 138 138

Sample Output 3

138


<?php

$n = trim(fgets(STDIN));
$m = explode(' ', trim(fgets(STDIN)));

while (count($m) > 1) {
    sort($m);
    $x = array_shift($m);
    $y = array_shift($m);
    $m[] = ($x + $y) / 2;
}

echo current($m) . ".\n";


<?php

$n = trim(fgets(STDIN));

$a = array_map('intval',explode(' ', trim(fgets(STDIN))));
sort($a);

$sum = ($a[0] + $a[1]) / 2;
for($i = 2;$i < $n;$i++) {
	$sum = ($sum + $a[$i]) / 2;
}
echo $sum."\n";


<?php
fscanf(STDIN, "%d %d", $a, $b);
echo max($a + $b, $a - $b, $a * $b);

Score : 100 points

Problem Statement

We have two integers: A and B.

Print the largest number among A + B, A - B, and A \times B.

Constraints

All values in input are integers.

-100 \leq A,\ B \leq 100

Input

Input is given from Standard Input in the following format:

A B

Output

Print the largest number among A + B, A - B, and A \times B.

Sample Input 1

-13 3

Sample Output 1

-10

The largest number among A + B = -10, A - B = -16, and A \times B = -39 is -10.

Sample Input 2

1 -33

Sample Output 2

34

The largest number among A + B = -32, A - B = 34, and A \times B = -33 is 34.

Sample Input 3

13 3

Sample Output 3

39

The largest number among A + B = 16, A - B = 10, and A \times B = 39 is 39.


<?php

$n = intval(trim(fgets(STDIN)));

$count=0.0;
$array = [];
for ($i=0; $i<$n; $i++) {
    $str = trim(fgets(STDIN));
    $sArr = str_split($str);
    sort($sArr);
    $newS = implode('',$sArr);

    foreach ($array as $s) {
        if ( strcmp($s, $array[$j]) == 0 ) {
            $count++;
        }
    }

    $array[] = $newS;
}

echo "$count\n";


<?php
// Your code here!
$input = fgets(STDIN);
$number_array = explode(' ', $input);
$sum = $number_array[0] + $number_array[1];
$substruction = $number_array[0] - $number_array[1];
$square = $number_array[0] * $number_array[1];

echo max($sum, $substruction, $square);
?>


<?php
  $N = intval(trim(fgets(STDIN)));

  $sorted_count = [];
  $ans = 0;

  for($i=0; $i<$N; $i++){
    # 文字列をアルファベット順にソートする
    $word = str_split(trim(fgets(STDIN)));
    sort($word);

    # 文字列に戻す
    $word = implode($word);

    # 既に出てきてる単語かチェック
    if (!array_key_exists($word, $sorted_count)) {
      # なければ初出なので、１個目としてカウント
      $sorted_count[$word] = 1;
    }else {
      # これまで出てきてる個数を答えにふやす。
      $ans += $sorted_count[$word];
      # 出現回数を一つふやす
      $sorted_count[$word] += 1;
    }
  }
  echo $ans;

?>

Score : 300 points

Problem Statement

We will call a string obtained by arranging the characters contained in a string a in some order, an anagram of a.

For example, greenbin is an anagram of beginner. As seen here, when the same character occurs multiple times, that character must be used that number of times.

Given are N strings s_1, s_2, \ldots, s_N. Each of these strings has a length of 10 and consists of lowercase English characters. Additionally, all of these strings are distinct. Find the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Constraints

2 \leq N \leq 10^5

s_i is a string of length 10.

Each character in s_i is a lowercase English letter.

s_1, s_2, \ldots, s_N are all distinct.

Input

Input is given from Standard Input in the following format:

N
s_1
s_2
:
s_N

Output

Print the number of pairs of integers i, j (1 \leq i < j \leq N) such that s_i is an anagram of s_j.

Sample Input 1

3
acornistnt
peanutbomb
constraint

Sample Output 1

1

s_1 = acornistnt is an anagram of s_3 = constraint. There are no other pairs i, j such that s_i is an anagram of s_j, so the answer is 1.

Sample Input 2

2
oneplustwo
ninemodsix

Sample Output 2

0

If there is no pair i, j such that s_i is an anagram of s_j, print 0.

Sample Input 3

5
abaaaaaaaa
oneplustwo
aaaaaaaaba
twoplusone
aaaabaaaaa

Sample Output 3

4

Note that the answer may not fit into a 32-bit integer type, though we cannot put such a case here.


<?php
$n = trim(fgets(STDIN));
for($i=0; $i<$n; $i++){
    $arr[] = trim(fgets(STDIN));
    $a = str_split($arr[$i]);
    natsort($a);
    $str[] = implode($a);
}

$ans = 0;
$count = array_count_values($str);

foreach ($count as $value) {
    if($value > 1){
        for($s=1; $s<$value; $s++){
            $ans += $value-$s;
        }
    }
}

print_r($ans);

?>


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

$arr = [];

for(; $n>0; $n--){
  fscanf(STDIN, "%s", $s);

  $split = str_split($s);
  sort($split);
  $sorted = implode('', $split);

  $arr[$sorted] = isset($arr[$sorted])? $arr[$sorted]+1 : 1;
}

$cnt = 0;
foreach($arr as $str){
  if($str === 1) continue;

  $a = factorial($str);
  $b = 2;
  $cnt += $a / ($b*factorial($str-$b));
}

echo $cnt, "\n";

function factorial($num){
  return ($num === 0)? 1 : array_product(range(1,$num));
}


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($N,$M) =  explode(" ",trim(fgets(STDIN)));
//$H =  explode(" ",trim(fgets(STDIN)));
for($i=0;$i<$N;$i++) {
  list($A,$B) =  explode(" ",trim(fgets(STDIN)));
  $m[$M-$A][]=$B;
}
$pq = new SplPriorityQueue();
$pq->setExtractFlags(SplPriorityQueue::EXTR_PRIORITY);
$res=0;
for($i=$M;$i>=0;$i--) {
  if (isset($m[$i])) {
    foreach($m[$i] as $v) {
      $pq->insert($v,$v);
    }
  }
  if ($pq->isEmpty()==false) {
    $res += $pq->extract();
  }
}
printf("%d\n",$res);

Score : 400 points

Problem Statement

There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it.

You can take and complete at most one of these jobs in a day.

However, you cannot retake a job that you have already done.

Find the maximum total reward that you can earn no later than M days from today.

You can already start working today.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq A_i \leq 10^5

1 \leq B_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the maximum total reward that you can earn no later than M days from today.

Sample Input 1

3 4
4 3
4 1
2 2

Sample Output 1

5

You can earn the total reward of 5 by taking the jobs as follows:

Take and complete the first job today. You will earn the reward of 3 after four days from today.

Take and complete the third job tomorrow. You will earn the reward of 2 after two days from tomorrow, that is, after three days from today.

Sample Input 2

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

Sample Output 2

10

Sample Input 3

1 1
2 1

Sample Output 3

0


<?php

//文字列の入力
fscanf(STDIN,"%d %d %d",$a,$b,$c);

//容器１に容器２から入れることのできる量
$max = $a - $b;

if ($max >= $c){
    echo 0;
}else{
    $total = $c - $max;
    echo $total;
}

Score : 100 points

Problem Statement

We have two bottles for holding water.

Bottle 1 can hold up to A milliliters of water, and now it contains B milliliters of water.

Bottle 2 contains C milliliters of water.

We will transfer water from Bottle 2 to Bottle 1 as much as possible.

How much amount of water will remain in Bottle 2?

Constraints

All values in input are integers.

1 \leq B \leq A \leq 20

1 \leq C \leq 20

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the integer representing the amount of water, in milliliters, that will remain in Bottle 2.

Sample Input 1

6 4 3

Sample Output 1

1

We will transfer two milliliters of water from Bottle 2 to Bottle 1, and one milliliter of water will remain in Bottle 2.

Sample Input 2

8 3 9

Sample Output 2

4

Sample Input 3

12 3 7

Sample Output 3

0


<?php
// Your code here!
    $arr = array_map("intval", explode(" ", fgets(STDIN)));
    echo max(0, $arr[2] - ($arr[0] - $arr[1])) . PHP_EOL;

?>


<?php
  list[$a,$b,$c] = explode(" ",fgets(STDIN));
	if($a >= ($b +$c)) {
      echo 0;
    }
	else {
      echo $c+$b-$a;
    }
?>


<?php
list($a, $b, $c) = ints();
echo max(0, $c-($a-$b));

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function o(...$val){
    if(count($val)==1)$val = array_shift($val);
    $trace = debug_backtrace();
    echo $trace[0]['line'].")";
    if(is_array($val)){
        if(count($val) == 0){
            echo "empty array";
        }elseif(!is_array(current($val))){
            echo "array:";
            echo implode(" ", $val)."\n";
        }else{
            echo "array:array\n";
            foreach($val as $row){
                echo implode(" ", $row)."\n";
            }
        }
    }else{
        echo $val."\n";
    }
}


Score : 200 points

Problem Statement

Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros).

Constraints

1 \leq N \leq 10^5

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of positive integers less than or equal to N that have an odd number of digits.

Sample Input 1

11

Sample Output 1

9

Among the positive integers less than or equal to 11, nine integers have an odd number of digits: 1, 2, \ldots, 9.

Sample Input 2

136

Sample Output 2

46

In addition to 1, 2, \ldots, 9, another 37 integers also have an odd number of digits: 100, 101, \ldots, 136.

Sample Input 3

100000

Sample Output 3

90909


<?php
$RL=str_split(fgets(STDIN));
$oddList=array_fill(0, count($RL), 1);
$evenList=array_fill(0, count($RL), 0);
$keepList=$oddList;
$cnt=0;

while(true){
  $temp=array_fill(0, count($keepList), 0);
  foreach($RL as $k => $v){
    if($v=='R'){
      $temp[$k+1]+=$keepList[$k];
    }else{
      $temp[$k-1]+=$keepList[$k];
    }
  }
  $cnt++;
  if($cnt%2==1){
    if($oddList==$temp){
      break;
    }
    $oddList=$temp;
  }else{
    if($evenList==$temp){
      break;
    }
    $evenList=$temp;
  }
  $keepList=$temp;
}
echo implode($evenList);

Score : 400 points

Problem Statement

Given is a string S consisting of L and R.

Let N be the length of S. There are N squares arranged from left to right, and the i-th character of S from the left is written on the i-th square from the left.

The character written on the leftmost square is always R, and the character written on the rightmost square is always L.

Initially, one child is standing on each square.

Each child will perform the move below 10^{100} times:

Move one square in the direction specified by the character written in the square on which the child is standing. L denotes left, and R denotes right.

Find the number of children standing on each square after the children performed the moves.

Constraints

S is a string of length between 2 and 10^5 (inclusive).

Each character of S is L or R.

The first and last characters of S are R and L, respectively.

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of children standing on each square after the children performed the moves, in order from left to right.

Sample Input 1

RRLRL

Sample Output 1

0 1 2 1 1

After each child performed one move, the number of children standing on each square is 0, 2, 1, 1, 1 from left to right.

After each child performed two moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

After each child performed 10^{100} moves, the number of children standing on each square is 0, 1, 2, 1, 1 from left to right.

Sample Input 2

RRLLLLRLRRLL

Sample Output 2

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

Sample Input 3

RRRLLRLLRRRLLLLL

Sample Output 3

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


<?php

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

$result = ($a + $b) / 2;
echo is_int($result) ? $result : 'IMPOSSIBLE';

Score: 100 points

Problem Statement

We have two distinct integers A and B.

Print the integer K such that |A - K| = |B - K|.

If such an integer does not exist, print IMPOSSIBLE instead.

Constraints

All values in input are integers.

0 \leq A,\ B \leq 10^9

A and B are distinct.

Input

Input is given from Standard Input in the following format:

A B

Output

Print the integer K satisfying the condition.

If such an integer does not exist, print IMPOSSIBLE instead.

Sample Input 1

2 16

Sample Output 1

9

|2 - 9| = 7 and |16 - 9| = 7, so 9 satisfies the condition.

Sample Input 2

0 3

Sample Output 2

IMPOSSIBLE

No integer satisfies the condition.

Sample Input 3

998244353 99824435

Sample Output 3

549034394


<?php

  fscanf("$d $d", $a, $b);
  $abs = abs($a - $b);

  if($abs%2 === 1) {
  	echo "IMPOSSIBLE";
  } else {
    echo min($a, $b) + $abs / 2;
  }


<?php

# スペース区切りの整数の入力
fscanf(STDIN, "%d %d", $a, $b);

$k = ($a + $b)/2;

if(is_int($k) === false){
    echo "IMPOSSIBLE", PHP_EOL ;
}else{
    echo "$k", PHP_EOL ;
}


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($A,$B) =  explode(" ",trim(fgets(STDIN)));
//$d =  explode(" ",trim(fgets(STDIN)));

$K = abs($A-$B);
if (($K % 2) == 1)
  printf("IMPOSSIBLE\n");
else
printf("%d\n",abs($A - ($K/2)));


<?php
  /*
$x = explode(" ",trim(fgets(STDIN)));
sort($x);

for ($i=0;$i<$x[1];$i++){
if(abs($x[0]-$i)==abs($x[1]-$i)){
echo $i;
exit;
}
}
echo 'IMPOSSIBLE';
*/
$N =trim(fgets(STDIN));
$p = explode(" ",trim(fgets(STDIN)));
$c=0;
for($i=0;$i<$N;++$i){
if($p[$i]!=$i+1){
++$c;
}
}

if($c<=2){
echo 'YES';
}else{
echo 'NO';
}

Score : 200 points

Problem Statement

We have a sequence p = {p_1,\ p_2,\ ...,\ p_N} which is a permutation of {1,\ 2,\ ...,\ N}.

You can perform the following operation at most once: choose integers i and j (1 \leq i < j \leq N), and swap p_i and p_j. Note that you can also choose not to perform it.

Print YES if you can sort p in ascending order in this way, and NO otherwise.

Constraints

All values in input are integers.

2 \leq N \leq 50

p is a permutation of {1,\ 2,\ ...,\ N}.

Input

Input is given from Standard Input in the following format:

N
p_1 p_2 ... p_N

Output

Print YES if you can sort p in ascending order in the way stated in the problem statement, and NO otherwise.

Sample Input 1

5
5 2 3 4 1

Sample Output 1

YES

You can sort p in ascending order by swapping p_1 and p_5.

Sample Input 2

5
2 4 3 5 1

Sample Output 2

NO

In this case, swapping any two elements does not sort p in ascending order.

Sample Input 3

7
1 2 3 4 5 6 7

Sample Output 3

YES

p is already sorted in ascending order, so no operation is needed.


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

  $arrayA = explode(" ", trim(fgets(STDIN)));
  $arrayB = explode(" ", trim(fgets(STDIN)));

  $total = 0;
  for($i=0; $i<$n; $i++){
    if($arrayA[$i]>$arrayB[$i]){
      $total += $arrayB[$i];
    }else{
      $total += $arrayA[$i];
      $arrayB[$i] -= $arrayA[$i];

      if($arrayB[$i]>0){
        if($arrayA[$i+1]>$arrayB[$i]){
          $total += $arrayB[$i];
        }else{
          $total += $arrayA[$i+1];
        }
      }
    }
  }

  echo $total."\n";

Score : 300 points

Problem Statement

There are N+1 towns. The i-th town is being attacked by A_i monsters.

We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.

What is the maximum total number of monsters the heroes can cooperate to defeat?

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_{N+1}
B_1 B_2 ... B_N

Output

Print the maximum total number of monsters the heroes can defeat.

Sample Input 1

2
3 5 2
4 5

Sample Output 1

9

If the heroes choose the monsters to defeat as follows, they can defeat nine monsters in total, which is the maximum result.

The first hero defeats two monsters attacking the first town and two monsters attacking the second town.

The second hero defeats three monsters attacking the second town and two monsters attacking the third town.

Sample Input 2

3
5 6 3 8
5 100 8

Sample Output 2

22

Sample Input 3

2
100 1 1
1 100

Sample Output 3

3


<?php
$n = int();
$aArray = ints();
$bArray = ints();

$left = $aArray[0];
$total = 0;
for($i = 1; $i <= $n; $i++){
  $left+=$aArray[$i];
  $kill = min($left, $bArray[$i-1]);
  $left = min($left, $aArray[$i]);
  $total+=$kill;
}
echo $total;

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function o(...$val){
    if(count($val)==1)$val = array_shift($val);
    $trace = debug_backtrace();
    echo $trace[0]['line'].")";
    if(is_array($val)){
        if(count($val) == 0){
            echo "empty array";
        }elseif(!is_array(current($val))){
            echo "array:";
            echo implode(" ", $val)."\n";
        }else{
            echo "array:array\n";
            foreach($val as $row){
                echo implode(" ", $row)."\n";
            }
        }
    }else{
        echo $val."\n";
    }
}


<?php
define("MOD", 10**9+7);
$str = str_split(str());
$n = count($str);
for($j = 0; $j < 13; $j++){
  $dp[$n-1][$j] = 0;
}
if($str[$n-1] == "?"){
  for($i = 0; $i < 10; $i++){
    $dp[$n-1][$i] = 1;
  }
}else{
  $dp[$n-1][$str[$n-1]] = 1;
}
$c = 0;
$m = 1;
for($i = $n-2; $i>=0; --$i){
  $m*=10;
  $m%=13;
  for($j = 0; $j < 13; ++$j){
    $dp[$i][$j] = 0;
  }
  $dpi = &$dp[$i];
  $dpip = $dp[$i+1];
  if($str[$i] != "?"){
    $diff = $m*intval($str[$i])%13;
    for($j = 0; $j < 13; ++$j){
      $dpi[($j+$diff)%13] = $dpip[$j];
    }
  }else{
    for($k = 0; $k < 10; ++$k){
      $diff = $m*intval($k)%13;
      for($j = 0; $j < 13; ++$j){
        $dpi[($j+$diff)%13] += $dpip[$j];
        $c+=$dpip[$j];
      }
    }
  }
  for($j = 0; $j < 13; $j++){
    $dp[$i][$j] = $dp[$i][$j] % MOD;
  }
}
echo $dp[0][5];

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function o(...$val){
    if(count($val)==1)$val = array_shift($val);
    $trace = debug_backtrace();
    echo $trace[0]['line'].")";
    if(is_array($val)){
        if(count($val) == 0){
            echo "empty array";
        }elseif(!is_array(current($val))){
            echo "array:";
            echo implode(" ", $val)."\n";
        }else{
            echo "array:array\n";
            foreach($val as $row){
                echo implode(" ", $row)."\n";
            }
        }
    }else{
        echo $val."\n";
    }
}

Score : 400 points

Problem Statement

Given is a string S. Each character in S is either a digit (0, ..., 9) or ?.

Among the integers obtained by replacing each occurrence of ? with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.

Since the answer can be enormous, print the count modulo 10^9+7.

Constraints

S is a string consisting of digits (0, ..., 9) and ?.

1 \leq |S| \leq 10^5

Input

Input is given from Standard Input in the following format:

S

Output

Print the number of integers satisfying the condition, modulo 10^9+7.

Sample Input 1

??2??5

Sample Output 1

768

For example, 482305, 002865, and 972665 satisfy the condition.

Sample Input 2

?44

Sample Output 2

1

Only 044 satisfies the condition.

Sample Input 3

7?4

Sample Output 3

0

We may not be able to produce an integer satisfying the condition.

Sample Input 4

?6?42???8??2??06243????9??3???7258??5??7???????774????4?1??17???9?5?70???76???

Sample Output 4

153716888


Score : 400 points

Problem Statement

Given is an integer S.
Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:

0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9

The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.

We can prove that there always exist six integers that satisfy the conditions under the constraints of this problem.

Constraints

1 \leq S \leq 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

S

Output

Print six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfy the conditions, in this order, with spaces in between.
If multiple solutions exist, any of them will be accepted.

Sample Input 1

3

Sample Output 1

1 0 2 2 0 1

The area of the triangle in a two-dimensional plane whose vertices are (1,0),(2,2), and (0,1) is 3/2.
Printing 3 0 3 1 0 1 or 1 0 0 1 2 2 will also be accepted.

Sample Input 2

100

Sample Output 2

0 0 10 0 0 10

Sample Input 3

311114770564041497

Sample Output 3

314159265 358979323 846264338 327950288 419716939 937510582


<?php
while ($line = fgets(STDIN)) {
    $tmp[] = trim($line);
}

$menseki = $tmp[0];
$sqrt = sqrt($menseki);

if ($menseki % 2) {
    $x = 1;
    $y = $menseki;
} else {
    $x = 2;
    $y = $menseki / 2;
}

if(is_int($sqrt)){
    $x = $sqrt;
    $y = $sqrt;
}
$limit = $sqrt / 2;
for ($i = 3; $i < $limit; $i += 2) {
    if ($menseki % $i == 0) {
        $x = $i;
        $y = $menseki / $i;
    }
}
echo "0 0 " . $x . " 0 0 " . $y;


<?php
$n = int();
$sqrtN = sqrt($n);
$a = ceil($sqrtN);
$d = ceil($sqrtN);
$left = $a*$d - $n;
if($left == 0){
  $b = 0;
  $c = 0;
}else{
  $b = 1;
  $c = $left;
}

echo "0 0 $a $b $c $d";

function factor($M){
    $f = [];
    $rootM = $M**0.5+1;
    for($j = 2; $j <= $rootM; $j++){
        if($M%$j == 0){
            $f[] = $j;
            $M/=$j;
            $rootM = $M**0.5+1;
            $j--;
        }
    }
    if($M>1){
        $f[] = $M;
    }
    return $f;
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}


<?php
$input = fgets(STDIN);
$area = 3 * pow($input, 2);
echo $area . "\n";

Score : 100 points

Problem Statement

It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2.

Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r.

Constraints

1 \leq r \leq 100

r is an integer.

Input

Input is given from Standard Input in the following format:

r

Output

Print an integer representing the area of the regular dodecagon.

Sample Input 1

4

Sample Output 1

48

The area of the regular dodecagon is 3 \times 4^2 = 48.

Sample Input 2

15

Sample Output 2

675

Sample Input 3

80

Sample Output 3

19200


<?php
fscanf(STDIN, "%d", $a);
$result = 3 * pow($a, 2);
echo $result."\n";
?>


<?php

$inputs = explode(' ',trim(fgets(STDIN)));

$answer = ceil($inputs[0] / ($inputs[1] + $inputs[1] + 1));
print $answer;

Score : 200 points

Problem Statement

There are N apple trees in a row. People say that one of them will bear golden apples.

We want to deploy some number of inspectors so that each of these trees will be inspected.

Each inspector will be deployed under one of the trees. For convenience, we will assign numbers from 1 through N to the trees. An inspector deployed under the i-th tree (1 \leq i \leq N) will inspect the trees with numbers between i-D and i+D (inclusive).

Find the minimum number of inspectors that we need to deploy to achieve the objective.

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq D \leq 20

Input

Input is given from Standard Input in the following format:

N D

Output

Print the minimum number of inspectors that we need to deploy to achieve the objective.

Sample Input 1

6 2

Sample Output 1

2

We can achieve the objective by, for example, placing an inspector under Tree 3 and Tree 4.

Sample Input 2

14 3

Sample Output 2

2

Sample Input 3

20 4

Sample Output 3

3


<?php
  fscanf(STDIN, "%d", $n);
  $a = [];
  $max = -1;
  $second_max = -1;
  for ($i=0; $i<$n; $i++) {
    fscanf(STDIN, "%d", $a_);
    $a[] = $a_;

    # マックス値と次に大きな値を保存しておく
    if ($a_ > $max) {
      $second_max = $max;
      $max = $a_;
    } else if ($a_ > $second_max) {
      $second_max = $a_;
    }
  }

  # マックス値と同じなら次に大きな値を出力
  # そうでないならマックス値
  for ($i=0; $i<$n; $i++) {
    if ($a[$i] == $max) echo $second_max . "\n";
    else echo $max . "\n";
  }
?>

Score : 300 points

Problem Statement

You are given a sequence of length N: A_1, A_2, ..., A_N.
For each integer i between 1 and N (inclusive), answer the following question:

Find the maximum value among the N-1 elements other than A_i in the sequence.

Constraints

2 \leq N \leq 200000

1 \leq A_i \leq 200000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print N lines. The i-th line (1 \leq i \leq N) should contain the maximum value among the N-1 elements other than A_i in the sequence.

Sample Input 1

3
1
4
3

Sample Output 1

4
3
4

The maximum value among the two elements other than A_1, that is, A_2 = 4 and A_3 = 3, is 4.

The maximum value among the two elements other than A_2, that is, A_1 = 1 and A_3 = 3, is 3.

The maximum value among the two elements other than A_3, that is, A_1 = 1 and A_2 = 4, is 4.

Sample Input 2

2
5
5

Sample Output 2

5
5


<?php
$n = intval(trim(fgets(STDIN)));
for ($i = 0; $i < $n; ++$i) {
    $a[$i] = intval(trim(fgets(STDIN)));
    $b[$i] = $a[$i];
    $sai = max($a);
}

echo PHP_EOL;

for ($i = 0; $i < $n; ++$i) {
    if ($sai > $a[$i])  {
        $max = $sai;
    } elseif ($sai == $a[$i]) {
        sort($b);
        $max = $b[1];
    }
    echo $max . PHP_EOL;
}

?>


<?php

while ($line = fgets(STDIN)) {
   $stdin[] = trim($line);
}
#$v2 = str_split($stdin[0]);
#$v2 = explode(" ", $stdin[0]);

#var_dump($stdin);

unset($stdin[0]);

$max = max($stdin);

$ans = NULL;

foreach($stdin as $k => $v){
  if($v == $max){
    $array = array();
    $array = $stdin;
    unset($array[$k]);
    $ans .= max($array) . PHP_EOL;
  }else{
    $ans .= $max . PHP_EOL;
  }
}

echo $ans . PHP_EOL;


<?php
# 入力
fscanf(STDIN, '%d', $n);
$a = array_merge([0], array_map('intval', explode(" ", trim(fgets(STDIN)))));
$b = [];
$result = [];
for ($i = $n; $i > 0; $i--) {
    $sum = 0;
    for ($j = 2; $i * $j <= $n; $j++) {
        if (isset($b[$i * $j])) {
            $sum++;
        }
    }
    if ($sum % 2 != $a[$i]) {
        $b[$i] = true;
        $result[] = $i;
    }
}
$cnt = count($b);
echo $cnt.PHP_EOL;
if ($cnt > 0) {
    echo implode(" ", $result).PHP_EOL;
}
?>

Score : 400 points

Problem Statement

There are N empty boxes arranged in a row from left to right.
The integer i is written on the i-th box from the left (1 \leq i \leq N).

For each of these boxes, Snuke can choose either to put a ball in it or to put nothing in it.

We say a set of choices to put a ball or not in the boxes is good when the following condition is satisfied:

For every integer i between 1 and N (inclusive), the total number of balls contained in the boxes with multiples of i written on them is congruent to a_i modulo 2.

Does there exist a good set of choices? If the answer is yes, find one good set of choices.

Constraints

All values in input are integers.

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

a_i is 0 or 1.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

If a good set of choices does not exist, print -1.

If a good set of choices exists, print one such set of choices in the following format:

M
b_1 b_2 ... b_M

where M denotes the number of boxes that will contain a ball, and b_1,\ b_2,\ ...,\ b_M are the integers written on these boxes, in any order.

Sample Input 1

3
1 0 0

Sample Output 1

1
1

Consider putting a ball only in the box with 1 written on it.

There are three boxes with multiples of 1 written on them: the boxes with 1, 2, and 3. The total number of balls contained in these boxes is 1.

There is only one box with a multiple of 2 written on it: the box with 2. The total number of balls contained in these boxes is 0.

There is only one box with a multiple of 3 written on it: the box with 3. The total number of balls contained in these boxes is 0.

Thus, the condition is satisfied, so this set of choices is good.

Sample Input 2

5
0 0 0 0 0

Sample Output 2

0

Putting nothing in the boxes can be a good set of choices.


<?php

fscanf(STDIN, "%d", $n);

$array = explode(" ", trim(fgets(STDIN)));

$half = intdiv($n, 2);

for($i=$n-1;$i>$half;$i--){

    if($array[$i] == 1){
        $box[$i+1] = $i+1;
    }

}
$short = intdiv($half, 5);
for($i = $half; $i >$short; $i--){
    $check = ($i+1)*2;
    $flag = 0;
    while($check <= $n){
        $flag = ($flag + isset($box[$check])?1:0)%2;
        $check = $check * 2;
    }
    if(($flag && $array[$i] == 0) || !$flag && $array[$i] == 1){
        $box[$i+1] = $i+1;
    }
}

for($i = $short; $i >0; $i--){
    $check = ($i+1);
    $double = $check*2;
    if(isset($box[$double])){
        $flag = 1;
    }else{
        $flag = 0;
    }
    $loop = $check + $double;
    while($loop <= $n){
        $flag = ($flag + isset($box[$loop])?1:0)%2;
        $loop = $loop + $double;
    }
    if(($flag && $array[$i] == 0) || !$flag && $array[$i] == 1){
        $box[$i+1] = $i+1;
    }
}
if(isset($box)) {
    $m = count($box);
}else{
    $m = 0;
    $p = 1;
}
$num = $m % 2;
if($array[0] == 1){
    if($num == 0){
        $box[1] = 1;
        $m++;
    }
}elseif($num == 1){
    $box[1] = 1;
    $m++;
}

echo $m.PHP_EOL;
if($m == 0){
    echo 0;
}else{
    echo implode(" ", $box);
}


<?php
list($n) = ints();
for ($i = 0; $i < $n; ++$i) list($a[]) = ints();
// 同じ色で塗れるマスをグループ分けした時のグループごとの末尾の値を格納
// この数より大きい数字であればこのグループに入れられる
$ends = [$a[0]];
for ($i = 1; $i < $n; ++$i) {
    // 二分探索で入れられるグループのうち末尾の値が最大のものを探す
    // endsは常にソート済（降順）
    $l = count($ends);
    $ok = $l;
    $ng = -1;
    while (abs($ok - $ng) > 1) {
        $mid = intdiv($ok + $ng, 2);
        if ($ends[$mid] < $a[$i]) $ok = $mid;
        else $ng = $mid;
    }
    // 見つからない場合はok=lなので要素が追加される
    $ends[$ok] = $a[$i];
}
echo count($ends);
function ints()
{
    return array_map('intval', explode(' ', trim(fgets(STDIN))));
}

Score : 500 points

Problem Statement

You are given a sequence with N integers: A = \{ A_1, A_2, \cdots, A_N \}.
For each of these N integers, we will choose a color and paint the integer with that color. Here the following condition must be satisfied:

If A_i and A_j (i < j) are painted with the same color, A_i < A_j.

Find the minimum number of colors required to satisfy the condition.

Constraints

1 \leq N \leq 10^5

0 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the minimum number of colors required to satisfy the condition.

Sample Input 1

5
2
1
4
5
3

Sample Output 1

2

We can satisfy the condition with two colors by, for example, painting 2 and 3 red and painting 1, 4, and 5 blue.

Sample Input 2

4
0
0
0
0

Sample Output 2

4

We have to paint all the integers with distinct colors.


<?php
$n = intval(fgets(STDIN));
$maxLen = 0;
$currentLen = 0;
$currentNum = 10**10;
for($i = 0; $i < $n; $i++){
  $a = intval(fgets(STDIN));
  if($a <= $currentNum){
    $currentNum = $a;
    $currentLen++;
    $maxLen = max($maxLen, $currentLen);
  }else{
    $currentLen = 1;
    $currentNum = 10**10;
  }
}
echo $maxLen;


Score : 100 points

Problem Statement

N of us are going on a trip, by train or taxi.

The train will cost each of us A yen (the currency of Japan).

The taxi will cost us a total of B yen.

How much is our minimum total travel expense?

Constraints

All values in input are integers.

1 \leq N \leq 20

1 \leq A \leq 50

1 \leq B \leq 50

Input

Input is given from Standard Input in the following format:

N A B

Output

Print an integer representing the minimum total travel expense.

Sample Input 1

4 2 9

Sample Output 1

8

The train will cost us 4 \times 2 = 8 yen, and the taxi will cost us 9 yen, so the minimum total travel expense is 8 yen.

Sample Input 2

4 2 7

Sample Output 2

7

Sample Input 3

4 2 8

Sample Output 3

8


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

$r = $a * $b;

if($r >= $c){
    echo $c;
}else{
    echo $r;
}


<?php
  function dis($x,$y){
    $len = count($x);
    $total = 0;
    for($i=0; $i<$len; $i++){
      $sa = abs($x[$i]-$y[$i]);
      $total += $sa*$sa;
    }
    $total = sqrt($total);
    $total_int = (int)($total);
    return ($total == $total_int);
  }

  fscanf(STDIN,"%d %d",$n,$d);
  while($line= trim(fgets(STDIN)) ){
   $x[] = explode(" ",$line);
  }
  $count = 0;
  for($i=0; $i<$n; $i++){
    if($i < $n-1){
      $t = $i+1;
    }else{
      $t = 0;
    }

    if( dis($x[$i],$x[$t]) ){
      $count++;
    }
  }

  echo $count."\n";

Score : 200 points

Problem Statement

There are N points in a D-dimensional space.

The coordinates of the i-th point are (X_{i1}, X_{i2}, ..., X_{iD}).

The distance between two points with coordinates (y_1, y_2, ..., y_D) and (z_1, z_2, ..., z_D) is \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2 + ... + (y_D - z_D)^2}.

How many pairs (i, j) (i < j) are there such that the distance between the i-th point and the j-th point is an integer?

Constraints

All values in input are integers.

2 \leq N \leq 10

1 \leq D \leq 10

-20 \leq X_{ij} \leq 20

No two given points have the same coordinates. That is, if i \neq j, there exists k such that X_{ik} \neq X_{jk}.

Input

Input is given from Standard Input in the following format:

N D
X_{11} X_{12} ... X_{1D}
X_{21} X_{22} ... X_{2D}
\vdots
X_{N1} X_{N2} ... X_{ND}

Output

Print the number of pairs (i, j) (i < j) such that the distance between the i-th point and the j-th point is an integer.

Sample Input 1

3 2
1 2
5 5
-2 8

Sample Output 1

1

The number of pairs with an integer distance is one, as follows:

The distance between the first point and the second point is \sqrt{|1-5|^2 + |2-5|^2} = 5, which is an integer.

The distance between the second point and the third point is \sqrt{|5-(-2)|^2 + |5-8|^2} = \sqrt{58}, which is not an integer.

The distance between the third point and the first point is \sqrt{|-2-1|^2+|8-2|^2} = 3\sqrt{5}, which is not an integer.

Sample Input 2

3 4
-3 7 8 2
-12 1 10 2
-2 8 9 3

Sample Output 2

2

Sample Input 3

5 1
1
2
3
4
5

Sample Output 3

10


<?php
fscanf(STDIN, "%d %d", $N, $D);
$xArray = array();
  $count=0;
if($D==1){
  for($i=1;$i<$N;$i++){
    $count+=$i;
  }
}
for($i=0;$i<$N;$i++){
  $xArray[] = explode(" ", trim(fgets(STDIN)));
}
$kyori=0;
for($i=0;$i<$N;$i++){
  for($j=$i+1;$j<$D;$j++){
    $kyori=0;
    $k=0;
    foreach($xArray[$i] as $xi){
      $xj=$xArray[$j][$k];
      $kyori+=abs($xi-$xj)*abs($xi-$xj);
      $k++;
    }

    if(intval(floor(sqrt($kyori)))*intval(floor(sqrt($kyori)))==$kyori&&$kyori>0){
      $count++;
    }
  }
}

    echo  ($count)."\n";

?>


<?php

$s = str_split(trim(fgets(STDIN)));
sort($s);
$n = count(array_unique($s));
echo $n==2 && $s[1]!==$s[2]? 'Yes' : 'No';

?>

Score : 100 points

Problem Statement

You are given a 4-character string S consisting of uppercase English letters.
Determine if S consists of exactly two kinds of characters which both appear twice in S.

Constraints

The length of S is 4.

S consists of uppercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S consists of exactly two kinds of characters which both appear twice in S, print Yes; otherwise, print No.

Sample Input 1

ASSA

Sample Output 1

Yes

S consists of A and S which both appear twice in S.

Sample Input 2

STOP

Sample Output 2

No

Sample Input 3

FFEE

Sample Output 3

Yes

Sample Input 4

FREE

Sample Output 4

No


<?php
fscanf(STDIN, "%s", $s);
$c = count_chars($s, 1);
if (count($c) == 2 && array_product($c) == 4) {
	echo 'Yes';
} else {
	echo 'No';
}


Score : 200 points

Problem Statement

We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.

Print the number of elements p_i (1 < i < n) that satisfy the following condition:

p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.

Constraints

All values in input are integers.

3 \leq n \leq 20

p is a permutation of {1,\ 2,\ ...,\ n}.

Input

Input is given from Standard Input in the following format:

n
p_1 p_2 ... p_n

Output

Print the number of elements p_i (1 < i < n) that satisfy the condition.

Sample Input 1

5
1 3 5 4 2

Sample Output 1

2

p_2 = 3 is the second smallest number among p_1 = 1, p_2 = 3, and p_3 = 5. Also, p_4 = 4 is the second smallest number among p_3 = 5, p_4 = 4, and p_5 = 2. These two elements satisfy the condition.

Sample Input 2

9
9 6 3 2 5 8 7 4 1

Sample Output 2

5


<?php
$a = trim(fgets(STDIN));
$input = explode(' ', trim(fgets(STDIN)));
$count = 0;

for ($i = 1; $i < $a - 1; $i++) {

        if (($input[$i - 1] < $input[$i] && $input[$i] < $input[$i + 1]) or ($input[$i - 1] > $input[$i] && $input[$i] > $input[$i + 1])) {
            $count++;

    }
}
echo $count;
?>


Score : 100 points

Problem Statement

The door of Snuke's laboratory is locked with a security code.

The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.

You are given the current security code S. If S is hard to enter, print Bad; otherwise, print Good.

Constraints

S is a 4-character string consisting of digits.

Input

Input is given from Standard Input in the following format:

S

Output

If S is hard to enter, print Bad; otherwise, print Good.

Sample Input 1

3776

Sample Output 1

Bad

The second and third digits are the same, so 3776 is hard to enter.

Sample Input 2

8080

Sample Output 2

Good

There are no two consecutive digits that are the same, so 8080 is not hard to enter.

Sample Input 3

1333

Sample Output 3

Bad

Sample Input 4

0024

Sample Output 4

Bad


<?php

fscanf(STDIN, "%s", $IntCode);
$StrCode = (string) $IntCode;
$ArrayCode = array(0,0,0,0);
$Result = "Good";

for($i = 0; $i < 4; $i++)
{
	$ArrayCode[$i] = substr($StrCode, $i, 1);
}

for ($i = 0; $i < 3; $i++) {
	if($ArrayCode[$i] == $ArrayCode[$i + 1])
	{
		$Result = "Bad";
	}
}

echo $Result;


        <?php
          $ans = fgets(STDIN);

    $arr = str_split($ans);
    if($arr[0]==$arr[1]){
      echo "bad"."\n";
    }
    elseif($arr[1]==$arr[2]){
        echo "bad"."\n";
    }
    elseif($arr[2]==$arr[3]){
        echo "bad"."\n";
    }
    else{
          echo "good"."\n";
    }
        ?>


<?php
# 文字列の入力
fscanf(STDIN, "%s", $s);
$tmp = str_split($s);
$bFlg = false;
for($i = 0;$i < count($tmp)-1;$i++){
    $j = $i+1;
    if($tmp[$i] == $tmp[$j]){
        $bFlg = true;
    }
}
# 出力
var_dump(($bFlg)?'Bad':'Good');
?>


<?php
$input = fgets(STDIN);
$input = explode("", $input);
$now = '';
for ($i = 0; $i < 4;  $i++  ) {
	if ($now == $input[i]) {
		echo "Bad";
		exit;
	} else {
		$now = $input[$i];
	}
}
echo "Good";

?>


<?php
$result = array();
fscanf(STDIN, "%d %d",$n, $l);
for ($i = 0; $i < $n; $i++) {
  $result[] += $l + $i;
}
$min = abs(min($result));

for ($i = 0; $i < $n; $i++) {
  if(abs($min) > abs($result[$i])){
    $min = $result[$i];
  }
}
echo array_sum($result) - $min,PHP_EOL;

Score : 200 points

Problem Statement

You have N apples, called Apple 1, Apple 2, Apple 3, ..., Apple N. The flavor of Apple i is L+i-1, which can be negative.

You can make an apple pie using one or more of the apples. The flavor of the apple pie will be the sum of the flavors of the apples used.

You planned to make an apple pie using all of the apples, but being hungry tempts you to eat one of them, which can no longer be used to make the apple pie.

You want to make an apple pie that is as similar as possible to the one that you planned to make. Thus, you will choose the apple to eat so that the flavor of the apple pie made of the remaining N-1 apples will have the smallest possible absolute difference from the flavor of the apple pie made of all the N apples.

Find the flavor of the apple pie made of the remaining N-1 apples when you choose the apple to eat as above.

We can prove that this value is uniquely determined.

Constraints

2 \leq N \leq 200

-100 \leq L \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N L

Output

Find the flavor of the apple pie made of the remaining N-1 apples when you optimally choose the apple to eat.

Sample Input 1

5 2

Sample Output 1

18

The flavors of Apple 1, 2, 3, 4, and 5 are 2, 3, 4, 5, and 6, respectively. The optimal choice is to eat Apple 1, so the answer is 3+4+5+6=18.

Sample Input 2

3 -1

Sample Output 2

0

The flavors of Apple 1, 2, and 3 are -1, 0, and 1, respectively. The optimal choice is to eat Apple 2, so the answer is (-1)+1=0.

Sample Input 3

30 -50

Sample Output 3

-1044


<?php

    $inputs = explode(' ',trim(fgets(STDIN)));
	$total = 0;
	$check = abs($inputs[1]);

for($x = 0;$x < $inputs[0];$x++){
	$apple = $inputs[1] + $x;
	$total += $apple;
	if(abs($check) > abs($apple)){
      $check = $apple;
    }
}
$total -= $check;

print $total;


<?php
  fscanf(STDIN,"%d%d%d%d", $a,$b,$c,$d);
  function gcd($m, $n){
      if($n > $m) list($m, $n) = array($n, $m);
      while($n !== 0){
          $tmp_n = $n;
          $n = $m % $n;
          $m = $tmp_n;
      }
      return $m;
  }

  function lcm($m, $n){
      return $m * $n / gcd($m, $n);
  }

  $cd = lcm($c,$d);

  $a--;
  if($c>$b && $d>$b){
      echo $b-$a;
      exit;
  }

  $count1 = (int)($b/$c)-(int)($a/$c);
  $count2 = (int)($b/$d)-(int)($a/$d);
  $count3 = (int)($b/$cd)-(int)($a/$cd);
  echo ($b-$a)-($count1+$count2-$count3);

Score : 300 points

Problem Statement

You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Constraints

1\leq A\leq B\leq 10^{18}

1\leq C,D\leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B C D

Output

Print the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.

Sample Input 1

4 9 2 3

Sample Output 1

2

5 and 7 satisfy the condition.

Sample Input 2

10 40 6 8

Sample Output 2

23

Sample Input 3

314159265358979323 846264338327950288 419716939 937510582

Sample Output 3

532105071133627368


<?php
# C - Anti-Division

fscanf(STDIN, "%d %d %d %d", $A, $B, $C, $D);

$A = $A - 1;

#1からA
$ADividedC = intdiv($A, $C);
$ADividedD = intdiv($A, $D);
$ADividedCD = intdiv($A, lcm($C, $D));
$AA = ($A - $ADividedC - $ADividedD + $ADividedCD);

#1からB
$BDividedC = intdiv($B, $C);
$BDividedD = intdiv($B, $D);
$BDividedCD = intdiv($B, lcm($C, $D));
$BB = ($B - $BDividedC - $BDividedD + $BDividedCD);

echo ($BB - $AA) . PHP_EOL;

//最大公約数
function gcd($m, $n){
    if($n > $m) list($m, $n) = array($n, $m);

    while($n !== 0){
        $tmp_n = $n;
        $n = $m % $n;
        $m = $tmp_n;
    }
    return $m;
}

//最小公倍数
function lcm($m, $n){
    return $m * $n / gcd($m, $n);
}


    const INPUT_DELIMITER = " ";

    // 最小公倍数を求める
    function getLCM ($a, $b) {
        return $a * $b / getGCM($a, $b);
    }

    // 最大公約数を求める
    function getGCM ($a, $b) {
        if ($a < $b) {
            list($min, $max) = [$a, $b];
        } else {
            list($min, $max) = [$b, $a];
        }

        $mod = $max % $min;
        if ($mod === 0) {
            return $min;
        }

        return getGCM($min, $mod);
    }

    // 入力
    $input = fgets(STDIN);
    $inputArray = explode(INPUT_DELIMITER, $input);

    $A = $inputArray[0];
    $B = $inputArray[1];
    $C = $inputArray[2];
    $D = $inputArray[3];

    // CとDの公倍数
    $CD = getLCM($C, $D);

    $range = $B - $A;
    // 割り切れないものの個数
    $countC = floor($range / $C);
    $countD = floor($range / $D);
    $countCD = floor($range / $CD);

    //
    $count = bcsub($range , ($countC + $countD - $countCD));

    echo $count;


<?php

//文字列の入力
fscanf(STDIN,"%d %d",$x,$a);

if ($x < $a || $x !== $a){
    echo 0;
}elseif($x >= 10){
    echo 10;
}

Score : 100 points

Problem Statement

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

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

Constraints

0 \leq X, A \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X A

Output

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

Sample Input 1

3 5

Sample Output 1

0

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

Sample Input 2

7 5

Sample Output 2

10

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

Sample Input 3

6 6

Sample Output 3

10

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