<?php

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

$tree = array_fill(1,$n,[]);
$point = array_fill(1,$n,0);

for($i=0;$i<$n-1;$i++){
    fscanf(STDIN, "%d%d", $start, $end);
    $tree[$start][] = $end;
}

for($i=0;$i<$q;$i++){
    fscanf(STDIN, "%d%d", $target, $plus);
    $point[$target]+= $plus;
}

$start = $point[1];
$point[1] =0;
plus_point(1,$start);

echo implode(" ", $point);

function plus_point($target, $plus){
    global $tree, $point;
    $point[$target] += $plus;
    if(!empty($tree[$target])){
        foreach($tree[$target] as $value ){
            plus_point($value, $point[$target]);
        }
    }

}


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($N,$Q) =  explode(" ",trim(fgets(STDIN)));
//$v =  explode(" ",trim(fgets(STDIN)));
for($i=0;$i<$N-1;$i++) {
  list($a,$b) =  explode(" ",trim(fgets(STDIN)));
  $a-=1;
  $b-=1;
  $t[$a][]=$b;
  $t[$b][]=$a;
}
$c = array_fill(0,$N,0);
for($i=0;$i<$Q;$i++) {
  list($p,$x) =  explode(" ",trim(fgets(STDIN)));
  $p-=1;
  $c[$p] += $x;
}
dfs(0);
printf("%s\n",implode(" " ,$c));

function dfs($v,$p=-1)
{
  global $t,$c;
  if (isset($t[$v])) {
    foreach($t[$v] as $u) {
      if ($u == $p) continue;
      $c[$u] += $c[$v];
      dfs($u,$v);
    }
  }
}

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

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

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

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

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

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

Sample Output 2

20 20 20 20 20 20

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, $Q);
	$a_array = array();
	$b_array = array();
	$p_array = array();
	$x_array = array();
	for ($i = 1; $i < $N; $i++) {
      fscanf(STDIN, "%d %d", $a, $b);
      $a_array[] = $a;
      $b_array[] = $b;
    }
	for ($i = 1; $i <= $Q; $i++) {
      fscanf(STDIN, "%d %d", $p, $x);
      $p_array[] = $p;
      $x_array[] = $x;
    }
	$tree = array();
	for ($i = 1; $i <= $N; $i++) {
      $tree[$i] = array();
    }

	for ($i = 0; $i < count($a_array); $i++) {
      $tree[$a_array[$i]][] = $b_array[$i];
    }

	$count_sum = array();
	for ($i = 0; $i < $N; $i++) {
      $count_sum[$i+1] = 0;
    }

	for ($i = 0; $i < count($p_array); $i++) {
      $count_sum[$p_array[$i]] += $x_array[$i];
    }

	$result = array();
	for ($i = 0; $i < $N; $i++) {
      $result[$i+1] = 0;
    }

	$result[1] = $count_sum[1];
	for ($i = 1; $i <= $N; $i++) {
      foreach($tree[$i] as $key => $v) {
        $result[$v] = $result[$i] + $count_sum[$v];
      }
    }

	for ($i = 1; $i < $N; $i++) {
      echo ($result[$i].' ');
    }
	echo ($result[$i]);
?>


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

$n = (int)$input[0];
$m = (int)$input[1];
$p = (int)$input[2];

$edges = [];
for ($i=0; $i < $m; $i++) {
	$input = explode(' ', trim(fgets(STDIN)));
	$edges[] = [
		(int)$input[0],
		(int)$input[1],
		((int)$input[2] - $p) * (-1),
	];
}
$dists = [];
$isLoop = [];
$inf = 1000000000;
for ($i=0; $i < $n; $i++) {
	$dists[$i+1] = $inf;
	$isLoop[$i+1] = false;
}
$dists[1] = 0;

// ベルマンフォード法
for ($i=0; $i < $n-1; $i++) {
	$updated = false;
	foreach ($edges as $tmp_e) {
		if ($dists[$tmp_e[0]] !== $inf && $dists[$tmp_e[1]] > $dists[$tmp_e[0]] + $tmp_e[2]) {
			$dists[$tmp_e[1]] = $dists[$tmp_e[0]] + $tmp_e[2];
			$updated = true;
			// predecessorは今回不要
		}
	}
	if (!$updated) {
		break;
	}
}
// dists[n]に関係する閉路を検出するため、再度ベルマンフォード
for ($i=0; $i < $n-1; $i++) {
	$updated = false;
	foreach ($edges as $tmp_e) {
		if ($dists[$tmp_e[0]] !== $inf && $dists[$tmp_e[1]] > $dists[$tmp_e[0]] + $tmp_e[2]) {
			$dists[$tmp_e[1]] = $dists[$tmp_e[0]] + $tmp_e[2];
			$updated = true;
			$isLoop[$tmp_e[1]] = true;
		}
		if ($isLoop[$tmp_e[0]]) {
			$isLoop[$tmp_e[1]] = true;
		}
	}
	if (!$updated) {
		break;
	}
}

if ($isLoop[$n]) {
	echo '-1';
}else{
	echo max(0, $dists[$n] * (-1));
}

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


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

$n = (int)$input[0];
$m = (int)$input[1];
$p = (int)$input[2];

$edges = [];
for ($i=0; $i < $m; $i++) {
	$input = explode(' ', trim(fgets(STDIN)));
	$edges[] = [
		(int)$input[0],
		(int)$input[1],
		((int)$input[2] - 10) * (-1),
	];
}
$dists = [];
$inf = 1000000;
for ($i=0; $i < $n; $i++) {
	if ($i === 0) {
		$dists[$i+1] = 0;
	}else{
		$dists[$i+1] = $inf;
	}
}

// ベルマンフォード法
for ($i=0; $i < $n; $i++) {
	for ($j=0; $j < $m; $j++) {
		$tmp_e = $edges[$j];
		if ($dists[$tmp_e[1]] > $dists[$tmp_e[0]] + $tmp_e[2]) {
			$dists[$tmp_e[1]] = $dists[$tmp_e[0]] + $tmp_e[2];
			// predecessorはここで更新する。今回考えなくて良い
			if ($i === $n-1 && $tmp_e[1] === $n) {
				// n回目の反復で値が更新される場合は、負の平炉があり、最短経路は定まらない
				echo '-1';
				exit();
			}
		}
	}
}
echo max(0, $dists[$n] * (-1));


<?php
list($n, $m, $p) = ints();
for($i = 1; $i <= $n; $i++){
  $map[$i] = [];
  $max[$i] = -10**10;
}
for($i = 0; $i < $n; $i++){
  list($a, $b, $c) = ints();
  $map[$a][$b] = $c - $p;
}

dfs(1, 0, []);
printf("%d", $max[$n]);

function dfs($current, $money, $pathMap){
  global $map, $max;

  $changed = false;
  if(isset($pathMap[$current])){
    if($money == -1){
      if($max[$current] != -1){
        $max[$current] = -1;
        $changed = true;
      }
    }elseif($money > $pathMap[$current]){
      $money = -1;
      $max[$current] = -1;
      $changed = true;
    }
  }else{
    if($money == -1){
      $pathMap[$current] = $money;
      if($max[$current] != -1)$changed = true;
      $max[$current] = -1;
    }else{
      $pathMap[$current] = $money;
      if($max[$current] != max($max[$current], $money))$changed = true;
      $max[$current] = max($max[$current], $money);
    }
  }
  if($changed == false)return;

  $next = $map[$current];
  foreach($next as $to => $income){
    if($money == -1){
      dfs($to, -1, $pathMap);
    }else{
      dfs($to, max(0, $money + $income), $pathMap);
    }
  }
}

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

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

    $H = array_map('intval',explode(" ",trim(fgets(STDIN))));
    $max=0;
    for($i=0;$i<$N-1;$i++){
        if(($H[$i]-$H[$i+1])>2){
            echo "No";
            exit;
        }
        if($max<$H[$i]){
            $max = $H[$i];
        }
        // echo $max."\n";
        if($max-$H[$i+1]>=2){
            echo "No";
            exit;
        }
    }
    echo "Yes";
?>

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.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

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

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


<?php
fscanf(STDIN, "%d", $N);
$H = array_map('intval', explode(" ", trim(fgets(STDIN))));

$ans = 'Yes';
$mmax = $H[0];

for ($i = 1; $i < $N; $i++) {
    $mmax = max($mmax, $H[$i]);
    if ($mmax - 2 >= $H[$i]) {
        $ans = 'No';
    }
}

echo $ans;


<?php
  // 逆からみて単調非増加

  $n = intVal(trim(fgets(STDIN)));
  $arr = array_map("intVal", explode(" ", trim(fgets(STDIN))));
  for($i=$n-2; $i>=0; $i--){
    if($arr[$i]-$arr[$i+1] > 1){
      echo "No" . PHP_EOL;
      exit();
    }elseif($arr[$i] - $arr[$i+1] == 1){
      $arr[$i] -= 1;
    }
  }
  echo "Yes" . PHP_EOL;
?>


<?php
$n = trim(fgets(STDIN));
$arr = explode(" ",trim(fgets(STDIN)));

for($i=$n-1; $i>0; $i--){
    if($arr[$i] < $arr[$i-1]){
        if(abs($arr[$i]-$arr[$i-1]) >= 2){
            echo "No";
            exit;
        }else{
            $arr[$i-1] = $arr[$i-1] -1;
        }
    }
}

echo "Yes";

?>


<?php
$file = new SplFileObject("php://stdin");
$file->setFlags(15);
$file->setCsvControl(' ');

$line = [];
foreach ($file as $i => $row) {
    $line[$i] = $row;
}

$column = $line[0][0];
$stairs = $line[1];
$isOperated = false;
$isError = false;
for ($i = 0; $i < $column - 1; $i++) {
    $left = $stairs[$i];
    $right = $stairs[$i + 1];

    if ($left - 1 > $right || (isset($min) && $min > $right)) {
        $isError = true;
    } elseif ($left - 1 == $right) {
        $min = $left - 1;
    }
}

$str = $isError ? 'No' : 'Yes';

echo $str . PHP_EOL;


<?php
fscanf(STDIN, "%d", $n);
$h = array_map('intval', explode(' ', trim(fgets(STDIN))));
$h[0]--;
for ($i = 1; $i < $n; $i++) {
    if ($h[$i - 1] < $h[$i]) {
        $h[$i]--;
    } elseif ($h[$i - 1] > $h[$i]) {
        exit ('No'.PHP_EOL);
    }
}
echo 'Yes'.PHP_EOL;


<?PHP
fscanf(STDIN, "%d", $a);
$k = explode(" ", fgets(STDIN));

$h=1;
$cnt=0;
foreach($k as $v){
  if($h-$v==1){
    $cnt++;
    $h=$v;
    if($cnt==2){
      echo 'No';
      exit;
    }
  }elseif($h-$v>1){
    echo 'No';
    exit;
  }else{
    $h=$v;
  }
}
echo 'Yes';


<?php
fscanf(STDIN, "%s", $a);
$input = trim(fgets(STDIN));
$inputs = explode(' ', $input);
$is_ok = true;

$start = $inputs[0];
$used = 0;
for ($i = 0; $i < count($inputs); $i++) {
  if (!isset($inputs[$i + 1])) {
   	break;
  }
  $inputs[$i] -= 1;
  $next = $inputs[$i + 1];
  if ($inputs[$i] > $next) {
    $is_ok = false;
    break;
  }
}

if ($is_ok) {
    echo "Yes\n";
} else {
    echo "No\n";
}


<?php

$input = (int)fgets(STDIN);

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

for($i=0; $i<$input; $i++){
  $heights[$i] = (int)$heights[$i];
}

$check = FALSE;

for($i=0; $i<$input; $i++){
  if($i < $input - 1 and $input != 2){
      if($i != 0){
          if($heights[$i] <= $heights[$i+1] or ($heights[$i] - 1 <= $heights[$i+1] and $heights[$i] - 1 >= $heights[$i-1])){
            $check = TRUE;
          }else{
            $check = FALSE;
            break;
          }
      }else{
          if($heights[$i] <= $heights[$i+1] or $heights[$i] - 1 <= $heights[$i+1]){
            $check = TRUE;
          }else{
            $check = FALSE;
            break;
          }
      }
  }
}

if($input === 2){
  if($heights[0] <= $heights[1] or $heights[0] - 1 <= $heights[1]){
    $check = TRUE;
  }
}

if($check === TRUE or $input === 1){
  echo "Yes";
}elseif($check === FALSE){
  echo "No";
}


<?php

$input = (int)fgets(STDIN);

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

for($i=0; $i<$input; $i++){
  $heights[$i] = (int)$heights[$i];
}

$check = FALSE;

for($i=0; $i<$input; $i++){
  if($i < $input - 1 and $input != 2){
      if($i != 0){
          if($heights[$i] <= $heights[$i+1] or $heights[$i] - 1 <= $heights[$i+1] and $heights[$i] - 1 >= $heights[$i-1]){
            $check = TRUE;
          }else{
            $check = FALSE;
            break;
          }
      }else{
          if($heights[$i] <= $heights[$i+1] or $heights[$i] - 1 <= $heights[$i+1]){
            $check = TRUE;
          }else{
            $check = FALSE;
            break;
          }
      }
  }
}

if($input === 2){
  if($heights[0] <= $heights[1] or $heights[0] - 1 <= $heights[1]){
    $check = TRUE;
  }
}

if($check === TRUE or $input === 1){
  echo "Yes";
}elseif($check === FALSE){
  echo "No";
}


<?php

$input = (int)fgets(STDIN);

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

for($i=0; $i<$input; $i++){
  $heights[$i] = (int)$heights[$i];
}

$check = FALSE;

for($i=0; $i<$input; $i++){
  if($i < $input - 1 and $input != 2){
      if($heights[$i] <= $heights[$i+1] or $heights[$i] - 1 <= $heights[$i+1] and $heights[$i] - 1 >= $heights[$i-1]){
        $check = TRUE;
      }else{
        $check = FALSE;
        break;
      }
  }
}

if($input === 2){
  if($heights[0] <= $heights[1] or $heights[0] - 1 <= $heights[1]){
    $check = TRUE;
  }
}

if($check === TRUE or $input === 1){
  echo "Yes";
}elseif($check === FALSE){
  echo "No";
}


<?php
fscanf(STDIN, "%s", $a);
$input = trim(fgets(STDIN));
$inputs = explode(' ', $input);
$is_ok = true;
$total_down = 0;

$start = $inputs[0];
foreach ($inputs as $i => $current) {
  if (!isset($inputs[($i + 1)])) {
    break;
  }
  $next = $inputs[($i + 1)];
  //print_r([$current, $next]) . "\n";
  if ($next < $current && $current - $next >= 2) {
    $is_ok = false;
    break;
  }
  if ($start - 2 <= $current) {
    $is_ok = false;
    break;
  }
}

if ($is_ok) {
    echo "Yes\n";
} else {
    echo "No\n";
}


<?php
fscanf(STDIN, "%s", $a);
$input = trim(fgets(STDIN));
$inputs = explode(' ', $input);
$last = array_pop($inputs);
$inputs[] = $last;
$is_ok = true;
if ($last == 1) {
    $is_ok = false;

} else {
    foreach ($inputs as $i => $current) {
      	if (!isset($inputs[($i + 1)])) {
         	break;
        }
        $next = $inputs[($i + 1)];
      	//print_r([$current, $next]) . "\n";
        if ($next < $current && $current - $next >= 2) {
            $is_ok = false;
            break;
        }
    }
}

if ($is_ok) {
    echo "Yes\n";
} else {
    echo "No\n";
}


<?php
fscanf(STDIN, "%s", $a);
$input = trim(fgets(STDIN));
$inputs = explode(' ', $input);
$last = array_pop($inputs);
$inputs[] = $last;
$is_ok = true;
if ($last == 1) {
    $is_ok = false;

} else {
    foreach ($inputs as $i => $current) {
        $next = $inputs[($i + 1)];
        if ($next > $current && $next - $current >= 2) {
            $is_ok = false;
            break;
        }
    }
}

if ($is_ok) {
    echo "Yes\n";
} else {
    echo "No\n";
}


<?php

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

#dream dreamer erase eraser

#var_dump($v2);

$cnt = 0;

$ans = "Yes";
for($i=1; $i<$stdin[0]; $i++){

  $diff = $v2[$i - 1] - $v2[$i];

  if($diff <= 0){
    continue;
  }elseif($diff == 1){
    $cnt++;
  }elseif($diff >= 2){
    $cnt++;
    $cnt++;
  }

}

    if($cnt > 1){
      $ans = "No";
    }

echo $ans . PHP_EOL;


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

$hi = 0;
for($i=0;$i<$N;$i++) {
  if ($H[$i]>$hi) {
    $hi = $H[$i];
    continue;
  }
  if ($hi - $H[$i]>1) {
    printf("No\n");
    exit;
  }

}
printf("Yes\n");


<?php
$n = int();
$hArray = ints();

$min = $hArray[0]-1;
for($i = 0; $i < $n; $i++){
  if($hArray[$i] < $min){
    echo "No";exit;
  }
  $min = max($min, $hArray[$i] - 1);
}
echo "Yes";exit;

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 : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


<?php
fscanf(STDIN, "%d %d",$l,$r);
$min = INF;
# lより1大きい数iを取得
for($i=$l;$i<$r;$i++){

	#iより大きい数jの取り得る値で判別
	for($j=$l+1;$j<=$r;$j++){

		$tmp = ($i * $j) % 2019;
		if($min > $tmp){

			$min = $tmp;
		}
		if ($min == 0) {
			echo $min;
			return;
		}
	}
}
echo $min;
?>


<?php

const INPUT_DELIMITER = " ";
$input = fgets(STDIN);
list($L, $R) = array_map('intval', explode(INPUT_DELIMITER, $input));

const MOD = 2019;

// 最大がMOD以下の時
if ($R < MOD) {
    echo $L * $R;
    return;
}

// $Lか$Rが2019の倍数を取りうる時
//（差が2019以上であればどっちかが2019の倍数に出来る）
if ($R - $L > MOD) {
    echo 0;
    return;
}

// それ以外のときは地道に計算してみる
$A = MOD;
$B = MOD;
for ($i = $L; $i <= $R; $i++) {
    $mod = $i % MOD;
    if ($A > $mod) {
        $A = $mod;
        continue;
    }
    if ($B > $mod) {
        $B = $mod;
    }
}

echo ($A * $B) % MOD;


<?php
    fscanf(STDIN, '%d %d', $left, $right);

    if(floor($left / 2019) != floor($right / 2019)){
        $ans = 0;
    }else{
        $left %= 2019;
        $ans = $left * ($left + 1) % 2019;
    }
    echo $ans;


<?php
    fscanf(STDIN, '%d %d', $left, $right);

    if(floor($left / 2019) != floor($right / 2019)){
        $ans = 0;
    }elseif($right % 2019 == 0){
        $ans = 0;
    }else{
        $mod = $left % 2019;
        $ans = $mod * ($mod + 1);
    }
    echo $ans;


<?php
ini_set('error_reporting', E_ALL & ~E_NOTICE);
fscanf(STDIN, "%s", $S);
$S = str_replace("BC", "D", $S);
$len = strlen($S);
$ans = 0;
$cnt = $streak = 0;
$streak = 0;
for ($i = 0; $i < $len; $i++) {
    if ($S[$i] === 'A' || $S[$i] === 'D') {
        $streak++;
        if ($S[$i] === 'A') {
            $cnt++;
        } else {
            $ans += $cnt;
        }
    } else {
        $cnt = $streak = 0;
    }
}
echo $ans;

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


<?php
fscanf(STDIN, "%s", $S);
$S = str_replace("BC", "D", $S);
$ans = 0;

while(true) {
    $cnt = substr_count($S, "ADDDDDDDDDD");
    $ans += $cnt * 10;
    $S = str_replace("ADDDDDDDDDD", "DDDDDDDDDDA", $S);

    $cnt = substr_count($S, "AAAAAAAAAAD");
    $ans += $cnt * 10;
    $S = str_replace("AAAAAAAAAAD", "DAAAAAAAAAA", $S);

    $cnt = substr_count($S, "AD");
    if ($cnt === 0) break;
    $ans += $cnt;
    $S = str_replace("AD", "DA", $S);
}
echo $ans;


Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3


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

$h = (int)$input[0];
$w = (int)$input[1];

$map = [];
$q = new SimpleQueue();
for ($i=0; $i < $h; $i++) {
	$input = trim(fgets(STDIN));
	$tmp = [];
	for ($j=0; $j < $w; $j++) {
		if ($input[$j] === '#') {
			$q->enq([$i, $j]);
			$tmp[] = 0;
		}else{
			$tmp[] = -1;
		}
	}
	$map[] = $tmp;
}
$max = 0;

while (!$q->isEmpty()) {
	$tmp = $q->deq();
	$dist = $map[$tmp[0]][$tmp[1]] + 1;
	$cand = getSur($tmp);
	$found = false;

	if ($tmp[0] > 0 && $map[$tmp[0]-1][$tmp[1]] === -1) {
		$found = true;
		$map[$tmp[0]-1][$tmp[1]] = $dist;
		$q->enq([$tmp[0]-1, $tmp[1]]);
	}
	if ($tmp[0] < $h-1 && $map[$tmp[0]+1][$tmp[1]] === -1) {
		$found = true;
		$map[$tmp[0]+1][$tmp[1]] = $dist;
		$q->enq([$tmp[0]+1, $tmp[1]]);
	}
	if ($tmp[1] > 0 && $map[$tmp[0]][$tmp[1]-1] === -1) {
		$found = true;
		$map[$tmp[0]][$tmp[1]-1] = $dist;
		$q->enq([$tmp[0], $tmp[1]-1]);
	}
	if ($tmp[0] < $w-1 && $map[$tmp[0]][$tmp[1]+1] === -1) {
		$found = true;
		$map[$tmp[0]][$tmp[1]+1] = $dist;
		$q->enq([$tmp[0], $tmp[1]+1]);
	}
	if ($found) {
		$max = max($max, $dist);
	}
	// dumpMap($map);
	// echo $q->getCount() . PHP_EOL;
}
echo $max;

// function dumpMap($map){
// 	foreach ($map as $row) {
// 		echo implode(' ', $row) . PHP_EOL;
// 	}
// 	// echo PHP_EOL;
// }

function getSur($xy){
	return [
		[$xy[0]-1, $xy[1]],
		[$xy[0]+1, $xy[1]],
		[$xy[0], $xy[1]-1],
		[$xy[0], $xy[1]+1],
	];
}

/**
 *
 */
class SimpleQueue
{
	private $data = [];
	private $idx = 0;

	public function enq($d){
		$this->data[] = $d;
	}
	public function deq(){
		$d = $this->data[$this->idx];
		$this->idx += 1;
		return $d;
	}
	public function isEmpty(){
		return count($this->data) === $this->idx;
	}
}


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

$h = (int)$input[0];
$w = (int)$input[1];
$q = new SimpleQueue();

$map = [];
$black = [];
for ($i=0; $i < $h; $i++) {
	$input = trim(fgets(STDIN));
	$tmp = [];
	for ($j=0; $j < $w; $j++) {
		$tmp[$j+1] = $input[$j];
		if ($input[$j] === '#') {
			$black[] = [$i+1, $j+1];
		}
	}
	$map[$i+1] = $tmp;
}
$cnt = 0;
foreach ($black as $b) {
	$cand = getSur($map, $b);
	foreach ($cand as $c) {
		if (isset($map[$c[0]][$c[1]]) && $map[$c[0]][$c[1]] !== '#') {
			$map[$c[0]][$c[1]] = '?';
			$q->enq($c);
		}
	}
}
while (!$q->isEmpty()) {
	++$cnt;
	$newq = new SimpleQueue();
	while (!$q->isEmpty()) {
		$tmp = $q->deq();
		if ($map[$tmp[0]][$tmp[1]] !== '#') {
			$map[$tmp[0]][$tmp[1]] = '#';
			$cand = getSur($map, $tmp);
			foreach ($cand as $v) {
				if (isset($map[$v[0]][$v[1]]) && $map[$v[0]][$v[1]] === '.') {
					$map[$v[0]][$v[1]] = '?';
					$newq->enq($v);
				}
			}
		}
	}
	// dumpMap($map);
	// echo $q->getCount() . PHP_EOL;
	$q = $newq;
}
echo $cnt;

function dumpMap($map){
	foreach ($map as $row) {
		echo implode(' ', $row) . PHP_EOL;
	}
	// echo PHP_EOL;
}
/**
 *
 */
class SimpleQueue
{
	private $data = [];
	private $idx = 0;

	public function enq($d){
		$this->data[] = $d;
	}

	public function deq(){
		$d = null;
		if (!$this->isEmpty()) {
			$d = $this->data[$this->idx];
			$this->idx += 1;
		}
		return $d;
	}

	public function isEmpty(){
		return count($this->data) === $this->idx;
	}

	public function getCount(){
		return count($this->data) - $this->idx;
	}

}

function getSur($map, $xy){
	$y = $xy[0];
	$x = $xy[1];
	$cand = [
		[$y-1, $x],
		[$y+1, $x],
		[$y, $x-1],
		[$y, $x+1],
	];
	return $cand;
}


#!/usr/bin/env php
<?php
const BLACK = '#';
const WHITE = '.';
function genInputs() {
    while(($input = rtrim(fgets(STDIN))) !== false) {
        foreach (explode(' ', $input) as $v) {
            yield $v;
        }
    }
}
function getNext($gen) {
    $value = $gen->current();
    $gen->next();
    return $value;
}
$gen = genInputs();

$H = (int)getNext($gen);
$W = (int)getNext($gen);

$change = [];
for ($i = 0; $i < $H; $i++) {
    $item = getNext($gen);
    for ($j = 0; $j < $W; $j++) {
        if ($item[$j] == BLACK) {
            $change[$i][$j] = 0;
        }
    }
}
$add_change = function($i, $j, $n) use($H, $W, &$change, &$add_change) {
    if (!isset($change[$i][$j])) {
        $change[$i][$j] = $n;
    } elseif ($change[$i][$j] > $n) {
        $change[$i][$j] = $n;
    } else {
        return false;
    }
    return true;
};
$number = 0;
$next = true;
while ($next) {
    $next = false;
    foreach ($change as $i => $row) {
        foreach ($row as $j => $item) {
            if ($item != $number) {
                continue;
            }
            foreach ([[$i - 1, $j], [$i + 1, $j], [$i, $j - 1], [$i, $j + 1]] as $pos) {
                if ($pos[0] < 0 || $pos[0] >= $H || $pos[1] < 0 || $pos[1] >= $W) {
                    continue;
                }
                $ret = $add_change($pos[0], $pos[1], $number + 1);
                if ($ret) {
                    $next = true;
                }
            }
        }
    }
    $number++;
}
echo max(array_map(function($child) { return max($child); }, $change)).PHP_EOL;


<?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();
$array=[];
$sum = 0;
$answer = 0;

for($i=0;$i<$n;$i++){
  $array[] = $sc->nextInt();
}

sort($array);

if($array[0] == $array[$n-1]){
  $answer = $array[0];
} else {
  for($i=$array[1];$i>0;$i--){
    $sum = 0;
    foreach($array as $key=>$value){
      if($value%$i > 0){
        $sum++;
      }
    }
    if($sum == 1){
      $answer = $i;
      break;
    }
  }
}

echo $answer . PHP_EOL;

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


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

    $min = min($input);

    for ($m = $min; $m > 1; $m--) {
        $f = 0;
        for ($i = 0; $i < $n; $i++) {
            if ($input[$i] % $m) {
                $f++;
            }
        }
        if ($f <= 1) {
            echo $m;
            return;
        }
    }
    echo 1;


<?php
//前提条件$size>=2
$size = fgets(STDIN);
//前提条件$v内の数>=1
$v = fgets(STDIN);
//全データを配列にする
$arrayAll = explode(" ", $v);
//求める最大公約数,1数無視できると考える
$lastMax = 0;

if($size <= 2){
  if($arrayAll[0]>=$arrayAll[1]){
    $lastMax = $arrayAll[0];
  }else{
    $lastMax = $arrayAll[1];
  }
}else{
  for($i=0;$i<$size;$i++){
    //初期化
    $arraySplice = $arrayAll;
    //i番目の要素を削除
    array_splice($arraySplice, $i, 1);
    //途中経過確認用,提出時削除
    //echo implode(",",$arraySplice)."\n";
    //$max初期化、配列内先頭2数の最大公約数を求め、配列内から削除
    $max = gcd($arraySplice[0],$arraySplice[1]);
    array_splice($arraySplice, 0, 2);
    //$maxと配列内の先頭の数との最大公約数を求める
    for($j=0;$j<$size-3;$j++){
      if($lastMax > $max){
        break;
      }
      //途中経過確認用,提出時削除
      //echo gcd($max,$arraySplice[0])."\n";
      if(gcd($max,$arraySplice[0]) > $max){
        $lastMax = gcd($max,$arraySplice[0]);
      }
      $max = gcd($max,$arraySplice[0]);
      array_splice($arraySplice, 0, 1);
    }
    //答え更新
    if($max > $lastMax){
      $lastMax = $max;
    }
  }
}
echo $lastMax;

//ユークリッド互除法
function gcd($a, $b) {
  if ($b === 0){
      return $a;
  }
  return gcd($b, $a % $b);
}


<?php
$n = trim(fgets(STDIN));
$vArray = explode(" ", trim(fgets(STDIN)));

foreach($vArray as $i => $v){
    $dArray = divisor($v);
    foreach($dArray as $d){
        @$map[$d]++;
    }
}
$max = 1;
foreach($map as $value => $count){
    if($count >= $n - 1){
        $max = max($max, $value);
    }
}
echo $max;

function divisor($n){
    if(!isset($GLOBALS["cache"][$n])){
        for($i = 1; $i < sqrt($n); $i++){
            if($n % $i == 0){
                $f[] = $i;
                $f[] = $n / $i;
            }
        }
        sort($f);
        $GLOBALS["cache"][$n] = array_unique($f);
    }
    return $GLOBALS["cache"][$n];
}


<?php
$n = trim(fgets(STDIN));
$vArray = explode(" ", trim(fgets(STDIN)));

$divmax = $vArray[0];
foreach($vArray as $i => $v){
    $dArray = divisor($v, $divmax);
    foreach($dArray as $d){
        @$map[$d]++;
    }
    $tmpmax = 0;
    foreach($map as $k => $c){
        if($c > $i - 1){
            $tmpmax = max($tmpmax, $k);
        }
    }
    $divmax = $tmpmax;
}
$max = 1;
foreach($map as $value => $count){
    if($count >= $n - 1){
        $max = max($max, $value);
    }
}
echo $max;

function divisor($n, $divmax){
    if(!isset($GLOBALS["cache"][$n])){
        for($i = min(ceil(sqrt($n)), $divmax); $i >= 1; $i--){
            if($n % $i == 0){
                $f[] = $i;
                $f[] = $n / $i;
            }
        }
        sort($f);
        $GLOBALS["cache"][$n] = array_unique($f);
    }
    return $GLOBALS["cache"][$n];
}


<?php
/**
 * ABC125
 * C - GCD on Blackboard
 */

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

// 累積GCDを計算
$gcd_list_left = [(int) $a[0]];
$gcd_list_right = [(int) $a[$n - 1]];
$gcd_memo = [];
for ($i = 1; $i < $n - 1; $i++) {
    $gcd_list_left[$i] = gcd($gcd_list_left[$i - 1], $a[$i]);
    $gcd_list_right[$i] = gcd($gcd_list_right[$i - 1], $a[$n - 1 - $i]);
}

// gcd((左累積GCD), (右累積GCD))
$gcd[0] = $gcd_list_right[$n - 2];
$gcd[$n - 1] = $gcd_list_left[$n - 2];
for ($i = 1; $i < $n - 1; $i++) {
    $gcd[$i] = gcd($gcd_list_left[$i - 1], $gcd_list_right[$n - 1 - $i - 1]);
}

echo max($gcd), "\n";

function gcd($a, $b): int {
    return $gcd_memo[$a][$b] ?? ($b == 0 ? $a : gcd($b, $a % $b));
}


<?php
/**
 * ABC125
 * C - GCD on Blackboard
 */

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

// 累積GCDを計算
$gcd_list_left = [(int) $a[0]];
$gcd_list_right = [(int) $a[$n - 1]];
$gcd_memo = [];
for ($i = 1; $i < $n - 1; $i++) {
    $gcd_list_left[$i] = gcd($gcd_list_left[$i - 1], $a[$i]);
    $gcd_list_right[$i] = gcd($gcd_list_right[$i - 1], $a[$n - 1 - $i]);
}

// gcd((左累積GCD), (右累積GCD))
$gcd[0] = $gcd_list_right[$n - 2];
$gcd[$n - 1] = $gcd_list_left[$n - 2];
for ($i = 1; $i < $n - 1; $i++) {
    $gcd[$i] = gcd($gcd_list_left[$i - 1], $gcd_list_right[$n - 1 - $i]);
}

echo max($gcd), "\n";

function gcd($a, $b): int {
    return $gcd_memo[$a][$b] ?? ($b == 0 ? $a : gcd($b, $a % $b));
}


<?php
/**
 * ABC125
 * C - GCD on Blackboard
 */

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

// 累積GCDを計算
$gcd_list_left = [(int) $a[0]];
$gcd_list_right = [(int) $a[$n - 1]];
var_dump($gcd_list_left);
var_dump($gcd_list_right);
$gcd_memo = [];
for ($i = 1; $i < $n - 1; $i++) {
    $gcd_list_left[$i] = gcd($gcd_list_left[$i - 1], $a[$i]);
    $gcd_list_right[$i] = gcd($gcd_list_right[$i - 1], $a[$n - 1 - $i]);
}

// gcd((左累積GCD), (右累積GCD))
$gcd[0] = $gcd_list_right[$n - 2];
$gcd[$n - 1] = $gcd_list_left[1];
for ($i = 1; $i < $n - 1; $i++) {
    var_dump($gcd_list_left[$i]);
    var_dump($gcd_list_right[$n - 1 - $i]);
    $gcd[$i] = gcd($gcd_list_left[$i - 1], $gcd_list_right[$n - 1 - $i]);
}

echo max($gcd), "\n";

function gcd($a, $b): int {
    return $gcd_memo[$a][$b] ?? ($b == 0 ? $a : gcd($b, $a % $b));
}


<?php

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

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

$ans = [];
$ans[0] = 1;
$ans[1] = $arr[1];

for ($i = 2;$i < $n;$i++) {
    $ans[$i] = gcd(array_merge($ans, [$arr[$i - 1]]));
}
$lastGcd = 1;
for ($i = $n; $i - 2 > -1; $i--) {
    $lastGcd = gcd([$lastGcd, $arr[$i + 1] ?? 1]);
    $ans[$i] = gcd([$lastGcd, $ans[$i] ?? 1]);
}

echo max($ans) . PHP_EOL;

function gcd(array $list)
{
    $c = count($list);
    if ($c === 0) {
        return 0;
    } elseif ($c === 1) {
        return $list[0];
    }

    return calcGCD($list);
}
function calcGCD(array &$list)
{
    $c = count($list);

    $v = $list[$c - 1] % $list[$c - 2];
    if ($v === 0) {
        if ($c === 2) {
            return $list[$c - 2];
        }

        array_pop($list);

        return calcGCD($list);
    }
    $list[$c - 1] = $list[$c - 2];
    $list[$c - 2] = $v;

    return calcGCD($list);
}


<?php
function gcd(array $list)
{
    $c = count($list);
    if ($c === 0) {
        return 0;
    } elseif ($c === 1) {
        return $list[0];
    }

    return calcGCD($list);
}
function calcGCD(array &$list)
{
    $c = count($list);

    $v = $list[$c - 1] % $list[$c - 2];
    if ($v === 0) {
        if ($c === 2) {
            return $list[$c - 2];
        }

        array_pop($list);

        return calcGCD($list);
    }
    $list[$c - 1] = $list[$c - 2];
    $list[$c - 2] = $v;

    return calcGCD($list);
}

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

$arr = explode(' ', fgets(STDIN));
$intArr = [];
foreach ($arr as $a) {
    $intArr[] = (int) $a;
}
sort($intArr);
$min = min($intArr);
$max = max($intArr);
if ($min === $max) {
    echo $max . PHP_EOL;
    exit;
}
if ($intArr[0] === 1) {
    $intArr[0] = $max;
}
$gcdOnlyMinMax = gmp_gcd($min, $max);
$gcdAll = gcd($intArr);
echo max($gcdAll, $gcdOnlyMinMax) . PHP_EOL;


<?php

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

$gcd_max = 1;
$memo = [];

if ($n == 2) {
    echo max($a_arr), "\n";
    exit();
}

for ($i = 0; $i < $n; $i++) {
    $reduced_a_arr = $a_arr;
    unset($reduced_a_arr[$i]);
    $gcd = array_reduce($reduced_a_arr, 'gcd');
    if ($gcd > $gcd_max) {
        $gcd_max = $gcd;
    }
}

echo $gcd_max, "\n";

function gcd($a, $b) {
    if (isset($memo[$a][$b])) {
        return $memo[$a][$b];
    }
    $gcd =  $b ? gcd($b, $a % $b) : $a;
    $memo[$a][$b] = $gcd;
    return $gcd;
}


<?php
$n = trim(fgets(STDIN));
$vArray = explode(" ", trim(fgets(STDIN)));

foreach($vArray as $v){
    $dArray = divisor($v);
    foreach($dArray as $d){
        @$map[$d]++;
    }
}
$max = 1;
foreach($map as $value => $count){
    if($count >= $n - 1){
        $max = max($max, $value);
    }
}
echo $max;

function divisor($n){
    for($i = ceil(sqrt($n)); $i >= 1; $i--){
        if($n % $i == 0){
            $f[] = $i;
            $f[] = $n / $i;
        }
    }
    sort($f);
    return array_unique($f);
}


<?php
 fscanf(STDIN, "%d %d %d", $a, $b, $c);
  if ($a<$b){
 	 if($b/$a > $c){
 		  echo $c;
 		 }else if($b/$a < $c){
    	  echo $b/$a;
  	}
  }else {echo 0;}
  ?>

Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


<?php
  list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));

  echo min(intdiv($b, $a), $c);


<?php
fscanf(STDIN, "%d %d %d", $a, $b, $c);
$count = floor($b / $a);
var_dump($count);
echo ($count >= $c) ? $c : $count;


<?php
fscanf(STDIN, '%d %d %d', $a, $b, $c);
$ans = min((int)floor($b / $a), $c);
echo $ans . PHP_EOL;


<?php
list($a, $b, $c) = explode(' ', fgets(STDIN));
echo min($b / $a, $c);
?>


$stdins = [];
while (true) {
  $stdin = trim(fgets(STDIN));
  if ($stdin === '') {
    break;
  }
  $stdins[] = $stdin;
}
$nums = explode(' ', $stdins[0]);

$times = $nums[1] / $nums[0];
if ($times > $nums[2]) {
	$times = $nums[2];
}

print($times);


Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


<?php
fscanf(STDIN, "%d %d", $N, $K);
$h=explode(' ',trim(fgets(STDIN)));
$memo = array();
array_push($memo, 0);
for ($memo_index = 1; $memo_index < $N; $memo_index++) {
  array_push($memo, PHP_INT_MAX);
  $first_index = max($memo_index - $K, 0);
  for ($j = $first_index; $j < $memo_index; $j++) {
    $diff = $h[$memo_index] - $h[$j];
    if ($diff < 0) {
      $diff = $diff * -1;
    }
    $memo[$memo_index] = min($memo[$j] + $diff, $memo[$memo_index]);
  }
}
echo($memo[$N-1]);


<?PHP
$amount = fgets(STDIN);
$aaa = fgets(STDIN);
$heights = explode(" ", $aaa);
$kick_power=2;
$dps=[];

foreach (range(0, $ans-1) as $index) {
	$dps[$index] = INF;
	if($index===0){
		$dps[0]=0;
		continue;
	}
//	$dps[$index]=$dps[$index-1]+abs($heights[$index]-$heights[$index-1]);
	foreach (range(1, $kick_power) as $i) {
		if($index>=$i){
			$distanse=abs($dps[$index - $i] + abs($heights[$index] - $heights[$index - $i]));
			if ($dps[$index]> $distanse){$dps[$index]=$distanse;}
		}

	}
}

echo end($dps);


<?php

function myabs($value) {
  if (value < 0) {
    return $value * -1;
  }
  return $value;
}

fscanf(STDIN, "%d %d", $N, $K);
$h=explode(' ',trim(fgets(STDIN)));
$memo = array();
array_push($memo, 0);
for ($memo_index = 1; $memo_index < $N; $memo_index++) {
  array_push($memo, PHP_INT_MAX);
  $first_index = max($memo_index - $K, 0);
  for ($j = $first_index; $j < $memo_index; $j++) {
    $diff = myabs($h[$memo_index] - $h[$j]);
    $memo[$memo_index] = min($memo[$j] + $diff, $memo[$memo_index]);
  }
}
echo($memo[$N-1]);

?>


<?php
fscanf(STDIN, "%d %d", $N, $K);
$h=explode(' ',trim(fgets(STDIN)));
$memo = array();
array_push($memo, 0);
for ($memo_index = 1; $memo_index < $N; $memo_index++) {
  array_push($memo, PHP_INT_MAX);
  $first_index = max($memo_index - $K, 0);
  for ($j = $first_index; $j < $memo_index; $j++) {
    $memo[$memo_index] = min($memo[$j] + abs($h[$memo_index] - $h[$j]), $memo[$memo_index]);
  }
}
echo($memo[$N-1]);


<?php
$a=trim(fgets(STDIN));
$input=explode(' ',trim(fgets(STDIN)));
$goal = $input[$a-1];
$ans = 0;
for($i = 0; $i <= $a;){
  $now = $input[$i];
  $one = $input[$i+1];
  $two = $input[$i+2];
  if(abs($goal-$one)<abs($goal-$two)){
    $ans += abs($now-$one);
    $i++;
  }else{
    if(abs($goal-$one)>abs($goal-$two)){
      $ans += abs($now-$two);
      $i+=2;
  	}else{
      if(abs($now-$one)<abs($now-$two)){
        $ans += abs($now-$one);
    	$i++;
      }else{
        $ans += abs($now-$two);
      	$i+=2;
      }
    }
  }
}
print($ans-$goal);


<?php
fscanf(STDIN,'%d',$N);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
$resultArray = array();
$resultArray[] = 0;
$resultArray[] = abs($arrayH[1]-$arrayH[0]);
for($i=2;$i<$N;$i++){
  if($resultArray[$i-1]+abs($arrayH[$i]-$arrayH[$i-1])>=$resultArray[$i-2]+abs($arrayH[$i]-$arrayH[$i-2])){
    $resultArray[] = $resultArray[$i-2]+abs($arrayH[$i]-$arrayH[$i-2]);
  }else{
    $resultArray[] = $resultArray[$i-1]+abs($arrayH[$i]-$arrayH[$i-1]);
  }
}

echo $resultArray[$N-1];


<?php
fscanf(STDIN,'%d',$N);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
$resultArray = array();
$resultArray[] = 0;
$resultArray[] = abs($arrayH[1]-$arrayH[0]);
for($i=2;$i<$N;$i++){
  if(abs($resultArray[$i-1]+$arrayH[$i]-$arrayH[$i-1])>=$resultArray[$i-2]+abs($arrayH[$i]-$arrayH[$i-2])){
    $resultArray[] = $resultArray[$i-2]+abs($arrayH[$i]-$arrayH[$i-2]);
  }else{
    $resultArray[] = $resultArray[$i-1]+abs($arrayH[$i]-$arrayH[$i-1]);
  }
}

echo $resultArray[$N-1];


<!DOCTYPE html>

<meta name="keywords" content="Python,Brython">
<meta charset="iso-8859-1">
<title>A - Frog 1</title>

Input Area

<textarea name="text1" id="text1" cols="50" rows="10"></textarea>

<button id="frog">frog</button>
<button id="frog2">frog2</button>

out1

<button id="button7">button7</button>

zone7


Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($N,$K) = explode(" ",trim(fgets(STDIN)));
//$a = explode(" ",trim(fgets(STDIN)));
$hh = explode(" ",trim(fgets(STDIN)));
foreach($hh as $v) {
  $h[]=(int)$v;
}

$dp[0]=0;
for($i=1;$i<(int)$N;++$i) {
  $dp[$i]=PHP_INT_MAX;
  $limit = min($i,(int)$K);
  for($j=1;$j<=$limit;++$j) {
    $dp[$i]=min($dp[$i],$dp[$i-$j]+abs($h[$i]-$h[$i-$j]));
  }
}
printf("%d\n",$dp[$N-1]);


<?php
//error_reporting(0);
//$N = trim(fgets(STDIN));
list($N,$K) = explode(" ",trim(fgets(STDIN)));
//$a = explode(" ",trim(fgets(STDIN)));
$hh = explode(" ",trim(fgets(STDIN)));
foreach($hh as $v) {
  $h[]=(int)$v;
}

$dp[0]=0;
for($i=1;$i<$N;++$i) {
  $dp[$i]=PHP_INT_MAX;
  $limit = min($i,$K);
  for($j=1;$j<=$limit;++$j) {
    $dp[$i]=min($dp[$i],$dp[$i-$j]+abs($h[$i]-$h[$i-$j]));
  }
}
printf("%d\n",$dp[$N-1]);


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

$dp[0]=0;
for($i=1;$i<$N;$i++) {
  $dp[$i]=10**18;
  $limit = min($i,$K);
  for($j=1;$j<=$limit;$j++) {
    $dp[$i]=min($dp[$i],$dp[$i-$j]+abs($h[$i]-$h[$i-$j]));
  }
}
printf("%d\n",$dp[$N-1]);


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

$dp[0]=0;
for($i=1;$i<$N;$i++) {
  $dp[$i]=10**18;
  $limit = min($i,$K);
  for($j=1;$j<=$limit;$j++) {
    $dp[$i]=min($dp[$i],$dp[$i-$j]+abs($h[$i]-$h[$i-$j]));
  }
}
printf("%d\n",$dp[$N-1]);
~
~


<?php

function getInput (): array
{
    $s = str_replace(array("\r\n","\r","\n"), '', trim(fgets(STDIN)));
    $s = explode(" ", $s);
    foreach ($s as $k => $v) {
        $s[$k] = (int)$v;
    }
    return $s;
}

function func (int $dist = 0, int $sumCost = 0, array $memo = []): bool
{
    global $N, $K, $minCost, $h;

    // ベースケース
    if ($dist === $N) {
        if ($minCost > $sumCost) {
            $minCost = $sumCost;
        }
        return true;
    }

    if (array_key_exists($dist, $memo)) return $memo[$dist];

    for ($k = 1; $k <= $K; $k++) {
        if ($dist+$k > $N) break;
        $memo[$dist] = func($dist+$k, $sumCost+abs($h[$dist]-$h[$dist+$k]), $memo);
    }

    return false;
}

$tmp = getInput();
$N = $tmp[0] - 1; // $hの添字にあわせるためマイナス
$K = $tmp[1];
$minCost = PHP_INT_MAX;
$h = getInput();
func();
echo $minCost;


<?PHP
$first_line = fgets(STDIN);
$second_line = fgets(STDIN);
$first_line_array = explode(" ", $first_line);
$steps_amount=$first_line_array[0];
//ジャンプで飛べる足場の数
$skip_power=$first_line_array[1];
$steps_heights = explode(" ", $second_line);

//足場ごとにたどり着くまでのコストの総和の最小値を入れていく配列
$dps=[];

foreach (range(0, $steps_amount-1) as $index) {

    // とりあえず無限で初期化して、数を比較して最小値を入れていく
//    $dps[$index] = INF;

    // 最初にいた足場に辿り着くまでのコストは０
    if($index===0){
        $dps[0]=0;
        continue;
    }

    $dps[$index]=$dps[$index-1]+abs($steps_heights[$index]-$steps_heights[$index-1]);

    foreach (range(1, $skip_power) as $i) {
        if($index>=$i){
            if ($dps[$index]> abs($dps[$index - $i] + abs($steps_heights[$index] - $steps_heights[$index - $i]))){$dps[$index]=abs($dps[$index - $i] + abs($steps_heights[$index] - $steps_heights[$index - $i]));}
        }

    }
}

echo end($dps);


<?PHP
$first_line = fgets(STDIN);
$second_line = fgets(STDIN);
$first_line_array = explode(" ", $first_line);
$steps_amount=$first_line_array[0];
//ジャンプで飛べる足場の数
$skip_power=$first_line_array[1];
$steps_heights = explode(" ", $second_line);

$dps=[];

foreach (range(0, $steps_amount-1) as $index) {
    $dps[$index] = INF;
    if($index===0){
        $dps[0]=0;
        continue;
    }
    $dps[$index]=$dps[$index-1]+abs($steps_heights[$index]-$steps_heights[$index-1]);

    foreach (range(1, $skip_power) as $i) {
        if($index>=$i){
            if ($dps[$index]> abs($dps[$index - $i] + abs($steps_heights[$index] - $steps_heights[$index - $i]))){$dps[$index]=abs($dps[$index - $i] + abs($steps_heights[$index] - $steps_heights[$index - $i]));}
        }

    }
}

echo end($dps);


<?PHP
$ans = fgets(STDIN);
$aaa = fgets(STDIN);
$heights = explode(" ", $aaa);
$array = explode(" ", $ans);
$amount=$array[0];
$kick_power=$array[1];
$dps=[];

foreach (range(0, $amount-1) as $index) {
    $dps[$index] = INF;
    if($index===0){
        $dps[0]=0;
        continue;
    }
    $dps[$index]=$dps[$index-1]+abs($heights[$index]-$heights[$index-1]);

    foreach (range(1, $kick_power) as $i) {
        if($index>=$i){
            if ($dps[$index]> abs($dps[$index - $i] + abs($heights[$index] - $heights[$index - $i]))){$dps[$index]=abs($dps[$index - $i] + abs($heights[$index] - $heights[$index - $i]));}
        }

    }
}

echo end($dps);


<?php
fscanf(STDIN, "%d %d", $N, $K);
$h=explode(' ',trim(fgets(STDIN)));
$memo = array_fill(0, $N, PHP_INT_MAX);
$memo[0] = 0;
for ($memo_index = 1; $memo_index < $N; $memo_index++) {
  $first_index = max($memo_index - $K, 0);
  for ($j = $first_index; $j < $memo_index; $j++) {
    $diff = abs($h[$memo_index] - $h[$j]);
    $memo[$memo_index] = min($memo[$j] + $diff, $memo[$memo_index]);
  }
}
echo($memo[$N-1]);


<?php
fscanf(STDIN, "%d %d", $N, $K);
$h=explode(' ',trim(fgets(STDIN)));
$memo = array_fill(0, count($h), PHP_INT_MAX);
$memo[0] = 0;
for ($memo_index = 1; $memo_index < count($h); $memo_index++) {
  $first_index = ($memo_index - $K) >= 0 ? $memo_index - $K : 0;
  for ($j = $first_index; $j < $memo_index; $j++) {
    $diff = abs($h[$memo_index] - $h[$j]);
    $current_cost = $memo[$j] + $diff;
    $memo[$memo_index] = min($current_cost, $memo[$memo_index]);
  }
}
echo($memo[count($memo)-1]);


<?php
fscanf(STDIN, "%d %d", $N, $K);
$h=explode(' ',trim(fgets(STDIN)));
$memo = array_fill(0, count($h), PHP_INT_MAX);
$memo[0] = 0;
for ($memo_index = 1; $memo_index < count($h); $memo_index++) {
  $first_index = ($memo_index - $K) >= 0 ? $memo_index - $K : 0;
  for ($j = $first_index; $j < $memo_index; $j++) {
    $diff = $h[$memo_index] - $h[$j];
    if ($diff < 0) $diff * -1;
    $current_cost = $memo[$j] + $diff;
    if ($current_cost < $memo[$memo_index]) {
      $memo[$memo_index] = $current_cost;
    }
  }
}
echo($memo[count($memo)-1]);


<?php
$ans = fgets(STDIN);
$aaa = fgets(STDIN);
$heights = explode(" ", $aaa);
$array = explode(" ", $ans);
$amount=$array[0];
$kick_power=$array[1];
$dps=[];

foreach (range(0, $ans-1) as $index) {
	$dps[$index] = INF;
	if($index===0){
		$dps[0]=0;
		continue;
	}
	$dps[$index]=$dps[$index-1]+abs($heights[$index]-$heights[$index-1]);

	foreach (range(1, $kick_power) as $i) {
		if($index<$i){
			continue;
		}
		$dps[$index]	 = min($dps[$index], abs($dps[$index - $i] + abs($heights[$index] - $heights[$index - $i])));
	}
}

echo end($dps);


<?php
$ans = fgets(STDIN);
$aaa = fgets(STDIN);
$step_heights = explode(" ", $aaa);
$array = explode(" ", $ans);
$amount=$array[0];
$kick_power=$array[1];
$dps=[];

//var_dump($amount,$kick_power,$step_heights);
foreach (range(0, $ans-1) as $index) {
	$dps[$index] = INF;
	if($index===0){
		$dps[0]=0;
		continue;
	}
//	var_dump('______1個飛ばし_______',$dps[$index-1]+abs($step_heights[$index]-$step_heights[$index-1]));
	$dps[$index]=min($dps[$index],$dps[$index-1]+abs($step_heights[$index]-$step_heights[$index-1]));
//var_dump('______$dps[$index]_______',$dps[$index]);
//	if($index>=2){
//		var_dump('______２個飛ばし_______',$dps[$index-2]+abs($step_heights[$index]-$step_heights[$index-2]));
//		$dps[$index]=min($dps[$index],abs($dps[$index-2]+abs($step_heights[$index]-$step_heights[$index-2])));
//		var_dump('______$dps[$index]_______',$dps[$index]);
//
//	}

	foreach (range(1, $kick_power) as $i) {
		if($index>=$i){
			$dps[$index] = min($dps[$index], abs($dps[$index - $i] + abs($step_heights[$index] - $step_heights[$index - $i])));
		}
	}
}

//var_dump($dps);
echo end($dps);


<?php
list($n, $k) = explode(" ", trim(fgets(STDIN)));
$numbers = explode(" ", trim(fgets(STDIN)));
$dp = [0];
for($i=0; $i<$n; $i++){
	for($j=1; $j<=$k; $j++){
		$cost = $dp[$i] + abs($numbers[$i+$j] - $numbers[$i]);
		if(!isset($dp[$i+$j])){
			$dp[$i+$j] = $cost;
		}else{
			if($cost<$dp[$i+$j]){
				$dp[$i+$j] = $cost;
			}
		}
	}
}

echo $dp[$n-1] . "\n";


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
$start = $arrayH[0];
$goal = $arrayH[$N-1];
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($goal-$start);
}else{
  $pointerNow = 0;
  $pointerPrev = 0;
//  $pointerNext = -1;
  $result = 0;
  $minCost = 10000;
  $minPointer = 0;
  while(true){
    $pointerNow++;
    $minCostNow = abs($goal-$arrayH[$pointerNow]);
    if($minCostNow <= $minCost){
      $minPointer = $pointerNow;
      $minCost = $minCostNow;
    }
    if($pointerNow-$pointerPrev === $K){
      $result += abs($arrayH[$pointerPrev]-$arrayH[$minPointer]);
      $pointerPrev = $minPointer;
      $pointerNow = $minPointer;
      $minCost = 10000;
      if($pointerNow === $N-1){
        break;
      }
    }
    if($pointerNow === $N-1){
      $result += abs($arrayH[$pointerPrev]-$arrayH[$minPointer]);
      break;
    }
  }
  echo $result;
}


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($arrayH[$N-1]-$arrayH[0]);
}else{
  $resultArray = array();
  //初期位置のコストは0
  $resultArray[] = 0;
  //1回でジャンプできる箇所までのコスト最小値は、その場所と最初との差
  for($i=1;$i<=$K;$i++){
    $resultArray[] = abs($arrayH[$i]-$arrayH[0]);
  }
  //動的計画法
  for($i=$K+1;$i<$N;$i++){
    $highCounter = true;
    $highNear = 9999;
    $lowCounter = true;
    $lowNear = 1;
    $valueI = $arrayH[$i];
    $minValue = $resultArray[$i-1]+abs($valueI-$arrayH[$i-1]);
    if($valueI < $arrayH[$i-1]){
      $high = $resultArray[$i-1];
      $highCounter = false;
      $highNear = $arrayH[$i-1];
    }elseif($valueI > $arrayH[$i-1]){
      $low = $resultArray[$i-1];
      $lowCounter = false;
      $lowNear = $arrayH[$i-1];
    }else{ //elseif($valueI === $arrayH[$i-1])
      $resultArray[] = $minValue;
      continue;
    }
    //コスト最小値計算
    for($j=2;$j<=$K;$j++){
//    for($j=$K;$j>=2;$j--){
      if($valueI < $arrayH[$i-$j]){
        if($highCounter){
          $high = $resultArray[$i-$j];
          $highCounter = false;
          $highNear = $arrayH[$i-$j];
        }elseif($highNear <= $arrayH[$i-$j] && $high <= $resultArray[$i-$j]){
          continue;
        }else{
          $high = $resultArray[$i-$j];
          $highNear = $arrayH[$i-$j];
        }
      }elseif($valueI > $arrayH[$i-$j]){
        if($lowCounter){
          $low = $resultArray[$i-$j];
          $lowCounter = false;
          $lowNear = $arrayH[$i-$j];
        }elseif($lowNear >= $arrayH[$i-$j] && $low <= $resultArray[$i-$j]){
          continue;
        }else{
          $low = $resultArray[$i-$j];
          $lowNear = $arrayH[$i-$j];
        }
      }else{ //elseif($valueI === $arrayH[$i-$j])
        $minValue = $resultArray[$i-$j];
        break;
      }
      $value = $resultArray[$i-$j]+abs($valueI-$arrayH[$i-$j]);
      if($value < $minValue){
        $minValue = $value;
      }
    }
    $resultArray[] = $minValue;
  }
  echo $resultArray[$N-1];
}


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($arrayH[$N-1]-$arrayH[0]);
}else{
  $resultArray = array();
  //初期位置のコストは0
  $resultArray[] = 0;
  //1回でジャンプできる箇所までのコスト最小値は、その場所と最初との差
  for($i=1;$i<=$K;$i++){
    $resultArray[] = abs($arrayH[$i]-$arrayH[0]);
  }
  //動的計画法
  for($i=$K+1;$i<$N;$i++){
    $valueI = $arrayH[$i];
    $minValue = $resultArray[$i-1]+abs($valueI-$arrayH[$i-1]);
    //コスト最小値計算
//    for($j=2;$j<=$K;$j++){
    for($j=$K;$j>=2;$j--){
      if($valueI === $arrayH[$i-$j]){
        $minValue = $resultArray[$i-$j];
        break;
      }
      $value = $resultArray[$i-$j]+abs($valueI-$arrayH[$i-$j]);
      if($value < $minValue){
        $minValue = $value;
      }
    }
    $resultArray[] = $minValue;
  }
  echo $resultArray[$N-1];
}


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($arrayH[$N-1]-$arrayH[0]);
}else{
  $resultArray = array();
  //初期位置のコストは0
  $resultArray[] = 0;
  //1回でジャンプできる箇所までのコスト最小値は、その場所と最初との差
  for($i=1;$i<=$K;$i++){
    $resultArray[] = abs($arrayH[$i]-$arrayH[0]);
  }
  //動的計画法
  for($i=$K+1;$i<$N;$i++){
    $valueI = $arrayH[$i];
    $minValue = $resultArray[$i-1]+abs($valueI-$arrayH[$i-1]);
    //コスト最小値計算
//    for($j=2;$j<=$K;$j++){
      for($j=$K;$j>=2;$j--){
      $valueR = $resultArray[$i-$j];
      if($valueI === $valueR){
        $minValue = $valueR;
        break;
      }
      $value = $valueR+abs($valueI-$arrayH[$i-$j]);
      if($value < $minValue){
        $minValue = $value;
      }
    }
    $resultArray[] = $minValue;
  }
  echo $resultArray[$N-1];
}


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($arrayH[$N-1]-$arrayH[0]);
}else{
  $resultArray = array();
  //初期位置のコストは0
  $resultArray[] = 0;
  //1回でジャンプできる箇所までのコスト最小値は、その場所と最初との差
  for($i=1;$i<=$K;$i++){
    $resultArray[] = abs($arrayH[$i]-$arrayH[0]);
  }
  //動的計画法
  for($i=$K+1;$i<$N;$i++){
    $valueI = $arrayH[$i];
    $minNumber = $i-1;
    $minValue = $resultArray[$minNumber]+abs($valueI-$arrayH[$minNumber]);
    //コスト最小値計算
    for($j=2;$j<=$K;$j++){
      if($minValue === 0){
        break;
      }
      $ij = $i-$j;
      $value = $resultArray[$ij]+abs($valueI-$arrayH[$ij]);
/*
      if($value < $minValue){
        $minValue = $value;
      }
*/
      $minValue = min($value,$minValue);
    }
    $resultArray[] = $minValue;
  }
  echo $resultArray[$N-1];
}


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($arrayH[$N-1]-$arrayH[0]);
}else{
  $resultArray = array();
  $resultArray[] = 0;
  //1回でジャンプできる箇所までのコスト最小値は、その場所と最初との差
  for($i=1;$i<=$K;$i++){
    $resultArray[] = abs($arrayH[$i]-$arrayH[0]);
  }
  //動的計画法
  for($i=$K+1;$i<$N;$i++){
    $minNumber = $i-1;
    $minValue = $resultArray[$minNumber]+abs($arrayH[$i]-$arrayH[$minNumber]);
    //コスト最小値計算
    for($j=2;$j<=$K;$j++){
      if($minValue === 0){
        break;
      }
      $value = $resultArray[$i-$j]+abs($arrayH[$i]-$arrayH[$i-$j]);
      if($value < $minValue){
        $minNumber = $i-$j;
        $minValue = $value;
      }
    }
    $resultArray[] = $minValue;
  }
  echo $resultArray[$N-1];
}


<?php
fscanf(STDIN,'%d %d',$N,$K);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
//1回で最後までジャンプできる場合は、最初と最後の差がコスト最小値
if($N-1<=$K){
  echo abs($arrayH[$N-1]-$arrayH[0]);
}else{
  $resultArray = array();
  $resultArray[] = 0;
  //1回でジャンプできる箇所までのコスト最小値は、その場所と最初との差
  for($i=1;$i<=$K;$i++){
    $resultArray[] = abs($arrayH[$i]-$arrayH[0]);
  }
  //動的計画法
  for($i=$K+1;$i<$N;$i++){
    $minNumber = $i-1;
    $minValue = $resultArray[$minNumber]+abs($arrayH[$i]-$arrayH[$minNumber]);
    //コスト最小値計算
    $arrayValue = $i-2;
    for($j=2;$j<=$K;$j++){
      if($minValue === 0){
        break;
      }
      $value = $resultArray[$arrayValue]+abs($arrayH[$i]-$arrayH[$arrayValue]);
//      $value = $resultArray[$i-$j]+abs($arrayH[$i]-$arrayH[$i-$j]);
      if($value < $minValue){
        $minNumber = $arrayValue;
//        $minNumber = $i-$j;
        $minValue = $value;
      }
      $arrayValue--;
    }
    $resultArray[] = $minValue;
  }
  echo $resultArray[$N-1];
}


<?php
fscanf(STDIN,'%d',$N);
$H = fgets(STDIN);
$arrayH = explode(' ',$H);
$resultArray = array();
$resultArray[] = 0;
$resultArray[] = abs($arrayH[1]-$arrayH[0]);
for($i=2;$i<$N;$i++){
  if($resultArray[$i-1]+abs($arrayH[$i]-$arrayH[$i-1])>=$resultArray[$i-2]+abs($arrayH[$i]-$arrayH[$i-2])){
    $resultArray[] = $resultArray[$i-2]+abs($arrayH[$i]-$arrayH[$i-2]);
  }else{
    $resultArray[] = $resultArray[$i-1]+abs($arrayH[$i]-$arrayH[$i-1]);
  }
}


<?php
list($N, $K) = array_map("intval", explode(" ", trim(fgets(STDIN))));
$hArray = array_map("intval", explode(" ", trim(fgets(STDIN))));

$dp[0] = 0;
for($i = 1; $i < $N; $i++){
    $dp[$i] = 10**18;
    $limit = min($i, $K);
    for($j = 1; $j <= $limit; $j++){
        $dp[$i] = min($dp[$i], $dp[$i-$j] + abs($hArray[$i] - $hArray[$i-$j]));
    }
}
echo $dp[$N-1];


<!DOCTYPE html>

<meta name="keywords" content="Python,Brython">
<meta charset="iso-8859-1">
<title>B - Frog2</title>

Input Area

<textarea name="text1" id="text1" cols="50" rows="10"></textarea>

<button id="frog">frog</button>
<button id="frog2">frog2</button>

out1

<button id="button7">button7</button>

zone7


<?php
fscanf(STDIN,"%d %d",$n,$k);
$list = explode(' ', trim(fgets(STDIN)));

function chmin($main, $compare) {
    if ($main > $compare) {
        $mian = $compare;
    }
}
$dp = array_fill(0, $n, INF);
$dp[0] = 0;
for ($i = 0; $i < $n - 1; $i++) {
    for ($j = 1; $j <= $k; $j++) {
        if ($i < $n - $j) {
            $dp[$i + $j] = min($dp[$i + $j], $dp[$i] + abs($list[$i + $j] - $list[$i]));
        }
    }
}

echo $dp[$n - 1];


Score : 100 points

Problem Statement

There are N items, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), Item i has a weight of w_i and a value of v_i.

Taro has decided to choose some of the N items and carry them home in a knapsack.
The capacity of the knapsack is W, which means that the sum of the weights of items taken must be at most W.

Find the maximum possible sum of the values of items that Taro takes home.

Constraints

All values in input are integers.

1 \leq N \leq 100

1 \leq W \leq 10^5

1 \leq w_i \leq W

1 \leq v_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible sum of the values of items that Taro takes home.

Sample Input 1

3 8
3 30
4 50
5 60

Sample Output 1

90

Items 1 and 3 should be taken.
Then, the sum of the weights is 3 + 5 = 8, and the sum of the values is 30 + 60 = 90.

Sample Input 2

5 5
1 1000000000
1 1000000000
1 1000000000
1 1000000000
1 1000000000

Sample Output 2

5000000000

The answer may not fit into a 32-bit integer type.

Sample Input 3

6 15
6 5
5 6
6 4
6 6
3 5
7 2

Sample Output 3

17

Items 2, 4 and 5 should be taken.
Then, the sum of the weights is 5 + 6 + 3 = 14, and the sum of the values is 6 + 6 + 5 = 17.


<?PHP
$first_line = fgets(STDIN);
// 取得した入力値を半角スペースで分解します
$first_line_array = explode(" ", $first_line);
//複数の変数に値を一括代入する
list($item_num, $weight_upper) = $first_line_array;

for ($i = 0; $i < $item_num; ++$i) {
    fscanf(STDIN, "%d %d ", $x, $y);
    $weight[$i] = $x;
    $value[$i] = $y;
}

$dp = [];
// 使うアイテムが０個だった場合から一つずつアイテムを増やして検討していく
foreach (range(0, $item_num - 1) as $item_index) {
    $i_value = $value[$item_index];
    $i_weight = $weight[$item_index];
    // リュックが許容する重さが０だった場合から検討していき増やして検討していく
    foreach (range(1, $weight_upper) as $weight_index) {
        $current_value = $dp[$item_index - 1][$weight_index] ?? 0;
        if ($weight[$item_index] <= $weight_index) {
            $new_value = (($dp[$item_index - 1][$weight_index - $weight[$item_index]] ?? 0) + $i_value);
            $dp[$item_index][$weight_index] = $current_value >= $new_value ? $current_value : $new_value;
        } else {
            $dp[$item_index][$weight_index] = $current_value;
        };
    }
}
echo $dp[(int)$item_num - 1][(int)$weight_upper];


<?PHP
$single_line_input = fgets(STDIN);
// 取得した入力値を半角スペースで分解します
$array = explode(" ", $single_line_input);
//複数の変数に値を一括代入する
list($item_num, $weight_upper) = $array;

for ($i = 0; $i < $item_num; ++$i) {
    fscanf(STDIN, "%d %d ", $x, $y);
    $weight[$i] = $x;
    $value[$i] = $y;
}

$dp = [];
foreach (range(0, $item_num - 1) as $item_index) {
    $i_value = $value[$item_index];
    $i_weight = $weight[$item_index];
    foreach (range(1, $weight_upper) as $weight_index) {
        $current_value = $dp[$item_index - 1][$weight_index] ?? 0;
        if ($weight[$item_index] <= $weight_index) {
            $new_value = (($dp[$item_index - 1][$weight_index - $weight[$item_index]] ?? 0 )+ $i_value);
            $dp[$item_index][$weight_index] = $current_value >= $new_value ? $current_value : $new_value;
        } else {
            $dp[$item_index][$weight_index] = $current_value;
        };
    }
}
echo $dp[(int)$item_num - 1][(int)$weight_upper];


<?PHP
$single_line_input = fgets(STDIN);
// 取得した入力値を半角スペースで分解します
$array = explode(" ", $single_line_input);
//複数の変数に値を一括代入する
list($item_num, $weight_upper) = $array;

for ($i = 0; $i < $item_num; ++$i) {
    fscanf(STDIN, "%d %d ", $x, $y);
    $weight[$i] = $x;
    $value[$i] = $y;
}

$dp = [];
foreach (range(1, $item_num - 1) as $item_index) {
    $i_value = $value[$item_index];
    $i_weight = $weight[$item_index];
    foreach (range(1, $weight_upper) as $weight_index) {
        $current_value = $dp[$item_index - 1][$weight_index] ?? 0;
        if ($weight[$item_index] <= $weight_index) {
            $new_value = ($dp[$item_index - 1][$weight_index - $weight[$item_index]] + $i_value);
            $dp[$item_index][$weight_index] = $current_value >= $new_value ? $current_value : $new_value;
        } else {
            $dp[$item_index][$weight_index] = $current_value;
        };
    }
}
echo $dp[(int)$item_num - 1][(int)$weight_upper];


<?PHP
$single_line_input = fgets(STDIN);
// 取得した入力値を半角スペースで分解します
$array = explode(" ", $single_line_input);
$item_num = $array[0];
$weight_upper = $array[1];
for($i=0;$i<$array[0];++$i){
    fscanf(STDIN,"%d %d ",$x,$y);
    $weight[$i]=$x;
    $value[$i]=$y;
}

//$dp = array_fill(0, $item_num+1, array_fill(0, $weight_upper+1, 0));
$dp = [];
foreach (range(0, $item_num-1) as $item_index) {
    $i_value = $value[$item_index];
    $i_weight = $weight[$item_index];
    foreach (range(0, $weight_upper) as $weight_index) {
$zantei=$dp[$item_index-1][$weight_index]?? 0;
        if($weight[$item_index] <= $weight_index) {
            $dp[$item_index][$weight_index]=max($zantei,($dp[$item_index-1][$weight_index-$weight[$item_index]] +$i_value));
        }else{$dp[$item_index][$weight_index] = $zantei ;}

    }
}
echo $dp[(int)$item_num-1][(int)$weight_upper];


<?PHP
$single_line_input = fgets(STDIN);
// 取得した入力値を半角スペースで分解します
$array = explode(" ", $single_line_input);
$item_num = $array[0];
$weight_upper = $array[1];
for($i=0;$i<$array[0];++$i){
    fscanf(STDIN,"%d %d ",$x,$y);
    $weight[$i]=$x;
    $value[$i]=$y;
}

$dp = array_fill(0, $item_num+1, array_fill(0, $weight_upper+1, 0));
//var_dump('dp',$dp);

foreach (range(0, $item_num-1) as $item_index) {
    $i_value = $value[$item_index];
    $i_weight = $weight[$item_index];
//    var_dump('vとw', $i_value, $i_weight);
    foreach (range(0, $weight_upper) as $weight_index) {

        if($weight[$item_index] <= $weight_index) {
//            var_dump('今回のと前のやつ', $dp[$item_index-1][$weight_index] ?? 0+$i_value, ($dp[$item_index-1][$weight_index-$weight[$item_index]] ?? 0));
            $dp[$item_index][$weight_index]=max($dp[$item_index-1][$weight_index],($dp[$item_index-1][$weight_index-$weight[$item_index]] +$i_value));
        }else{$dp[$item_index][$weight_index] = ($dp[$item_index-1][$weight_index] ?? 0 );}

    }
}
echo $dp[(int)$item_num-1][(int)$weight_upper];


<?php
list($N, $W) = array_map("intval", explode(" ", trim(fgets(STDIN))));
for($i = 0; $i < $N; $i++){
    $map[] = array_map("intval", explode(" ", trim(fgets(STDIN))));
}
array_unshift($map,[]);
for($i = 0; $i <= $N; $i++){
    for($j = 0; $j <= $W; $j++){
        $dp[$i][$j] = 0;
    }
}

echo $dp[$N][$W];


<?php
$w = [];
$v = [];
fscanf(STDIN, "%d %d", $N, $W);
for ($i = 0; $i < $N; $i++) {
    fscanf(STDIN, "%d %d", $w[$i], $v[$i]);
}

$current = new SplFixedArray($W+1);
$next = new SplFixedArray($W+1);

for ($j=0; $j <= $W; $j++) {
    $current[$j] = 0;
}

for ($i = 0; $i < $N; $i++) {
    for ($j = 0; $j <= $W; $j++) {
        if ($j >= $w[$i]) {
            $next[$j] = max($current[$j-$w[$i]] + $v[$i], $current[$j]);
        } else {
            $next[$j] = $current[$j];
        }
    }
    for ($j = 0; $j <= $W; $j++) {
        $current[$j] = $next[$j];
      $next[$j] = 0;
    }
}

$result = 0;
foreach ($current as $v) {
    if ($v >= $result) {
        $result = $v;
    }
}
echo $result."\n";


<?php
$a = str();
$b = str();

echo lcs($a, $b);

function lcs($str1, $str2){
    global $dp,$dpf;
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    $dp = array_fill(-1, $l1+1, array_fill(-1, $l2+1, 0));
    for($i = 0; $i < $l1; $i++){
        $dpb = $dp[$i-1];
        $dpi = &$dp[$i];
        $si = $str1[$i];
        $dpfi = [];
        for($j = 0; $j < $l2; $j++){
            if($si == $str2[$j]){
                $dpi[$j] = $dpb[$j-1] + 1;
                $dpfi[$j] = 1;
            }elseif($dpb[$j] > $dpi[$j-1]){
                $dpi[$j] = $dpb[$j];
                $dpfi[$j] = 2;
            }else{
                $dpi[$j] = $dpi[$j-1];
                $dpfi[$j] = 3;
            }
        }
        $dpf[] = $dpfi;
    }
    return $dp[$l1 - 1][$l2 - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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 : 100 points

Problem Statement

You are given strings s and t.
Find one longest string that is a subsequence of both s and t.

Notes

A subsequence of a string x is the string obtained by removing zero or more characters from x and concatenating the remaining characters without changing the order.

Constraints

s and t are strings consisting of lowercase English letters.

1 \leq |s|, |t| \leq 3000

Input

Input is given from Standard Input in the following format:

s
t

Output

Print one longest string that is a subsequence of both s and t.
If there are multiple such strings, any of them will be accepted.

Sample Input 1

axyb
abyxb

Sample Output 1

axb

The answer is axb or ayb; either will be accepted.

Sample Input 2

aa
xayaz

Sample Output 2

aa

Sample Input 3

a
z

Sample Output 3

The answer is (an empty string).

Sample Input 4

abracadabra
avadakedavra

Sample Output 4

aaadara


<?php
$a = str();
$b = str();

echo lcs($a, $b);

function lcs($str1, $str2){
    global $dp;
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    $dp = array_fill(-1, $l1+1, array_fill(-1, $l2+1, 0));
    for($i = 0; $i < $l1; $i++){
        $dpb = $dp[$i-1] ?? $dp[$i];
        $dpi = &$dp[$i];
        $si = $str1[$i];
        for($j = 0; $j < $l2; $j++){
            if($si == $str2[$j]){
                $dpi[$j] = $dpb[$j-1] + 1;
            }else{
                $dpi[$j] = max($dpb[$j], $dpi[$j-1]);
            }
        }
    }
    return $dp[$l1 - 1][$l2 - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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
$a = str();
$b = str();

echo lcs($a, $b);

function lcs($str1, $str2){
    global $dp;
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    $dp = array_fill(0, $l1, array_fill(0, $l2, 0));
    for($i = 0; $i < $l1; $i++){
        $dpb = $dp[$i-1] ?? $dp[$i];
        $dpi = &$dp[$i];
        for($j = 0; $j < $l2; $j++){
            if($str1[$i] == $str2[$j]){
                $dpi[$j] = ($dpb[$j-1]??0) + 1;
            }else{
                $dpi[$j] = max($dpb[$j], $dpi[$j-1]??0);
            }
        }
    }
    return $dp[$l1 - 1][$l2 - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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
$a = str();
$b = str();

echo lcs($a, $b);

function lcs($str1, $str2){
    global $dp;
    for($i = 0; $i < strlen($str1); $i++){
        $dpb = $dp[$i-1];
        $dpi = &$dp[$i];
        for($j = 0; $j < strlen($str2); $j++){
            if($str1[$i] == $str2[$j]){
                $dpi[$j] = ($dpb[$j-1]??0) + 1;
            }else{
                $dpi[$j] = max($dpb[$j]??0, $dpi[$j-1]??0);
            }
        }
    }
    return $dp[strlen($str1) - 1][strlen($str2) - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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
$a = str();
$b = str();

echo lcs($a, $b);

function lcs($str1, $str2){
    global $dp;
    for($i = 0; $i < strlen($str1); $i++){
        for($j = 0; $j < strlen($str2); $j++){
            if($str1[$i] == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??0) + 1;
            }else{
                $dp[$i][$j] = max($dp[$i-1][$j]??0, $dp[$i][$j-1]??0);
            }
        }
    }
    return $dp[strlen($str1) - 1][strlen($str2) - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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
$a = str();
$b = str();

echo lcstr($a, $b);

function lcs($str1, $str2){
    global $dp;
    for($i = 0; $i < strlen($str1); $i++){
        for($j = 0; $j < strlen($str2); $j++){
            if($str1[$i] == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??0) + 1;
            }else{
                $dp[$i][$j] = max($dp[$i-1][$j]??0, $dp[$i][$j-1]??0);
            }
        }
    }
    return $dp[strlen($str1) - 1][strlen($str2) - 1];
}

function lcstr($str1, $str2){
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    for($i = 0; $i < $l1; $i++){
        $s1 = $str1[$i];
        for($j = 0; $j < $l2; $j++){
            if($s1 == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??'') . $s1;
            }else{
                if(strlen($dp[$i-1][$j]??'') > strlen($dp[$i][$j-1]??'')){
                    $dp[$i][$j] = $dp[$i-1][$j]??'';
                }else{
                    $dp[$i][$j] = $dp[$i][$j-1]??'';
                }
            }
        }
    }
    return $dp[$l1 - 1][$l2 - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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
$a = str();
$b = str();

echo lcstr($a, $b);

function lcs($str1, $str2){
    global $dp;
    for($i = 0; $i < strlen($str1); $i++){
        for($j = 0; $j < strlen($str2); $j++){
            if($str1[$i] == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??0) + 1;
            }else{
                $dp[$i][$j] = max($dp[$i-1][$j]??0, $dp[$i][$j-1]??0);
            }
        }
    }
    return $dp[strlen($str1) - 1][strlen($str2) - 1];
}

function lcstr($str1, $str2){
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    for($i = 0; $i < $l1; $i++){
        for($j = 0; $j < $l2; $j++){
            if($str1[$i] == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??'') . $str1[$i];
            }else{
                if(strlen($dp[$i-1][$j]??'') > strlen($dp[$i][$j-1]??'')){
                    $dp[$i][$j] = $dp[$i-1][$j]??'';
                }else{
                    $dp[$i][$j] = $dp[$i][$j-1]??'';
                }
            }
        }
    }
    return $dp[$l1 - 1][$l2 - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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
$a = str();
$b = str();

echo lcstr($a, $b);

function lcs($str1, $str2){
    global $dp;
    for($i = 0; $i < strlen($str1); $i++){
        for($j = 0; $j < strlen($str2); $j++){
            if($str1[$i] == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??0) + 1;
            }else{
                $dp[$i][$j] = max($dp[$i-1][$j]??0, $dp[$i][$j-1]??0);
            }
        }
    }
    return $dp[strlen($str1) - 1][strlen($str2) - 1];
}

function lcstr($str1, $str2){
    $l1 = strlen($str1);
    $l2 = strlen($str2);
    for($i = 0; $i < $l1; $i++){
        for($j = 0; $j < $l2; $j++){
            if($str1[$i] == $str2[$j]){
                $dp[$i][$j] = ($dp[$i-1][$j-1]??'') . $str1[$i];
            }else{
                if(strlen($dp[$i-1][$j]??'') > strlen($dp[$i][$j-1]??'')){
                    $dp[$i][$j] = $dp[$i-1][$j]??'3';
                }else{
                    $dp[$i][$j] = $dp[$i][$j-1]??'3';
                }
            }
        }
    }
    return $dp[$l1 - 1][$l2 - 1];
}

function str(){
  return trim(fgets(STDIN));
}
function ints(){
  return array_map("intval", explode(" ", trim(fgets(STDIN))));
}
function int(){
  return intval(trim(fgets(STDIN)));
}
function chmax(&$a,$b){if($a<$b){$a=$b;return 1;}return 0;}
function chmin(&$a,$b){if($a>$b){$a=$b;return 1;}return 0;}

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

$dirty_s = str_split(fgets(STDIN));
$dirty_t = str_split(fgets(STDIN));
$double_used_words = array_intersect($dirty_s, $dirty_t);
$washed_s = array_intersect($dirty_s, $double_used_words);
$washed_t = array_intersect($dirty_t, $double_used_words);

$dp = [];
foreach ($washed_s as $s_index => $s) {
    foreach ($washed_t as $t_index => $t) {
        if ($t === $s) {
            $dp[$s_index][$t_index] = $dp[$s_index - 1][$t_index -1] + 1;
        } else {
            $x = $dp[$s_index][$t_index - 1];
            $y = $dp[$s_index - 1][$t_index];
            $dp[$s_index][$t_index] = max($x, $y);
        }
    }
}

$answer = '';
foreach (end($dp) as $index => $value) {
    if ($index == 1 && $value == 1 || $value - $dp[$index - 1] = 1) {
        $answer .= $washed_s[$index];
    }
}

echo ' ';


<?php
$dirty_s = str_split(fgets(STDIN));
$dirty_t = str_split(fgets(STDIN));
$double_used_words = array_intersect($dirty_s, $dirty_t);
$washed_s = array_intersect($dirty_s, $double_used_words);
$washed_t = array_intersect($dirty_t, $double_used_words);

$dp = [];
foreach ($washed_s as $s_index => $s) {
    foreach ($washed_t as $t_index => $t) {

        if ($t === $s) {
            $new = $dp[$s_index][$t_index - 1] + 1;
            $old = $dp[$s_index - 1][$t_index];
            $dp[$s_index][$t_index] = max($new, $old);
        } else {
            $new = $dp[$s_index][$t_index - 1];
            $old = $dp[$s_index - 1][$t_index];
            $dp[$s_index][$t_index] = max($new, $old);
        }
    }
}

$answer='';
foreach (end($dp) as $index => $value) {
    if($index==1&&$value==1||$value-$dp[$index-1]=1){
        $answer .= $washed_s[$index];
    }
}
if($answer==''){echo' ';}else{echo $answer;}


<?php

fscanf(STDIN, '%d', $D);

if ($D === 25) {
    echo 'Christmas';
} elseif ($D === 24) {
    echo 'Christmas Eve';
} elseif ($D === 23) {
    echo 'Christmas Eve Eve';
} elseif ($D === 22) {
    echo 'Christmas Eve Eve Eve';
}

echo PHP_EOL;

Score : 100 points

Problem Statement

In some other world, today is December D-th.

Write a program that prints Christmas if D = 25, Christmas Eve if D = 24, Christmas Eve Eve if D = 23 and Christmas Eve Eve Eve if D = 22.

Constraints

22 \leq D \leq 25

D is an integer.

Input

Input is given from Standard Input in the following format:

D

Output

Print the specified string (case-sensitive).

Sample Input 1

25

Sample Output 1

Christmas

Sample Input 2

22

Sample Output 2

Christmas Eve Eve Eve

Be sure to print spaces between the words.


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

switch ($d) {
    case $d === 22:
        echo 'Christmas Eve Eve Eve';
        break;
    case $d === 23:
        echo 'Christmas Eve Eve';
        break;
    case $d === 24:
        echo 'Christmas Eve';
        break;
    case $d === 25:
        echo 'Christmas';
        break;
}


<?php
fscanf(STDIN, "%d", $d);
$x = 'Christmas';
echo $x, str_repeat(' Eve', 25 - $d);


<?php
$x = fgets(STDIN);

echo "Christmas";

if ($x == 24) {
    echo " Eve";
} elseif ($x == 23) {
    echo " Eve Eve";
} elseif ($x == 22) {
    echo " Eve Eve Eve";
}


<?php

$s = trim(fgets(STDIN));
echo 'Christmas';
for($i=0; $i<25-$s; $i++){
  echo ' '.'Eve';
}

?>


<?php
fscanf(STDIN, "%d", $d);
if($d==25){
  echo 'Christmas';
}
elseif($d==24){
  echo 'Christmas Eve';
}
else if($d==23){
  echo 'Christmas Eve Eve';
}
else if($d==22){
  echo 'Christmas Eve Eve Eve';
}

?>


<?php
fscanf(STDIN, "%d", $d);
if($d == 25){
    echo "Christmas";
}elseif($d == 24){
    echo "Christmas Eve";
}elseif($d == 23){
    echo "Christmas Eve Eve";
}else{
    echo "Christmas Eve Eve Eve";
}
?>


            <?php
            fscanf(STDIN, "%d", $d);
            switch ($d) {
            case 22:
                echo "Christmas Eve Eve Eve"."\n";
                break;
            case 23:
                echo "Christmas Eve Eve"."\n";
                break;
            case 24:
                echo "Christmas Eve"."\n";
                break;
            case 25:
                echo "Christmas"."\n";
                break;
        }
            ?>


<?php
$f = fopen( 'php://stdin', 'r' );
$line = fgets($f);
$eve = ' Eve';
$day = (int)$line;
$output = 'Christmas';
for ($i = 1; $i <= (25 - $day); $i++) {
    $output = $output.$eve;
}
echo($output);


<?php
$N = fgets(STDIN);
if($N ==25){
print('Christmas');
}
if($N ==24){
print('Christmas Eve');
}
if($N ==23){
print('Christmas Eve Eve');
}
if($N ==22){
print('Christmas Eve Eve Eve');
}


<?php
fscanf(STDIN,'%d',$D);
if($D == 25){
  echo "Christmas";
}elseif ($D == 24) {
  // code...
  echo "Christmas Eve";
}elseif ($D == 23) {
  // code...
  echo "Christmas Eve Eve";
}else {
  // code...
  echo "Christmas Eve Eve Eve";
}

 ?>


<?php

//input
fscanf(STDIN,"%d",$day);

echo "Christmas";

for(;$day<25;$day++){
    echo " Eve";
}


<?php
# get a integer
fscanf(STDIN, "%d", $num);
$output = "";
if($num<=25 && $num>=22){
 $output = 'Christmas';
  for($i=$num;$i<25;$i++){
   $output = $output . " Eve";
  }

}
echo $output;
?>


<?php
# get a integer
fscanf(STDIN, "%d", $num);
$output = "";
if($d<=25 && $d>=22){
 $output = 'Christmas';
  for($i=$d;$i<25;$i++){
   $output = $output . " Eve";
  }

}
echo $output;
?>


<?php
$a = fgets(STDIN);
if ( $a == 22 ) {
 echo "Christmas Eve Eve Eve";
}elseif ($a ==23 ){
  echo "Christmas Eve Eve";
}elseif ($a ==24 ){
  echo "Christmas Eve";
}elseif ($a ==25 ){
  echo "Christmas";
}
?>


<?php

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

if ($a == 25) {
    echo "Christmas\n";
} else if ($a == 24) {
    echo "Christmas Eve\n";
} else if ($a == 23) {
    echo "Christmas Eve Eve\n";
} else if ($a == 22) {
    echo "Christmas Eve Eve Eve\n";
}


<?php
$N = trim(fgets(STDIN));
if ($N == 25){
echo 'Christmas';
}elseif ($N == 24){
echo 'Christmas Eve';
}elseif ($N ==23){
echo 'Christmas Eve Eve';
}else {
echo  'Christmas Eve Eve Eve';
}


<?php

function input($func = null) {
    if ($func === null) {
        return trim(fgets(STDIN));
    } else {
        return $func(trim(fgets(STDIN)));
    }
}
function input_array($func = null) {
    if ($func === null) {
        return explode(' ', input());
    } else {
        return array_map(function($v) use ($func) {
            return $func($v);
        }, explode(' ', input()));
    }
}

$d = input('intval');

echo 'Christmas';
for ($i = 0, $max = 25 - $d; $i < $max; $i++) {
    echo ' Eve';
}
echo "\n";


<?php

fscanf(STDIN, "%d", $n);
$H = []; $X = []; $Y = [];
for ($i = 0; $i < $n; ++$i) {
    fscanf(STDIN, "%d %d %d", $x, $y, $h);
    $X[] = $x; $Y[] = $y; $H[] = $h;
}

$ans;
for ($cx = 0; $cx <= 100; ++$cx) {
    for ($cy = 0; $cy <= 100; ++$cy) {

        // Hが0になるパターンも含んで列挙する
        $tmp = [];
        for ($i = 0; $i < $n; ++$i) {
            $tmp[] = $H[$i] + abs($X[$i] - $cx) + abs($Y[$i] - $cy);
        }
        $tmp = array_unique($tmp);

        // Hが0になっていないことを検証する
        foreach ($tmp as $hh) {
            // $hh: Hの候補
            $flg = true;
            for ($i = 0; $i < $n; ++$i) {

$tmax = max($hh - abs($X[$i] - $cx) - abs($Y[$i] - $cy), 0);

/* echo "tmax: $tmax, hh: $hh", PHP_EOL; */

                if ($tmax != $H[$i]) {
                    $flg = false;
                    break;
                }
            }
            if ($flg) {
                $ans = $hh;
/* echo "cx: $cx, cy: $cy, arr: " . implode(' ', $tmp), PHP_EOL; */
                break 3;
            }
        }

    }
}

echo sprintf("%d %d %d\n", $cx, $cy, $ans);

Score: 300 points

Problem Statement

In the Ancient Kingdom of Snuke, there was a pyramid to strengthen the authority of Takahashi, the president of AtCoder Inc.

The pyramid had center coordinates (C_X, C_Y) and height H. The altitude of coordinates (X, Y) is max(H - |X - C_X| - |Y - C_Y|, 0).

Aoki, an explorer, conducted a survey to identify the center coordinates and height of this pyramid. As a result, he obtained the following information:

C_X, C_Y was integers between 0 and 100 (inclusive), and H was an integer not less than 1.

Additionally, he obtained N pieces of information. The i-th of them is: "the altitude of point (x_i, y_i) is h_i."

This was enough to identify the center coordinates and the height of the pyramid. Find these values with the clues above.

Constraints

N is an integer between 1 and 100 (inclusive).

x_i and y_i are integers between 0 and 100 (inclusive).

h_i is an integer between 0 and 10^9 (inclusive).

The N coordinates (x_1, y_1), (x_2, y_2), (x_3, y_3), ..., (x_N, y_N) are all different.

The center coordinates and the height of the pyramid can be uniquely identified.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1 h_1
x_2 y_2 h_2
x_3 y_3 h_3
:
x_N y_N h_N

Output

Print values C_X, C_Y and H representing the center coordinates and the height of the pyramid in one line, with spaces in between.

Sample Input 1

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

Sample Output 1

2 2 6

In this case, the center coordinates and the height can be identified as (2, 2) and 6.

Sample Input 2

2
0 0 100
1 1 98

Sample Output 2

0 0 100

In this case, the center coordinates and the height can be identified as (0, 0) and 100.

Note that C_X and C_Y are known to be integers between 0 and 100.

Sample Input 3

3
99 1 191
100 1 192
99 0 192

Sample Output 3

100 0 193

In this case, the center coordinates and the height can be identified as (100, 0) and 193.


<?php

$input = trim(fgets(STDIN));
$input = explode(" ", $input);
$n_max = (int) $input[0];

$count = 0;
while (true) {
	$input = trim(fgets(STDIN));
	$input = explode(" ", $input);
	$args[$count] = [
		'x' => (int) $input[0],
		'y' => (int) $input[1],
		'h' => (int) $input[2],
	];
	++$count;
	if ($count >= $n_max) {
		break;
	}
}

for ($x=0; $x <= 100 ; $x++) {
	for ($y=0; $y <= 100 ; $y++) {
		$ok = true;
		$check_prev = null;
		for ($n=0; $n < $n_max; $n++) {
			$tmp = $args[$n];
			if ($tmp['h'] === 0) {
				continue;
			}
			$check = abs($x - $tmp['x']) + abs($y - $tmp['y']) + $tmp['h'];
			if (is_null($check_prev)) {
				$check_prev = $check;
			}else{
				if ($check_prev !== $check) {
					$ok = false;
					break;
				}
			}
		}
		if ($ok) {
			echo $x . ' ' . $y . ' ' . $check;
			exit(0);
		}
	}
}


<?php

$input = trim(fgets(STDIN));
$input = explode(" ", $input);
$n_max = (int) $input[0];

$count = 0;
while (true) {
	$input = trim(fgets(STDIN));
	$input = explode(" ", $input);
	$args[] = [
		'x' => (int) $input[0],
		'y' => (int) $input[1],
		'h' => (int) $input[2],
	];
	++$count;
	if ($count >= $n_max) {
		break;
	}
}

for ($x=0; $x <= 100 ; $x++) {
	for ($y=0; $y <= 100 ; $y++) {
		$ok = true;
		for ($n=0; $n < $n_max; $n++) {
			$tmp = $args[$n];
			$check = abs($x - $tmp['x']) + abs($y - $tmp['y']) + $tmp['h'];
			if ($n == 0) {
				$check_prev = $check;
			}else{
				if ($check_prev !== $check) {
					$ok = false;
					break;
				}
			}
		}
		if ($ok) {
			echo $x . ' ' . $y . ' ' .$check;
		}
	}
}


Score : 100 points

Problem Statement

You have decided to give an allowance to your child depending on the outcome of the game that he will play now.

The game is played as follows:

There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a + printed on it.

The player should construct a formula of the form X + Y, by arranging the four panels from left to right. (The operator panel should not be placed at either end of the formula.)

Then, the amount of the allowance will be equal to the resulting value of the formula.

Given the values A, B and C printed on the integer panels used in the game, find the maximum possible amount of the allowance.

Constraints

All values in input are integers.

1 \leq A, B, C \leq 9

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the maximum possible amount of the allowance.

Sample Input 1

1 5 2

Sample Output 1

53

The amount of the allowance will be 53 when the panels are arranged as 52+1, and this is the maximum possible amount.

Sample Input 2

9 9 9

Sample Output 2

108

Sample Input 3

6 6 7

Sample Output 3

82