Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.

ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.

<?php
    $strs[0] = fgets(STDIN);
    $strs[1] = fgets(STDIN);

    $punkts_count = explode(" ", $strs[0])[0];
    $max_km = explode(" ", $strs[0])[1];
    $punkts = explode(" ", $strs[1]);

    $bikes_count = 1;
    $km_count = $max_km;

    for($i=0;$i<$punkts_count-1;$i++) {
        $n1 = $i+1;
        $offset = $punkts[$n1]-$punkts[$i];

        if($offset > $max_km) {
			die("-1");
		}
        elseif($offset > $km_count) {
            $bikes_count++;
            $km_count = $max_km;
        }

        $km_count = $km_count-$offset;
    }

    echo $bikes_count;
?>

<?php
$arr = explode(" ",fgets(STDIN));
$count_points_n = intval($arr[0]);
$max_rande_k = intval($arr[1]);
$arr = NULL;
$arr_x = explode(" ",fgets(STDIN));

$min_count_points = 1;
for($i = 0; $i < $count_points_n; $i++){
    $point = $i;
    $flag = true;
    $cur_range = $arr_x[$i] + $max_rande_k;
    $is_succses = 0;
    while($flag) {
        $point++;
        if ($cur_range >= $arr_x[$point]) {
            $i = $point - 1;
            if($point >= $count_points_n){
                break;
            }
            $is_succses = 1;
        }
        else{
            $min_count_points++;
            break;
        }
    }
    if(!$is_succses){
        $min_count_points = -1;
        break;
    }
}
echo $min_count_points;
?>

<?php
list($count, $range) = explode(" ", fgets(STDIN));
$count = (int) $count;
$range = (int) $range;
$arr = explode(" ", fgets(STDIN));
$velo = 0;

$pos = $arr[0];
for($i = 1; $i < $count; $i++){
    if($arr[$i] > $pos){
    	$pos = $arr[$i-1] + $range;
		if($arr[$i] > $pos){
			$velo = -1;
			break;
		} else {$velo ++;}
    }
}
echo $velo."  ";

<?php
	list($bicycle_rental_count, $max_distance) = explode(" ", fgets(STDIN));
	$bicycle_rental_count = (int) $bicycle_rental_count;
	$max_distance = (int) $max_distance;
	$bicycle_rental_coords = explode(" ", fgets(STDIN));

	if(count($bicycle_rental_coords) != $bicycle_rental_count) die();
	if($bicycle_rental_count < 2 || $bicycle_rental_count > 1000) die();
	if($max_distance < 1 || $max_distance > 100000) die();
	if($bicycle_rental_coords[0] < 0 || $bicycle_rental_coords[$bicycle_rental_count-1] > 100000) die();

	$bicycle_count = 1; $distance_remain = $max_distance;
	for($i = 1; $i <= count($bicycle_rental_coords); $i++){
		if(($max_distance - ($bicycle_rental_coords[$i] - $bicycle_rental_coords[$i-1])) < 0){
			$bicycle_count = -1;
			break;
		}

		if($distance_remain == 0 && $i != count($bicycle_rental_coords) - 1){
			$bicycle_count++;
			$distance_remain = $max_distance;
		} else
		if($i == count($bicycle_rental_coords) - 1){
		    $distance_remain = $distance_remain - ($bicycle_rental_coords[$i] - $bicycle_rental_coords[$i-1]);
		    if($distance_remain < 0){
		        $bicycle_count++;
		    }
		    break;
		}

		$distance_remain = $distance_remain - ($bicycle_rental_coords[$i] - $bicycle_rental_coords[$i-1]);

		if($distance_remain < 0){
			$bicycle_count++;
			$distance_remain = $max_distance - ($bicycle_rental_coords[$i] - $bicycle_rental_coords[$i-1]);
		}
	}

	echo $bicycle_count;
?>

<?php
    $str = file_get_contents("стандартный ввод");

    $strs = explode("\n", $str);

    $punkts_count = explode(" ", $strs[0])[0];
    $max_km = explode(" ", $strs[0])[1];
    $punkts = explode(" ", $strs[1]);

    $bikes_count = 1;
    $km_count = $max_km;

    for($i=0;$i<$punkts_count-1;$i++) {
        $n1 = $i+1;
        $offset = $punkts[$n1]-$punkts[$i];

        if($offset > $max_km) {
			file_put_contents("стандартный вывод", "-1");
			die();
		}
        elseif($offset > $km_count) {
            $bikes_count++;
            $km_count = $max_km;
        }

        $km_count = $km_count-$offset;
    }

    file_put_contents("стандартный вывод", $bikes_count);
?>

<?php
    $str = file_get_contents("стандартный ввод");

    $strs = explode("\n", $str);

    $punkts_count = explode(" ", $strs[0])[0];
    $max_km = explode(" ", $strs[0])[1];
    $punkts = explode(" ", $strs[1]);

    $bikes_count = 0;
    $km_count = $max_km;

    for($i=0;$i<$punkts_count-1;$i++) {
        $n1 = $i+1;
        $offset = $punkts[$n1]-$punkts[$i];

        if($offset > $max_km) {
			file_put_contents("стандартный вывод", "-1");
			die();
		}
        elseif($offset > $km_count) {
            $bikes_count++;
            $km_count = $max_km;
        }

        $km_count = $km_count-$offset;
    }

    file_put_contents("стандартный вывод", $bikes_count);
?>

<?php
$arr = explode(" ",fgets(STDIN));
$count_points_n = intval($arr[0]);
$max_rande_k = intval($arr[1]);
$arr = NULL;
$arr_x = explode(" ",fgets(STDIN));

$min_count_points = 1;
for($i = 0; $i < $count_points_n; $i++){
    $point = $i;
    $flag = true;
    $cur_range = $arr_x[$i] + $max_rande_k;
    $is_succses = 0;
    while($flag) {
        $point++;
        if ($cur_range > $arr_x[$point]) {
            $i = $point;
            if($point >= $count_points_n){
                break;
            }
            $is_succses = 1;
        }
        else{
            $min_count_points++;
            break;
        }
    }
    if(!$is_succses){
        $min_count_points = -1;
        break;
    }
}
echo $min_count_points;

?>

<?php
list($count, $range) = explode(" ", fgets(STDIN));
$count = (int) $count;
$range = (int) $range;
$arr = explode(" ", fgets(STDIN));
$velo = 0;

$pos = $arr[0];
for($i = 1; $i < $count; $i++){
    if($arr[$i] > $pos){
     $pos = $arr[$i-1] + $range;
  if($arr[$i] > $pos){
   $velo = -1;
  } else {
   $velo ++;
  }

    }
}
echo $velo."  ";

<?php
// String
$q = '4 4';
$w = '3 6 8 10';
// Array
$q = explode(' ', $q);
$w = explode(' ', $w);
// Next
$t = $w[0];
// Bike
$u = 0;
// Foreach $w array
foreach($w as $key => $e){
	if($t < $e){
		// + "Next"
		$t += $q[1];
		// Search at array ($w) meanings ($t)
		$y = array_search($t, $w);
		// If $y == false
		if($y == false){
			// Check previous value
			if(!isset($w[$key - 1])){
				// Stop foreach
				$a = true;
			} else{
				// Duplicate "Next"
				$o = $t;
				// Bust
				$p = 0;
				// Search array($w)
				while($p < $e and $y == false){
					$o -= 1;
					$p += 1;
					$y = array_search($o, $w);
				}
				// If success search array
				if($o > 0 and isset($w[$y])){
					$t = $o;
					$u++;
				}
			}
		} else{ // If $y == true
			// Bike + 1
			$u++;
		}
	}
}
// Echo result
if($u > 0){
	echo $u;
} else{
	echo '-1';
}

<?php
$one = fgets(STDIN);
$two = fgets(STDIN);
$array_one = explode(' ', $one);
$array_two = explode(' ', $two);
$bike = 0;
$s = $array_two[0];
$q = 0;
foreach($array_two as $key => $pun){
	if($bike * $array_one[1] <= $array_two[0] + array_pop($array_two)){
		$s += $array_one[1];
		$var = array_search($s, $array_two);
		if($var == false){
			while($s > 0 and $var == false){
				$s -= 1;
				$var = array_search($s, $array_two);
			}
			if(isset($array_two[$var]) and $array_two[$var] != $pun){
				$bike++;
			}
		} else{
			$bike++;
		}
	}
}
if($bike <= 0){
	echo '-1';
} else{
	echo $bike;
}

<?php
	function one($num, $arr) {
		sort($arr);
		$less = array_filter($arr, function($d) use ($num){return $d <= $num;});
		$min = end($less);
		return $min;
	}

	$_1 = fgets(STDIN);
	$_2 = fgets(STDIN);
	$a = explode(' ', $_1);
	$b = explode(' ', $_2);
	$c = array_pop($b);
	$x = $b[0] + $a[1];

	while ($x != $c) {
		if (!in_array($x, $b)) {
			$y = one($x, $b);
			if ($y == $b[0]) break;
			$x = $y + $a[1];
			$z++;
		} else {
			$x = $x + $a[1];
			$z++;
		}
	}
	if ($z == 0) {
		echo '-1';
	} else {
		echo $z + 1;
	}
?>

<?php
	function one($num, $arr) {
		sort($arr);
		$less = array_filter($arr, function($d) use ($num){return $d <= $num;});
		$min = end($less);
		return $min;
	}

	$_1 = fgets(STDIN);
	$_2 = fgets(STDIN);
	$a = explode(' ', $_1);
	$b = explode(' ', $_2);
	$c = array_pop($b);
	$x = $b[0] + $a[1];

	while ($x != $c) {
		if (!in_array($x, $b)) {
			$y = one($x, $b);
			if ($y == $b[0]) break;
			if (($y + $a[1]) == $x) {$z++; break 1;}
			$x = $y + $a[1];
			$z++;
		} else {
			$x = $x + $a[1];
			$z++;
		}
	}
	if ($z == 0) {
		echo '-1';
	} else {
		echo $z + 1;
	}
?>


'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the prices of the questions. The third line contains m distinct integers bi (1 ≤ bi ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n.

In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.


You are given $$$n$$$ of integers $$$a_1, a_2, \ldots, a_n$$$. Process $$$q$$$ queries of two types: query of the form "0 $$$x_j$$$": add the value $$$x_j$$$ to all even elements of the array $$$a$$$, query of the form "1 $$$x_j$$$": add the value $$$x_j$$$ to all odd elements of the array $$$a$$$.Note that when processing the query, we look specifically at the odd/even value of $$$a_i$$$, not its index.After processing each query, print the sum of the elements of the array $$$a$$$.Please note that the answer for some test cases won't fit into 32-bit integer type, so you should use at least 64-bit integer type in your programming language (like long long for C++).

The first line of the input contains an integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$q$$$ ($$$1 \leq n$$$, $$$q \leq 10^5$$$) — the length of array $$$a$$$ and the number of queries. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — elements of the array $$$a$$$. The following $$$q$$$ lines contain queries as two integers $$$type_j$$$ and $$$x_j$$$ $$$(0 \leq type_j \leq 1$$$, $$$1 \leq x_j \leq 10^4$$$). It is guaranteed that the sum of values $$$n$$$ over all test cases in a test does not exceed $$$10^5$$$. Similarly, the sum of values $$$q$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print $$$q$$$ numbers: the sum of the elements of the array $$$a$$$ after processing a query.

<?php
//[$n,$m] = array_map('intval', explode(' ', trim(fgets(STDIN))));
[$t] = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$a = array_map('intval', explode(' ', trim(fgets(STDIN))));
//[$s,$t] = explode(' ', trim(fgets(STDIN)));
//[$s] = explode(' ', trim(fgets(STDIN)));
//$s = explode(' ', trim(fgets(STDIN)));
//function decr($v){return --$v;}
//$alpha='abcdefghijklmnopqrstuvwxyz';
//$mod=1000000009;
//$mod=1000000007;
//$mod=998244353;
//$a=[];
//$b=[];
for($i=0;$i<$t;$i++){
    [$n,$q] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $a = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $sum = array_sum($a);
    $gu=0;
    $ki=0;
    for($j=0;$j<$n;$j++){
        if($a[$j] % 2== 0) $gu++;
        else $ki++;
    }
    for($j=0;$j<$q;$j++){
        [$x,$y] = array_map('intval', explode(' ', trim(fgets(STDIN))));
        if($x == 0){
            $sum += $y * $gu;
            if($y % 2 == 1){
                $ki = $n;
                $gu = 0;
            }
        }else{
            $sum += $y * $ki;
            if($y % 2 == 1){
                $gu = $n;
                $ki = 0;
            }
        }
        $ans[] = $sum;
    }
}

echo implode(PHP_EOL,$ans);


Vus the Cossack has two binary strings, that is, strings that consist only of "0" and "1". We call these strings $$$a$$$ and $$$b$$$. It is known that $$$|b| \leq |a|$$$, that is, the length of $$$b$$$ is at most the length of $$$a$$$.The Cossack considers every substring of length $$$|b|$$$ in string $$$a$$$. Let's call this substring $$$c$$$. He matches the corresponding characters in $$$b$$$ and $$$c$$$, after which he counts the number of positions where the two strings are different. We call this function $$$f(b, c)$$$.For example, let $$$b = 00110$$$, and $$$c = 11000$$$. In these strings, the first, second, third and fourth positions are different.Vus the Cossack counts the number of such substrings $$$c$$$ such that $$$f(b, c)$$$ is even.For example, let $$$a = 01100010$$$ and $$$b = 00110$$$. $$$a$$$ has four substrings of the length $$$|b|$$$: $$$01100$$$, $$$11000$$$, $$$10001$$$, $$$00010$$$.  $$$f(00110, 01100) = 2$$$; $$$f(00110, 11000) = 4$$$; $$$f(00110, 10001) = 4$$$; $$$f(00110, 00010) = 1$$$. Since in three substrings, $$$f(b, c)$$$ is even, the answer is $$$3$$$.Vus can not find the answer for big strings. That is why he is asking you to help him.

The first line contains a binary string $$$a$$$ ($$$1 \leq |a| \leq 10^6$$$) — the first string. The second line contains a binary string $$$b$$$ ($$$1 \leq |b| \leq |a|$$$) — the second string.

NoteThe first example is explained in the legend.In the second example, there are five substrings that satisfy us: $$$1010$$$, $$$0101$$$, $$$1111$$$, $$$1111$$$.

<?php
#1186B
$a = trim(fgets(STDIN));
$b = trim(fgets(STDIN));
$aLength = strlen($a);
$bLength = strlen($b);
$aAmount = substr_count(substr($a, 0, $bLength), '1');
$bAmount = substr_count($b, '1');
$limit = $aLength - $bLength + 1;
$result = 0;
$i = 0;
do {
    $result += (int)((($aAmount + $bAmount) % 2) === 0);
    if ($a[$i] === '1') {
        $aAmount--;
    }
    if (isset($a[$i + $bLength]) && $a[$i + $bLength] === '1') {
        $aAmount++;
    }
    $i++;
} while ($i < $limit);
echo $result;


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.


The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).You are given a sequence $$$a$$$ consisting of $$$n$$$ integers. All these integers are distinct, each value from $$$1$$$ to $$$n$$$ appears in the sequence exactly once.You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the rightmost element of the sequence, write it down and remove it from the sequence. Your task is to write down a strictly increasing sequence, and among all such sequences you should take the longest (the length of the sequence is the number of elements in it).For example, for the sequence $$$[2, 1, 5, 4, 3]$$$ the answer is $$$4$$$ (you take $$$2$$$ and the sequence becomes $$$[1, 5, 4, 3]$$$, then you take the rightmost element $$$3$$$ and the sequence becomes $$$[1, 5, 4]$$$, then you take $$$4$$$ and the sequence becomes $$$[1, 5]$$$ and then you take $$$5$$$ and the sequence becomes $$$[1]$$$, the obtained increasing sequence is $$$[2, 3, 4, 5]$$$).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. All these integers are pairwise distinct.

In the first line of the output print $$$k$$$ — the maximum number of elements in a strictly increasing sequence you can obtain. In the second line print a string $$$s$$$ of length $$$k$$$, where the $$$j$$$-th character of this string $$$s_j$$$ should be 'L' if you take the leftmost element during the $$$j$$$-th move and 'R' otherwise. If there are multiple answers, you can print any.

NoteThe first example is described in the problem statement.


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You want to distribute these $$$n$$$ integers into two groups $$$s_1$$$ and $$$s_2$$$ (groups can be empty) so that the following conditions are satisfied:  For each $$$i$$$ $$$(1 \leq i \leq n)$$$, $$$a_i$$$ goes into exactly one group. The value $$$|sum(s_1)| - |sum(s_2)|$$$ is the maximum possible among all such ways to distribute the integers.Here $$$sum(s_1)$$$ denotes the sum of the numbers in the group $$$s_1$$$, and $$$sum(s_2)$$$ denotes the sum of the numbers in the group $$$s_2$$$.Determine the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 2 \cdot 10^4)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1 \leq n \leq 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(-10^9 \leq a_i \leq 10^9)$$$  — elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, output a single integer  — the maximum possible value of $$$|sum(s_1)| - |sum(s_2)|$$$.

<?php

declare(strict_types = 1);

class Code
{
	private function repeat(int $t): void
	{
		for ($i = 0; $i < $t; $i++) {
			$this->go();
		}
	}

	private function readLn(): string
	{
		return fgets(STDIN);
	}

	private function readInt(): int
	{
		return intval(fgets(STDIN));
	}

	private function readStrings(): array
	{
		return explode(' ', fgets(STDIN));
	}

	private function readInts(): array
	{
		return explode(' ', fgets(STDIN));
	}

	private array $OUTPUT_LINES = [];

	private function outputLn(string $s): void
	{
		$this->OUTPUT_LINES[] = $s;
	}

	private function go(): void
	{
		$this->readLn();
		$this->outputLn(strval(abs(array_sum($this->readInts()))));
	}

	public function __construct()
	{
		$this->repeat($this->readInt());
		echo implode(PHP_EOL, $this->OUTPUT_LINES);
	}
}

new Code();

<?php

declare(strict_types = 1);

class Code
{
	private function readLn(): string
	{
		return fgets(STDIN);
	}

	private function readInt(): int
	{
		return intval(fgets(STDIN));
	}

	private function readStrings(): array
	{
		return explode(' ', fgets(STDIN));
	}

	private function readInts(): array
	{
		return explode(' ', fgets(STDIN));
	}

	public array $OUTPUT_LINES = [];

	private function outputLn(string $s): void
	{
		$this->OUTPUT_LINES[] = $s;
	}

	private function go(): void
	{
		$this->readLn();
		$this->outputLn(strval(abs(array_sum($this->readInts()))));
	}

	public function __construct()
	{
		$t = $this->readInt();
		for ($i = 0; $i < $t; $i++) {
			$this->go();
		}
		echo implode(PHP_EOL, $this->OUTPUT_LINES);
	}
}

new Code();

<?php

declare(strict_types = 1);

function go(): string {
	$n = intval(fgets(STDIN));
	$a = explode(' ', trim(fgets(STDIN)));

	foreach ($a as $k => $v) {
		$a[$k] = intval($v);
	}

	$s1 = $s2 = 0;

	foreach ($a as $k => $v) {
		if ($v >= 1) {
			$s1 += $v;
		} else {
			$s2 += $v;
		}
	}

	$res1 = abs($s1) - abs($s2);
	$res2 = abs($s2) - abs($s1);

	return max($res1, $res2) . PHP_EOL;
}

$t = intval(fgets(STDIN));

for ($i = 0; $i < $t; $i++) {
	echo go();
}

<?php
function getSum(){
    $count = trim(fgets(STDIN));
    $arr = explode(" ",trim(fgets(STDIN)));
    $sum1 = 0;
    $sum2 = 0;
    for ($i=0; $i<$count; $i++){
        if($arr[$i]>0){
            $s1[] =$arr[$i];
            $sum1 +=$arr[$i];
        } else {
            $s2[] =$arr[$i];
            $sum2 +=$arr[$i];
        }
    }
    if (abs($sum2)>abs($sum1)){
        $v = abs($sum2)-abs($sum1);
    } else {
        $v = abs($sum1)-abs($sum2);
    }
    echo "$v\n";
}
$count = trim(fgets(STDIN));
for ($j=0; $j<$count; $j++){
    getSum();
}
?>

<?php

declare(strict_types = 1);

function go(): string {
	$n = intval(fgets(STDIN));
	$a = explode(' ', trim(fgets(STDIN)));

	foreach ($a as $k => $v) {
		$a[$k] = intval($v);
	}

	$s1 = $s2 = 0;

	foreach ($a as $k => $v) {
		if ($v >= 1) {
			$s1 += $v;
		} else {
			$s2 += $v;
		}
	}

	$res1 = abs($s1) - abs($s2);
	$res2 = abs($s2) - abs($s1);

	return strval(max($res1, $res2));
}

$t = intval(fgets(STDIN));

for ($i = 0; $i < $t; $i++) {
	echo go();
}


You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
list($c, $d) = explode(" ", trim(fgets(STDIN)));
$e = explode(" ", trim(fgets(STDIN)));
$f = explode(" ", trim(fgets(STDIN)));
$g = array_reverse($f);
$h = array_slice($e, 0, $c);
$i = array_slice($g, 0, $d);
$j = max($h);
$k = min($i);
if($j < $k)
{
    print "YES";
}
else
{
    print "NO";
}
?>

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
list($aN, $bN) = explode(" ", trim(fgets($file)));
list($aT, $bT) = explode(" ", trim(fgets($file)));
$aArray = explode(" ", trim(fgets($file)));
$bArray = explode(" ", trim(fgets($file)));
$af = $aArray[$aT - 1];
$bf = $bArray[count($bArray) - $bT];
if ($af < $bf) {
    echo "YES";
}else{
    echo "NO";
}

<?php
  list($na, $nb) = explode(' ', trim(fgets(STDIN)));
  list($k, $m) = explode(' ', trim(fgets(STDIN)));
  $a = explode(' ', trim(fgets(STDIN)));
  $b = explode(' ', trim(fgets(STDIN)));
  if ($a[$k - 1] < $b[$nb - $m])
    print('YES');
  else
    print('NO');
?>

    <?php
        $n = explode(" ",trim(fgets(STDIN)));
        $m =  explode(" ",trim(fgets(STDIN)));
        $A =  explode(" ",trim(fgets(STDIN)));
        $B =  explode(" ",trim(fgets(STDIN)));
        sort($A);
        sort($B);
        if($A[$m[0]-1] < $B[$n[1] - $m[1]]){
            echo "YES\n";
        }else{
            echo "NO\n";
        }

<?php
        $n = explode(" ",trim(fgets(STDIN)));
        $m =  explode(" ",trim(fgets(STDIN)));
        $A =  explode(" ",trim(fgets(STDIN)));
        $B =  explode(" ",trim(fgets(STDIN)));
        sort($A);
        sort($B);
        if($A[$m[0]-1] < $B[0]){
            echo "YES";
        }else{
            echo "NO";
        }

<?php
        $n = explode(" ",trim(fgets(STDIN)));
        $m =  explode(" ",trim(fgets(STDIN)));
        $A =  explode(" ",trim(fgets(STDIN)));
        $B =  explode(" ",trim(fgets(STDIN)));
        sort($A);
        sort($B);
        if($A[$m[0]-1] < $B[0]){
            echo "YES\n";
        }else{
            echo "NO\n";
        }


Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well.This time Igor K. got disappointed in one of his hobbies: editing and voicing videos. Moreover, he got disappointed in it so much, that he decided to destroy his secret archive for good. Igor K. use Pindows XR operation system which represents files and folders by small icons. At that, m icons can fit in a horizontal row in any window.Igor K.'s computer contains n folders in the D: disk's root catalog. The folders are numbered from 1 to n in the order from the left to the right and from top to bottom (see the images). At that the folders with secret videos have numbers from a to b inclusive. Igor K. wants to delete them forever, at that making as few frame selections as possible, and then pressing Shift+Delete exactly once. What is the minimum number of times Igor K. will have to select the folder in order to select folders from a to b and only them? Let us note that if some selected folder is selected repeatedly, then it is deselected. Each selection possesses the shape of some rectangle with sides parallel to the screen's borders.

The only line contains four integers n, m, a, b (1 ≤ n, m ≤ 109, 1 ≤ a ≤ b ≤ n). They are the number of folders in Igor K.'s computer, the width of a window and the numbers of the first and the last folders that need to be deleted.

Print a single number: the least possible number of times Igor K. will have to select the folders using frames to select only the folders with numbers from a to b.

NoteThe images below illustrate statement tests.The first test:In this test we can select folders 3 and 4 with out first selection, folders 5, 6, 7, 8 with our second selection and folder 9 with our third, last selection.The second test:In this test we can first select all folders in the first row (2, 3, 4, 5), then — all other ones.


Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1\leq a, b\leq 100$$$), representing a corresponding test case.

For each test case print the single integer on a separate line — the answer to the problem.

NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black.

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

$t = trim(fgets($file));

for ($i = 0; $i < $t; $i++) {
  list($a, $b) = explode(" ", trim(fgets($file)));
  $res = $a * $b;
  echo $res.PHP_EOL;
}

?>

<?php

/*
 * https://codeforces.com/contest/1484
 */

//$file = fopen("./input.txt", "r");
$file = fopen("php://stdin", "r");
$rowsNumber = trim(fgets($file));

for($i=0; $i<$rowsNumber; $i++) {
    list($a, $b) = explode(" ", trim(fgets($file)));

    echo $a*$b . PHP_EOL;
}

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

	while($t--) {
		list($a,$b) = explode(" ", trim(fgets(STDIN)));
		print $a*$b."\n";
	}
?>


Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.

NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined.

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$n = trim(fgets($handle));
$a = trim(fgets($handle));
$a=explode(' ',$a);
$b= trim(fgets($handle));
$b=explode(' ',$b);
$x=[];
for($i=0;$i<$n;$i++)
{
 $x[$b[$i]]=$i;
}
$max=-1;$ans=0;$as=0;
for($i=0;$i<$n;$i++)
{
    $ans=$x[$a[$i]];
    if($ans>$max)
    {
        $max=$ans;
    }
    else
    {
        $as++;
    }
    //$max=max($ans,$max);
}
echo $as;

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$n = trim(fgets($handle));
$a = trim(fgets($handle));
$a=explode(' ',$a);
$b= trim(fgets($handle));
$b=explode(' ',$b);
$x=[];
for($i=0;$i<$n;$i++)
{
 $x[$b[$i]]=$i;
}
$max=0;$ans=0;
for($i=0;$i<$n;$i++)
{
    $ans=$x[$a[$i]]-$i;
    $max=max($ans,$max);
}
echo $max;

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$n = trim(fgets($handle));
$a = trim(fgets($handle));
$a=explode(' ',$a);
$b= trim(fgets($handle));
$b=explode(' ',$b);
$x=[];
for($i=0;$i<$n;$i++)
{
 $x[$b[$i]]=$i;
}
$max=-1;$ans=0;
for($i=0;$i<$n;$i++)
{
    $ans=$x[$a[$i]]-$i;
    $max=max($ans,$max);
}
echo $max;


Vova is playing a computer game. There are in total $$$n$$$ turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is $$$k$$$.During each turn Vova can choose what to do:   If the current charge of his laptop battery is strictly greater than $$$a$$$, Vova can just play, and then the charge of his laptop battery will decrease by $$$a$$$;  if the current charge of his laptop battery is strictly greater than $$$b$$$ ($$$b<a$$$), Vova can play and charge his laptop, and then the charge of his laptop battery will decrease by $$$b$$$;  if the current charge of his laptop battery is less than or equal to $$$a$$$ and $$$b$$$ at the same time then Vova cannot do anything and loses the game. Regardless of Vova's turns the charge of the laptop battery is always decreases.Vova wants to complete the game (Vova can complete the game if after each of $$$n$$$ turns the charge of the laptop battery is strictly greater than $$$0$$$). Vova has to play exactly $$$n$$$ turns. Among all possible ways to complete the game, Vova wants to choose the one where the number of turns when he just plays (first type turn) is the maximum possible. It is possible that Vova cannot complete the game at all.Your task is to find out the maximum possible number of turns Vova can just play (make the first type turn) or report that Vova cannot complete the game.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each query is presented by a single line. The only line of the query contains four integers $$$k, n, a$$$ and $$$b$$$ ($$$1 \le k, n \le 10^9, 1 \le b < a \le 10^9$$$) — the initial charge of Vova's laptop battery, the number of turns in the game and values $$$a$$$ and $$$b$$$, correspondingly.

For each query print one integer: -1 if Vova cannot complete the game or the maximum number of turns Vova can just play (make the first type turn) otherwise.

NoteIn the first example query Vova can just play $$$4$$$ turns and spend $$$12$$$ units of charge and then one turn play and charge and spend $$$2$$$ more units. So the remaining charge of the battery will be $$$1$$$.In the second example query Vova cannot complete the game because even if he will play and charge the battery during each turn then the charge of the laptop battery will be $$$0$$$ after the last turn.


You are given $$$n$$$ strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String $$$a$$$ is a substring of string $$$b$$$ if it is possible to choose several consecutive letters in $$$b$$$ in such a way that they form $$$a$$$. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of strings. The next $$$n$$$ lines contain the given strings. The number of letters in each string is from $$$1$$$ to $$$100$$$, inclusive. Each string consists of lowercase English letters. Some strings might be equal.

If it is impossible to reorder $$$n$$$ given strings in required order, print "NO" (without quotes). Otherwise print "YES" (without quotes) and $$$n$$$ given strings in required order.

NoteIn the second example you cannot reorder the strings because the string "abab" is not a substring of the string "abacaba".

<?php
fscanf(STDIN,"%d",$numOfstr);
$str=array();
for ($i=0; $i <$numOfstr; $i++)
{
	fscanf(STDIN,"%s",$str[$i]);
}
for ($i=0; $i <$numOfstr-1 ; $i++)
 {
       for ($j=0; $j <$numOfstr-1 ; $j++)
        {
        	if(strlen($str[$j])>strlen($str[$j+1]))
        	{
        		$tmp=$str[$j];
        		$str[$j]=$str[$j+1];
        		$str[$j+1]=$tmp;
        	}
        }
 }
 //print_r($str)."\n";
 $count=0;
 for ($i=0; $i <$numOfstr-1 ; $i++)
  {
 	  $cnt=substr_count($str[$i+1],$str[$i]);
 	  if($cnt>=1)
 	  {
 	  	$count++;
 	  }
  }
  //echo "$count\n";

  if($count>=$numOfstr-1)
  {
	   echo "YES\n";
	  for ($i=0; $i <$numOfstr ; $i++)
	   {
	  	   echo "$str[$i]\n";
	   }
  }
  else
  	echo "NO\n";

<?php

$str = array();
$n = (int) readline();

for($i = 0; $i < $n; $i++)
    $str[] = readline();

for($i = 0; $i < $n; $i++) {
    for($j = $i + 1; $j < $n; $j++) {
        if(strlen($str[$j]) < strlen($str[$i])) {
            $temp = $str[$i];
            $str[$i] = $str[$j];
            $str[$j] = $temp;
        }
    }
}

for($i = 0; $i < $n - 1; $i++)
    if(strpos($str[$i+1], $str[$i]) === false)
        break;

if($i != ($n - 1)) echo "NO\n";
else {
    echo "YES\n";
    foreach($str as $val)
        echo $val."\n";
}

<?php
fscanf(STDIN,"%d",$numOfstr);
$str=array();
for ($i=0; $i <$numOfstr; $i++)
{
	fscanf(STDIN,"%s",$str[$i]);
}
for ($i=0; $i <$numOfstr-1 ; $i++)
 {
       for ($j=0; $j <$numOfstr-1 ; $j++)
        {
        	if(strlen($str[$j])>strlen($str[$j+1]))
        	{
        		$tmp=$str[$j];
        		$str[$j]=$str[$j+1];
        		$str[$j+1]=$tmp;
        	}
        }
 }
 print_r($str)."\n";
 $count=0;
 for ($i=0; $i <$numOfstr-1 ; $i++)
  {
 	  $cnt=substr_count($str[$i+1],$str[$i]);
 	  if($cnt>=1)
 	  {
 	  	$count++;
 	  }
  }
  //echo "$count\n";

  if($count>=$numOfstr-1)
  {
	   echo "YES\n";
	  for ($i=0; $i <$numOfstr ; $i++)
	   {
	  	   echo "$str[$i]\n";
	   }
  }
  else
  	echo "NO\n";

<?php
fscanf(STDIN,"%d",$numOfstr);
$str=array();
for ($i=0; $i <$numOfstr; $i++)
{
	fscanf(STDIN,"%s",$str[$i]);
}
for ($i=0; $i <$numOfstr-1 ; $i++)
 {
       for ($j=0; $j <$numOfstr-1 ; $j++)
        {
        	if(strlen($str[$j])>strlen($str[$j+1]))
        	{
        		$tmp=$str[$j];
        		$str[$j]=$str[$j+1];
        		$str[$j+1]=$tmp;
        	}
        }
 }
 $cnt=0;
 for ($i=0; $i <$numOfstr-1 ; $i++)
  {
 	  $cnt+=substr_count($str[$i+1],$str[$i]);
  }
  if($cnt>=$numOfstr-1)
  {
	   echo "YES\n";
	  for ($i=0; $i <$numOfstr ; $i++)
	   {
	  	   echo "$str[$i]\n";
	   }
  }
  else
  	echo "NO\n";


Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \times 3$$$ square.  What is the maximum side length of the square Ujan can get?

The first line of input contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$), the lengths of the planks.

For each of the test cases, output a single integer, the maximum possible side length of the square.

NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \times 4$$$ square.In the third sample, the maximum possible square is $$$1 \times 1$$$ and can be taken simply as any of the planks.

<?php
list($c) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $c; $i++) {
    list($k) = explode(' ', trim(fgets(STDIN)));
    $aArray = explode(' ', trim(fgets(STDIN)));
    $j = 1;
    $iCount = 0;
    arsort($aArray);
    foreach ($aArray as $sK => $sV){
        if($j > $sV) {
            break;
        } else {
            $iCount++;
            $j++;
        }
    }
    echo $iCount."\n";
}

<?php
// STDIN = fopen('input.txt', 'r');
$q = + trim(fgets(STDIN));

for ($i = 0; $i < $q; $i++){
	$n = + trim(fgets(STDIN));
	$arr = explode(' ', trim(fgets(STDIN)));

	echo calc($n, $arr)."\n";

}

function calc($n, $arr){
	sort($arr);
	$arr = array_reverse($arr);
	for ($i = 0; $i < $n; $i++){
		if($i + 1 > $arr[$i]){
			return $i;
		}
	}
	return $n;

}

<?php
$count = intval(fgets(STDIN));
$i = 0;
while($i < $count)
{
    $n = intval(fgets(STDIN));
    $lens = explode(" ", fgets(STDIN));
    $sorted = array();
    foreach($lens as $len)
    {
        // if(!isset($sorted[$len]))
        //     $sorted[$len] = 0;
        // $sorted[$len]++;
        $sorted[] = intval($len);
    }
    sort($sorted);
    $max = 0;
    foreach($sorted as $k => $len)
    {
        if($n - $k <= $len)
        {
            $max = $n - $k;
            break;
        }
    }
    echo $max."\n";
    $i++;
}
?>

<?php

$t=trim(fgets(STDIN));
while($t--)
{
    $n=trim(fgets(STDIN));
    $a=explode(' ',trim(fgets(STDIN)));
    rsort($a);
    $ind=$n;
    for($i=0;$i<$n;$i++)
    if($i+1>$a[$i])
    {
        $ind=$i;
        break;
    }
    echo "$ind\n";

}

?>

<?php

$n = trim(fgets(STDIN));
for($i = 0; $i < $n; $i++){
    $a = trim(fgets(STDIN));
    $t = explode(' ', trim(fgets(STDIN)));
    rsort($t);
    $j = 0;
    foreach($t as $v){
        if($v > $j){
            $j++;
        } else {
            break;
        }
    }
    echo "$j\n";

}

<?php

function check($s,$d)
{
    $c=0;$r=0;
    for ($i=0;$i<$d;$i++)
    {
        if($s[$i]=='A')$c++;
        else $r++;
    }

    if($c>$r)
        return "Anton";
    else if($c<$r)
        return "Danik";
    else
        return "Friendship";
}
function solve()
{
    $server="php://stdin";
    $local="input.txt";
    $handle = fopen($server, "r");
    $s="";$d=0;$t=0;
    $t = trim(fgets($handle));
    for($i=0;$i<$t;$i++)
    {
        $arr=array();
        $d = trim(fgets($handle));

        $result = trim(fgets($handle));
        $arr = explode(' ',$result);
        rsort($arr);
        $count=0;
        for ($h=0;$h<sizeof($arr);$h++)
            if($h<$arr[$h])
                $count++;

        printf("%d\n",$count);

    }

}

solve();
?>

<?php
$k = fgets(STDIN);
for($i = 0; $i < $k; $i++)
{
    $n = fgets(STDIN);
    $lens = explode(" ", fgets(STDIN));
    $sorted = array();
    foreach($lens as $len)
    {
        if(!isset($sorted[$len]))
            $sorted[$len] = 0;
        $sorted[$len]++;
    }
    ksort($sorted);
    $max = 0;
    foreach($sorted as $k => $len)
    {
        if($k == $len)
            $max = $len;
    }
    echo $max."\n";
}
?>

<?php

function check($s,$d)
{
    $c=0;$r=0;
    for ($i=0;$i<$d;$i++)
    {
        if($s[$i]=='A')$c++;
        else $r++;
    }

    if($c>$r)
        return "Anton";
    else if($c<$r)
        return "Danik";
    else
        return "Friendship";
}
function solve()
{
    $server="php://stdin";
    $local="input.txt";
    $handle = fopen($server, "r");
    $s="";$d=0;$t=0;
    $t = trim(fgets($handle));
    for($i=0;$i<$t;$i++)
    {
        $arr=array();
        $d = trim(fgets($handle));

        $result = trim(fgets($handle));
        $arr = explode(' ',$result);
        rsort($arr);
        $count=0;
        for ($h=0;$h<sizeof($arr);$h++)
            if($h<$arr[$h])
                $count++;

        printf("%d",$count);

    }

}

<?php

$t = trim(fgets(STDIN));

$ans = "";

for ($o = 0; $o < $t; $o++)
{
	$n = trim(fgets(STDIN));
	$data = explode(" ", trim(fgets(STDIN)));
	sort($data);
	$ans .= (($n >= 3) ? $data[$n-3] : (($n == 2) ? $data[n - 2] : $data[n - 1]))."\n";
}
echo $ans;

?>


Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 centimeter long rope to hang clothes on. The dryer has got a coordinate system installed: the leftmost end of the dryer has coordinate 0, and the opposite end has coordinate 100. Overall, the university has n students. Dean's office allows i-th student to use the segment (li, ri) of the dryer. However, the dean's office actions are contradictory and now one part of the dryer can belong to multiple students!Alexey don't like when someone touch his clothes. That's why he want make it impossible to someone clothes touch his ones. So Alexey wonders: what is the total length of the parts of the dryer that he may use in a such way that clothes of the others (n - 1) students aren't drying there. Help him! Note that Alexey, as the most respected student, has number 1.

The first line contains a positive integer n (1 ≤ n ≤ 100). The (i + 1)-th line contains integers li and ri (0 ≤ li < ri ≤ 100) — the endpoints of the corresponding segment for the i-th student.

On a single line print a single number k, equal to the sum of lengths of the parts of the dryer which are inside Alexey's segment and are outside all other segments.

NoteNote that it's not important are clothes drying on the touching segments (e.g. (0, 1) and (1, 2)) considered to be touching or not because you need to find the length of segments.In the first test sample Alexey may use the only segment (0, 1). In such case his clothes will not touch clothes on the segments (1, 6) and (2, 8). The length of segment (0, 1) is 1.In the second test sample Alexey may dry his clothes on segments (0, 1) and (5, 7). Overall length of these segments is 3.

<?php

class ArgsHelper
{
	private $useStd;
	private $input;

	public function __construct()
	{
		$this->useStd = stristr($GLOBALS['argv'][0], '.PhpStorm2019.3\config') === false;
	}

	public function calculateResult($input)
	{
		array_shift($input);

		$alexPlace = array_shift($input);

		$alexPlace = explode(' ', trim($alexPlace));
		$alexes = array_fill($alexPlace[0], $alexPlace[1] - $alexPlace[0], 1);
		foreach ($input as $item)
		{
			$item = explode(' ', trim($item));

			if ($item[0] >= $alexPlace[1])
			{
				continue;
			}
			for ($j = $item[0]; $j < $item[1]; $j++)
			{
				if ($j>=$alexPlace[1])
				{
					break;
				}
				unset($alexes[$j]);
			}
		}
		return count($alexes);
	}

	public function readInputLines()
	{
		$this->input = [];
		if ($this->useStd)
		{
			while ($line = fgets(STDIN))
			{
				$this->input[] = $line;
			}
		}
		else
		{
			global $testInput;
			$this->input = explode("\n", trim($testInput));
		}
	}

	public function getInputLines()
	{
		$this->readInputLines();
		return $this->input;
	}

	public function printResult($result)
	{
		if ($this->useStd)
		{
			fwrite(STDOUT, $result);
		}
		else
		{
			var_dump($result);
		}
	}

}

##################################################
$testInput = '3
0 10
1 5
7 15
';

$helper = new ArgsHelper();
$lines = $helper->getInputLines();

$result = '';
#
$result = trim($helper->calculateResult($lines) . "\n");
#

$helper->printResult($result);

<?php

class ArgsHelper
{
	private $useStd;
	private $input;

	public function __construct()
	{
		$this->useStd = stristr($GLOBALS['argv'][0], '.PhpStorm2019.3\config') === false;
	}

	public function calculateResult($input)
	{
		array_shift($input);
		$alexPlace = array_shift($input);
		$alexPlace = explode(' ', $alexPlace);
		$alexes = array_fill($alexPlace[0], $alexPlace[1] - $alexPlace[0], 1);
		foreach ($input as $item)
		{
			$item = explode(' ', $item);
			if ($item[0] >= $alexPlace[1])
			{
				continue;
			}
			for ($j = $item[0]; $j < $item[1]; $j++)
			{
				if ($j>=$alexPlace[1])
				{
					break;
				}
				unset($alexes[$j]);
			}
		}
		return count($alexes);
	}

	public function readInputLines()
	{
		$this->input = [];
		if ($this->useStd)
		{
			while ($line = fgets(STDIN))
			{
				$this->input[] = $line;
			}
		}
		else
		{
			global $testInput;
			$this->input = explode("\n", trim($testInput));
		}
	}

	public function getInputLines()
	{
		$this->readInputLines();
		return $this->input;
	}

	public function printResult($result)
	{
		if ($this->useStd)
		{
			fwrite(STDOUT, $result);
		}
		else
		{
			var_dump($result);
		}
	}

}

##################################################
$testInput = '3
0 10
1 5
7 15
';

$helper = new ArgsHelper();
$lines = $helper->getInputLines();

$result = '';
#
$result = trim($helper->calculateResult($lines) . "\n");
#

$helper->printResult($result);


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

<?php
$st = ['purple'=>'Power', 'green'=>'Time', 'red'=>'Reality', 'blue' => 'Space', 'orange' => 'Soul', 'yellow' => 'Mind'];
$n = intval(trim(fgets(STDIN)));
while($n--){
	$clr = trim(fgets(STDIN));
	unset($st[$clr]);
}
print count($st). "\n";
print implode("\n", $st)."\n";

<?php
    $arr = array("purple" => "Power",
    "green" => "Time",
    "blue" => "Space",
    "orange" => "Soul",
    "red" => "Reality",
    "yellow" => "Mind"
    );

    $cnt = array("purple" => 0,
    "green" => 0,
    "blue" => 0,
    "orange" => 0,
    "red" => 0,
    "yellow" => 0
    );

    $n = trim(fgets(STDIN));
    for($i=0; $i<$n; $i++)
    {
        $s = trim(fgets(STDIN));
        $cnt[$s]++;
    }

    echo 6 - $n . PHP_EOL;

    foreach($cnt as $x => $val)
        if(!$val)
            echo $arr[$x] . PHP_EOL;
?>

<?php
$a = trim(fgets(STDIN));
$b = array();
for($x = 0; $x < $a; $x++)
{
     $c = trim(fgets(STDIN));
     $b[$x] = $c;
}
$d = array("purple", "green", "blue", "orange", "red", "yellow");
$e = array_diff($d, $b);
$f = array("Power", "Time", "Space", "Soul", "Reality", "Mind");
$g = array_keys($e);
print count($e) . "\n";
for($x = 0; $x < count($e); $x++)
{
     print $f[$g[$x]] . "\n";
}
?>

#include <bits/stdc++.h>

using namespace std;

#define in freopen("input.txt", "r", stdin);
#define out freopen("output.txt", "w", stdout);

int execute()
{
    int n, i;

    cin >> n;

    map < string, bool > used;

    string s;

    for(i=0; i<n; i++)
    {
        cin >> s;
        used[s] = true;
    }

    vector < string > a;
    a.push_back("purple");
    a.push_back("green");
    a.push_back("blue");
    a.push_back("orange");
    a.push_back("red");
    a.push_back("yellow");

    map < string, string > assoc;

    assoc[a[0]] = "Power";
    assoc[a[1]] = "Time";
    assoc[a[2]] = "Space";
    assoc[a[3]] = "Soul";
    assoc[a[4]] = "Reality";
    assoc[a[5]] = "Mind";

    cout << 6 - used.size() << endl;

    for(i=0; i<6; i++)
        if(!used[a[i]])
            cout << assoc[a[i]] << endl;

    return 0;
}

char mtest = false;
unsigned short TE = 1;

int main()
{
    //in
    ios_base::sync_with_stdio(false);

    if(mtest)
        cin >> TE;

    while(TE--)
        execute();

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define in freopen("input.txt", "r", stdin);
#define out freopen("output.txt", "w", stdout);

int execute()
{
    int n, i;
    cin >> n;
    map < string, bool > used;
    string s;
    for(i=0; i<n; i++)
    {
        cin >> s;
        used[s] = true;
    }

    string a[] = {"purple", "green", "blue", "orange", "red", "yellow"};

    map < string, string > assoc;

    assoc[a[0]] = "Power";
    assoc[a[1]] = "Time";
    assoc[a[2]] = "Space";
    assoc[a[3]] = "Soul";
    assoc[a[4]] = "Reality";
    assoc[a[5]] = "Mind";

    cout << 6 - used.size() << endl;

    for(i=0; i<6; i++)
        if(!used[a[i]])
            cout << assoc[a[i]] << endl;

    return 0;
}

char mtest = false;
unsigned short TE = 1;

int main()
{
    //in
    ios_base::sync_with_stdio(false);

    if(mtest)
        cin >> TE;

    while(TE--)
        execute();

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define in freopen("input.txt", "r", stdin);
#define out freopen("output.txt", "w", stdout);

int execute()
{
    int n;

    int i;

    cin >> n;

    map < string, bool > used;

    string s;

    for(i=0; i<n; i++)
    {
        cin >> s;
        used[s] = true;
    }

    string a[] = {"purple", "green", "blue", "orange", "red", "yellow"};

    map < string, string > assoc;

    assoc[a[0]] = "Power";
    assoc[a[1]] = "Time";
    assoc[a[2]] = "Space";
    assoc[a[3]] = "Soul";
    assoc[a[4]] = "Reality";
    assoc[a[5]] = "Mind";

    cout << 6 - used.size() << endl;

    for(i=0; i<6; i++)
        if(!used[a[i]])
            cout << assoc[a[i]] << endl;

    return 0;
}

char mtest = false;
unsigned short TE = 1;

int main()
{
    //in
    ios_base::sync_with_stdio(false);

    if(mtest)
        cin >> TE;

    while(TE--)
        execute();

    return 0;
}

#include <bits/stdc++.h>

using namespace std;

#define in freopen("input.txt", "r", stdin);
#define out freopen("output.txt", "w", stdout);

int execute()
{
    int n, i;

    cin >> n;

    map < string, bool > used;

    string s;

    for(i=0; i<n; i++)
    {
        cin >> s;
        used[s] = true;
    }

    vector < string > a;
    a.push_back("purple");
    a.push_back("green");
    a.push_back("blue");
    a.push_back("orange");
    a.push_back("red");
    a.push_back("yellow");

    map < string, string > assoc;

    assoc[a[0]] = "Power";
    assoc[a[1]] = "Time";
    assoc[a[2]] = "Space";
    assoc[a[3]] = "Soul";
    assoc[a[4]] = "Reality";
    assoc[a[5]] = "Mind";

    cout << 6 - n << endl;

    for(i=0; i<6; i++)
        if(!used[a[i]])
            cout << assoc[a[i]] << endl;

    return 0;
}

char mtest = false;
unsigned short TE = 1;

int main()
{
    in
    ios_base::sync_with_stdio(false);

    if(mtest)
        cin >> TE;

    while(TE--)
        execute();

    return 0;
}


In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor.To begin with friends learned the rules: in the race there are n sections of equal length and m participants. The participants numbered from 1 to m. About each participant the following is known: li — the number of the starting section,  ri — the number of the finishing section (li ≤ ri), ti — the time a biathlete needs to complete an section of the path, ci — the profit in roubles. If the i-th sportsman wins on one of the sections, the profit will be given to the man who had placed a bet on that sportsman. The i-th biathlete passes the sections from li to ri inclusive. The competitor runs the whole way in (ri - li + 1)·ti time units. It takes him exactly ti time units to pass each section. In case of the athlete's victory on k sections the man who has betted on him receives k·ci roubles.In each section the winner is determined independently as follows: if there is at least one biathlete running this in this section, then among all of them the winner is the one who has ran this section in minimum time (spent minimum time passing this section). In case of equality of times the athlete with the smaller index number wins. If there are no participants in this section, then the winner in this section in not determined. We have to say that in the summer biathlon all the participants are moving at a constant speed.We should also add that Nikita can bet on each section and on any contestant running in this section.Help the friends find the maximum possible profit.

The first line contains two integers n and m (1 ≤ n, m ≤ 100). Then follow m lines, each containing 4 integers li, ri, ti, ci (1 ≤ li ≤ ri ≤ n, 1 ≤ ti, ci ≤ 1000).

Print a single integer, the maximal profit in roubles that the friends can get. In each of n sections it is not allowed to place bets on more than one sportsman.

NoteIn the first test the optimal bet is: in the 1-2 sections on biathlete 1, in section 3 on biathlete 3, in section 4 on biathlete 4. Total: profit of 5 rubles for 1 section, the profit of 5 rubles for 2 section, profit of 30 rubles for a 3 section, profit of 20 rubles for 4 section. Total profit 60 rubles.In the second test the optimal bet is: on 1 and 5 sections on biathlete 1, in the 2-4 sections on biathlete 2, in the 6-7 sections on athlete 4. There is no winner in the 8 section. Total: profit of 10 rubles for 1 section, the profit of 15 rubles for 2,3,4 section, profit of 10 rubles for a 5 section, profit of 20 rubles for 6, 7 section. Total profit 105 rubles.


Hr0d1y has $$$q$$$ queries on a binary string $$$s$$$ of length $$$n$$$. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \leq l_i \lt r_i \leq n)$$$. For each query, he has to determine whether there exists a good subsequence in $$$s$$$ that is equal to the substring $$$s[l_i\ldots r_i]$$$.   A substring $$$s[i\ldots j]$$$ of a string $$$s$$$ is the string formed by characters $$$s_i s_{i+1} \ldots s_j$$$. String $$$a$$$ is said to be a subsequence of string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length $$$\ge 2$$$. For example, if $$$s$$$ is "1100110", then the subsequences $$$s_1s_2s_4$$$ ("1100110") and $$$s_1s_5s_7$$$ ("1100110") are good, while $$$s_1s_2s_3$$$ ("1100110") is not good. Can you help Hr0d1y answer each query?

The first line of the input contains a single integer $$$t$$$ ($$$1\leq t \leq 100$$$) — the number of test cases. The description of each test case is as follows. The first line contains two integers $$$n$$$ ($$$2 \leq n \leq 100$$$) and $$$q$$$ ($$$1\leq q \leq 100$$$) — the length of the string and the number of queries.  The second line contains the string $$$s$$$. The $$$i$$$-th of the next $$$q$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \leq l_i \lt r_i \leq n$$$).

For each test case, output $$$q$$$ lines. The $$$i$$$-th line of the output of each test case should contain "YES" if there exists a good subsequence equal to the substring $$$s[l_i...r_i]$$$, and "NO" otherwise. You may print each letter in any case (upper or lower).

NoteIn the first test case,   $$$s[2\ldots 4] = $$$ "010". In this case $$$s_1s_3s_5$$$ ("001000") and $$$s_2s_3s_6$$$ ("001000") are good suitable subsequences, while $$$s_2s_3s_4$$$ ("001000") is not good.  $$$s[1\ldots 3] = $$$ "001". No suitable good subsequence exists.  $$$s[3\ldots 5] = $$$ "100". Here $$$s_3s_5s_6$$$ ("001000") is a suitable good subsequence.


Iahub wants to enhance his multitasking abilities. In order to do this, he wants to sort n arrays simultaneously, each array consisting of m integers.Iahub can choose a pair of distinct indices i and j (1 ≤ i, j ≤ m, i ≠ j). Then in each array the values at positions i and j are swapped only if the value at position i is strictly greater than the value at position j.Iahub wants to find an array of pairs of distinct indices that, chosen in order, sort all of the n arrays in ascending or descending order (the particular order is given in input). The size of the array can be at most  (at most  pairs). Help Iahub, find any suitable array.

The first line contains three integers n (1 ≤  n ≤ 1000), m (1 ≤ m ≤  100) and k. Integer k is 0 if the arrays must be sorted in ascending order, and 1 if the arrays must be sorted in descending order. Each line i of the next n lines contains m integers separated by a space, representing the i-th array. For each element x of the array i, 1 ≤ x ≤ 106 holds.

On the first line of the output print an integer p, the size of the array (p can be at most ). Each of the next p lines must contain two distinct integers i and j (1 ≤ i, j ≤ m, i ≠ j), representing the chosen indices. If there are multiple correct answers, you can print any.

NoteConsider the first sample. After the first operation, the arrays become [1, 3, 2, 5, 4] and [1, 2, 3, 4, 5]. After the second operation, the arrays become [1, 2, 3, 5, 4] and [1, 2, 3, 4, 5]. After the third operation they become [1, 2, 3, 4, 5] and [1, 2, 3, 4, 5].

<?php
error_reporting("off");
//384B: Multitasking
list($n, $m, $k) = explode(" ", trim(fgets(STDIN)));
echo $m * ($m - 1) / 2;
echo "\n";
for ($i = 1; $i <= $m; $i++) {
    for ($j = $i + 1; $j <= $m; $j++) {
        echo $i." ".$j."\n";
    }
}
?>


Berland crossword is a puzzle that is solved on a square grid with $$$n$$$ rows and $$$n$$$ columns. Initially all the cells are white.To solve the puzzle one has to color some cells on the border of the grid black in such a way that:   exactly $$$U$$$ cells in the top row are black;  exactly $$$R$$$ cells in the rightmost column are black;  exactly $$$D$$$ cells in the bottom row are black;  exactly $$$L$$$ cells in the leftmost column are black. Note that you can color zero cells black and leave every cell white.Your task is to check if there exists a solution to the given puzzle.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains $$$5$$$ integers $$$n, U, R, D, L$$$ ($$$2 \le n \le 100$$$; $$$0 \le U, R, D, L \le n$$$).

For each testcase print "YES" if the solution exists and "NO" otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteHere are possible solutions to testcases $$$1$$$, $$$2$$$ and $$$4$$$:

<?php

$times = (int)trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $ui[], $ri[], $di[], $li[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
}
for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $u = &$ui[$idx];
    $r = &$ri[$idx];
    $d = &$di[$idx];
    $l = &$li[$idx];
    for ($i = 0; $i < 16; ++$i) {
        $s = sprintf('%04d', decbin($i));
        $sm = 0;
        $sm += iscnt($s[0] + $s[1], $u);
        $sm += iscnt($s[1] + $s[2], $r);
        $sm += iscnt($s[2] + $s[3], $d);
        $sm += iscnt($s[3] + $s[0], $l);
        if ($sm == 4) {
            echo 'YES' , PHP_EOL;
            continue 2;
        }
    }
    echo 'NO' , PHP_EOL;
}

function iscnt($a, $b)
{
    if ($a == 0) {
        return $b <= 3;
    } elseif ($a == 1) {
        return $b >= 1 && $b <= 4;
    } else {
        return $b >= 2;
    }
}


Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items.

In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week).

Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now.

NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25.


Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.

The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.  Each of the next n lines contains xi (0 ≤ xi ≤ m) — the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≤ yij ≤ m) — the numbers of these bulbs.

If it's possible to turn on all m bulbs print "YES", otherwise print "NO".

NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = range(1, $b);
$d = array();
for($x = 1; $x <= $a; $x++)
{
    $e = explode(" ", trim(fgets(STDIN)));
    $f = array_slice($e, 1);
    $d = array_merge($d, $f);
}
$g = array_unique($d);
sort($g);
$h = array_diff($c, $g);
if(count($h) == 0)
{
    print "YES";
}
else
{
    print "NO";
}
?>

<?php
$n_m = trim(fgets(STDIN));
$nm_arr = explode(" ", $n_m);
$n = $nm_arr[0];
$m = $nm_arr[1];
for ($i = 1; $i <= $n; $i++) {
    $n_l = trim(fgets(STDIN));
    $nl_arr = explode(" ", $n_l);
    for ($j = 1; $j <= $nl_arr[0]; $j++) {
        $m_array[] = $nl_arr[$j];
    }
}
for ($k = 1; $k <= $m; $k++){
    if (in_array($k, $m_array)) {
        $f = true;
    } else {
        $f = false;
        break;
    }
}
if ($f) {
    echo "YES";
} else {
    echo "NO";
}
?>

<?php
/**
 * Author: 七柳先森
 * Date: 2016/1/23  9:08
 */
while(fscanf(STDIN,"%d%d",$n,$m)){
    $bulbStatus = array_fill(0,$m,0);
   // var_dump($bulbStatus);
    for($i = 0 ; $i < $n ; $i++){
        $line = stream_get_line(STDIN,65535,"\n");
        $num = explode(" ",$line);
        for($j = 1 ; $j < count($num); $j++){
            $bulbStatus[ $num[$j] -1 ] = 1;
        }
    }
    if(array_sum($bulbStatus) == $m){
        fprintf(STDOUT,"YES");
    }else{
        fprintf(STDOUT,"NO");
    }
    exit();
}

<?php
$input = file_get_contents('php://stdin');
$input = explode("\n", $input);
$firstString = $input[0];
$firstString = explode(" ", $firstString );
$n = $firstString[0];
$m = $firstString[1];

unset($input[0]);
$lamps = array();
for($i=1; $i<=$m; $i++) {
    $lamps[$i] = $i;
}

foreach($input as $row) {
   $rLamps = explode(' ', $row);
   unset($rLamps[0]);
   foreach($rLamps as $lamp) {
    $lamp = trim($lamp);
       unset($lamps[$lamp]);
   }
   if (empty($lamps)) {
       echo 'YES';
       die();
   }
}
echo 'NO';
?>

<?
list($n, $m) = explode(' ',trim(fgets(STDIN)));
for($i = 0; $i < $n;  ++$i){
 $arr =explode(' ',trim(fgets(STDIN)));
 for($j = 1; $j <= $arr[0];  ++$j){
  $bulbs[$arr[$j]]++;
 }
}
$flag = true;

for($j = 1; $j <= $m;  ++$j){
  if($bulbs[$j] < 1)
  {
   $flag = false;
   break;
  }
}
echo ($flag)?"YES":"NO";

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = range(1, 4);
$d = array();
for($x = 1; $x <= $a; $x++)
{
    $e = explode(" ", trim(fgets(STDIN)));
    $f = array_slice($e, 1);
    $d = array_merge($d, $f);
}
$g = array_unique($d);
sort($g);
$h = array_diff($c, $g);
if(count($h) == 0)
{
    print "YES";
}
else
{
    print "NO";
}
?>

<?php
$n_m = trim(fgets(STDIN));
$nm_arr = explode(" ", $n_m);
$n = $nm_arr[0];
$m = $nm_arr[1];
for ($i = 1; $i <= $n; $i++) {
    $n_l = trim(fgets(STDIN));
    $nl_arr = explode(" ", $n_l);
    for ($j = 1; $j <= $nl_arr[0]; $j++) {
        $m_array[] = $nl_arr[$j];
    }
}
for ($k = 1; $k <= $m; $k++){
    if (in_array($k, $m_array)) {
        $f = true;
    } else {
        $f = false;
        break;
    }
}
if (f) {
    echo "YES";
} else {
    echo "NO";
}
?>

<?php
$input = file_get_contents('php://stdin');
$input = explode("\n", $input);
$firstString = $input[0];
$firstString = explode(" ", $firstString );
$n = $firstString[0];
$m = $firstString[1];

unset($input[0]);
$lamps = array();
for($i=1; $i<$m; $i++) {
    $lamps[$i] = $i;
}

foreach($input as $row) {
   $rLamps = explode(' ', $row);
   unset($rLamps[0]);
   foreach($rLamps as $lamp) {
       unset($lamps[$lamp]);
   }
   if (empty($lamps)) {
       echo 'YES';
       die();
   }
}
echo 'NO';
?>

<?php
$input = file_get_contents("php://stdin");
$input = explode("\n", $input);
$firstString = $input[0];
$firstString = explode(" ", $firstString );
$n = $firstString[0];
$m = $firstString[1];

unset($input[0]);
$lamps = array();
for($i=1; $i<$m; $i++) {
    $lamps[$i] = $i;
}

foreach($input as $row) {
   $rLamps = explode(' ', $row);
   unset($rLamps[0]);
   foreach($rLamps as $lamp) {
       unset($lamps[$lamp]);
   }
   if (empty($lamps)) {
       echo 'YES';
       die();
   }
}
echo 'NO';
?>

<?php
$input = file_get_contents('php://stdin');
$input = explode("\n", $input);
$firstString = $input[0];
$firstString = explode(" ", $firstString );
$n = $firstString[0];
$m = $firstString[1];

unset($input[0]);
$lamps = array();
for($i=1; $i<=$m; $i++) {
    $lamps[$i] = $i;
}

foreach($input as $row) {
   $rLamps = explode(' ', $row);
   unset($rLamps[0]);
   foreach($rLamps as $lamp) {
       unset($lamps[$lamp]);
   }
   if (empty($lamps)) {
       echo 'YES';
       die();
   }
}
echo 'NO';
?>


You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

For each test case, output on a separate line:    "YES" if $$$n$$$ has an odd divisor, greater than one;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

$t = trim(fgets($file));
for ($i = 0; $i < $t; $i++) {
  $n = trim(fgets($file));

  $h = pow(2, floor(log($n, 2)));

  if ($n == $h) {
    echo "NO".PHP_EOL;

    continue;
  }

  if ($n[ strlen($n) - 1 ] % 2 != 0) {
    echo "YES".PHP_EOL;

    continue;
  }

  echo "YES".PHP_EOL;
}
?>

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

$t = trim(fgets($file));
for ($i = 0; $i < $t; $i++) {
  $n = trim(fgets($file));

  $f = log($n, 2);
  $k = (string) $n;
  $h = pow(2, floor($f));

  if ($f == 1) { echo 'NO'.PHP_EOL; }
  else {
    if ($k[strlen($k) - 1] % 2 != 0) { echo 'YES'.PHP_EOL; }
    else {
      if ($h == $n) { echo 'NO'.PHP_EOL; }
      else { echo 'YES'.PHP_EOL; }
    }
  }
}
?>

<?php
function solve() {
    $n = Read::string();
    while (Bigint::mod($n, '2') == 0) {
        $n = Bigint::div($n, '2');
    }
    return $n == 1 ? "NO" : "YES";
}

#$t = 1;
$t = Read::int();
while ($t--) {
    echo solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2) {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '') {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
$fileName = 'php://stdin';
$file = fopen($fileName, "r");

$t = trim(fgets($file));
for ($i = 0; $i < $t; $i++) {
  $n = trim(fgets($file));

  $f = log($n, 2);
  $f1 = ceil($f);

  if ($f == 1) { echo 'NO'.PHP_EOL; }
  else {
    if ($f1 == $f) { echo 'NO'.PHP_EOL; }
    else { echo 'YES'.PHP_EOL; }
  }
}
?>

<?php
function solve() {
    $n = Read::string();
    $power = log($n, '2');
    return $power == floor($power) ? "NO" : "YES";
}

#$t = 1;
$t = Read::int();
while ($t--) {
    echo solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2) {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '') {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>

<?php
function solve() {
    $n = Read::int();
    while (Bigint::mod($n, 2) == 0) {
        $n = Bigint::div($n, 2);
    }

    return $n == 1 ? "NO" : "YES";
}

#$t = 1;
$t = Read::int();
while ($t--) {
    echo solve();
    echo "\n";
}

class Read
{
    public static function string()
    {
        return trim(fgets(STDIN));
    }

    public static function int()
    {
        return intval(fgets(STDIN));
    }

    public static function array_int($sep = ' ')
    {
        $s = trim(fgets(STDIN));
        return preg_split("/[\s,]+/", $s);
    }

}

class Bigint
{
    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 / $bigint2
     */
    public static function div($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                return bcmod($bigint1, $bigint2) == 0 ? bcdiv($bigint1, $bigint2) : bcadd(bcdiv($bigint1, $bigint2), 1);
            case 'floor':
                return bcdiv($bigint1, $bigint2);
            case 'round':
                $sResult = bcdiv($bigint1, $bigint2);
                return bcsub(bcdiv($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcdiv($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 + $bigint2
     */
    public static function add($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcadd($bigint1, $bigint2);
            case 'round':
                $sResult = bcadd($bigint1, $bigint2);
                return bcsub(bcadd($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcadd($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 - $bigint2
     */
    public static function sub($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcsub($bigint1, $bigint2);
            case 'round':
                $sResult = bcsub($bigint1, $bigint2);
                return bcsub(bcsub($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsub($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @param string $scale (ceil or floor or round)
     * @return string $bigint1 * $bigint2
     */
    public static function mul($bigint1, $bigint2, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcmul($bigint1, $bigint2);
            case 'round':
                $sResult = bcmul($bigint1, $bigint2);
                return bcsub(bcmul($bigint1, $bigint2, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcmul ($bigint1, $bigint2);
        }
    }

    /**
     * @param string $bigint1
     * @param string $bigint2
     * @return string $bigint1 % $bigint2
     */
    public static function mod($bigint1, $bigint2) {
        return bcmod($bigint1, $bigint2);
    }

    /**
     * @param string $bigint
     * @param string $scale (ceil or floor or round)
     * @return string sqrt($bigint)
     */
    public static function sqrt($bigint, $scale = '') {
        switch ($scale) {
            case 'ceil':
                return bcadd(bcsqrt ($bigint), 1);
            case 'floor':
                return bcsqrt($bigint);
            case 'round':
                $sResult = bcsqrt($bigint);
                return bcsub(bcsqrt($bigint, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcsqrt($bigint);
        }
    }

    /**
     * @param string $bigint
     * @param string $exponent
     * @param string $scale (ceil or floor or round)
     * @return string pow($bigint, $exponent)
     */
    public static function pow($bigint, $exponent, $scale = '') {
        switch ($scale) {
            case 'ceil':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) == 0 ? $sResult : bcadd($sResult, 1);
            case 'floor':
                return bcpow($bigint, $exponent);
            case 'round':
                $sResult = bcpow($bigint, $exponent);
                return bcsub(bcpow($bigint, $exponent, 2),  $sResult, 2) >= 0.5 ? bcadd($sResult, 1) : $sResult;
            default:
                return bcpow ($bigint, $exponent);
        }
    }
}

class Algorithms
{

    /** Факторизация - Разложение числа на простые множители
     * @param int $n
     * @return array
     */
    public static function factorization($n)
    {
        $a = [];
        for ($i = 2; $i * $i <= $n; ++$i) {
            $cnt = 0;
            while (bcmod($n, $i) == 0) {
                ++$cnt;
                $n = bcdiv($n, $i);
            }
            if ($cnt > 0) {
                $a[$i] = $cnt;
            }
        }
        if ($n > 1) {
            $a[$n] = 1;
        }

        return $a;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наибольший общий делитель (НОД)
     */
    public static function gcd($a, $b)
    {
        if ($b == 0) {
            return $a;
        } else {
            $a = $a % $b;
            return self::gcd($b, $a);
        }
    }

    /**
     * @param int $a
     * @param int $b
     * @return int Наименьшее общее кратное (НОК)
     */
    public static function lcm($a, $b)
    {
        return abs($a * $b) / self::gcd($a, $b);
    }

    /**Последовательность Фибоначчи =  0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987
     * return Фибоначчи{n}
     * @param int $n
     * @return int
     */
    public static function fibonacci($n)
    {
        $a = [0, 1];

        for ($i = 2; $i <= $n; $i++) {
            $a[$i] = $a[$i-1] + $a[$i-2];
        }

        return $a[$n];
    }

}

?>