Tired of boring office work, Denis decided to open a fast food restaurant.On the first day he made $$$a$$$ portions of dumplings, $$$b$$$ portions of cranberry juice and $$$c$$$ pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases to solve. Each of the remaining $$$t$$$ lines contains integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$0 \leq a, b, c \leq 10$$$) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.

For each test case print a single integer — the maximum number of visitors Denis can feed.

NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.


Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri, and its elements are a[li], a[li + 1], ..., a[ri].Alyona is going to find mex for each of the chosen subarrays. Among these m mexes the girl is going to find the smallest. She wants this minimum mex to be as large as possible. You are to find an array a of n elements so that the minimum mex among those chosen by Alyona subarrays is as large as possible.The mex of a set S is a minimum possible non-negative integer that is not in S.

The first line contains two integers n and m (1 ≤ n, m ≤ 105). The next m lines contain information about the subarrays chosen by Alyona. The i-th of these lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), that describe the subarray a[li], a[li + 1], ..., a[ri].

In the first line print single integer — the maximum possible minimum mex. In the second line print n integers — the array a. All the elements in a should be between 0 and 109. It is guaranteed that there is an optimal answer in which all the elements in a are between 0 and 109. If there are multiple solutions, print any of them.

NoteThe first example: the mex of the subarray (1, 3) is equal to 3, the mex of the subarray (2, 5) is equal to 3, the mex of the subarray (4, 5) is equal to 2 as well, thus the minumal mex among the subarrays chosen by Alyona is equal to 2.


You've got two numbers. As long as they are both larger than zero, they go through the same operation: subtract the lesser number from the larger one. If they equal substract one number from the another. For example, one operation transforms pair (4,17) to pair (4,13), it transforms (5,5) to (0,5).You've got some number of pairs (ai, bi). How many operations will be performed for each of them?

The first line contains the number of pairs n (1  ≤  n  ≤  1000). Then follow n lines, each line contains a pair of positive integers ai, bi (1  ≤  ai,  bi  ≤  109).

Print the sought number of operations for each pair on a single line.

<?php
$f = file('php://stdin');
$n = $f[0] + 0;
$f_out = fopen('php://stdout', 'w+');
for ($i = 1; $i <= $n; $i++) {
	$data = $f[$i];
	$a = $data + 0;
	$b = substr($data, strpos($data, ' ') + 1) + 0;
	$count = 0;
	while ($a && $b) {
		if ($a > $b) {
			$count2 = floor($a / $b);
			$a -= $b * $count2;
			$count += $count2;
		} else {
			$count2 = floor($b / $a);
			$b -= $a * $count2;
			$count += $count2;
		}
	};
	fwrite($f_out, $count . "\n");
}
fclose($f_out);

<?php
$f = file('input.txt');
$n = $f[0] + 0;
$f_out = fopen('output.txt', 'w+');
for ($i = 1; $i <= $n; $i++) {
	$data = $f[$i];
	$a = $data + 0;
	$b = substr($data, strpos($data, ' ') + 1) + 0;
	$count = 0;
	while ($a && $b) {
		if ($a > $b) {
			$count2 = floor($a / $b);
			$a -= $b * $count2;
			$count += $count2;
		} else {
			$count2 = floor($b / $a);
			$b -= $a * $count2;
			$count += $count2;
		}
	};
	fwrite($f_out, $count . "\n");
}
fclose($f_out);


You are given an array consisting of $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$. Initially $$$a_x = 1$$$, all other elements are equal to $$$0$$$.You have to perform $$$m$$$ operations. During the $$$i$$$-th operation, you choose two indices $$$c$$$ and $$$d$$$ such that $$$l_i \le c, d \le r_i$$$, and swap $$$a_c$$$ and $$$a_d$$$.Calculate the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the description of $$$t$$$ testcases follow. The first line of each test case contains three integers $$$n$$$, $$$x$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le m \le 100$$$; $$$1 \le x \le n$$$). Each of next $$$m$$$ lines contains the descriptions of the operations; the $$$i$$$-th line contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$).

For each test case print one integer — the number of indices $$$k$$$ such that it is possible to choose the operations so that $$$a_k = 1$$$ in the end.

NoteIn the first test case, it is possible to achieve $$$a_k = 1$$$ for every $$$k$$$. To do so, you may use the following operations:  swap $$$a_k$$$ and $$$a_4$$$;  swap $$$a_2$$$ and $$$a_2$$$;  swap $$$a_5$$$ and $$$a_5$$$. In the second test case, only $$$k = 1$$$ and $$$k = 2$$$ are possible answers. To achieve $$$a_1 = 1$$$, you have to swap $$$a_1$$$ and $$$a_1$$$ during the second operation. To achieve $$$a_2 = 1$$$, you have to swap $$$a_1$$$ and $$$a_2$$$ during the second operation.

<?php
    define("MAXN", 1024) ;
    define("GAP_VAL", 1e-7) ;

    function gap($n)
    {
        return $n < GAP_VAL ;
    }

    function merge($l, $r, $l2, $r2)
    {
        if($l2 > $r || $l > $r2) return array($l, $r) ;

        return array(min($l, $l2), max($r, $r2)) ;
    }

    $t = intval(trim(fgets(STDIN))) ;
    while($t --)
    {
        $in_str = explode(" ", trim(fgets(STDIN))) ;

        $x = intval($in_str[1]) ;
        $m = intval($in_str[2]) ;

        $l = $x ;
        $r = $x ;

        for($i = 0; $i < $m; $i ++)
        {
            $in_str = explode(" ", trim(fgets(STDIN))) ;

            list($l, $r) = merge($l, $r, intval($in_str[0]), intval($in_str[1])) ;
        }
        echo $r - $l + 1 . "\n" ;
    }
?>


Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and the other contains 1, then we are allowed to remove these two digits from the string, obtaining a string of length n - 2 as a result.Now Andreid thinks about what is the minimum length of the string that can remain after applying the described operation several times (possibly, zero)? Help him to calculate this number.

First line of the input contains a single integer n (1 ≤ n ≤ 2·105), the length of the string that Andreid has. The second line contains the string of length n consisting only from zeros and ones.

Output the minimum length of the string that may remain after applying the described operations several times.

NoteIn the first sample test it is possible to change the string like the following: .In the second sample test it is possible to change the string like the following: .In the third sample test it is possible to change the string like the following: .

<?php
$stdin = fopen("php://stdin", 'r');
fscanf($stdin, "%d\n", $n);
$s = fgets($stdin);
fclose($stdin);

$stack = [];
for ($i = 0; $i < $n; ++$i)
{
    $m = count($stack);
    $cur = $s[$i] + 0;
    if ($m == 0 || ($stack[$m - 1] xor $cur) == 0)
    {
        $stack[] = $cur;
    }
    else
    {
        array_pop($stack);
    }
}
echo count($stack);
?>

<?php

$len = trim(fgets(STDIN));
$str = trim(fgets(STDIN));

// $len = 200000;
// $str = '';

// for ($i = 0; $i < 100000; $i++)
// {
//     $str = $str . 0;
// }

// for ($i = 0; $i < 100000; $i++)
// {
//     $str = $str . 1;
// }

$arr = str_split($str);
$numOne = 0;
$numZero = 0;

foreach ($arr as $key => $value)
{
    if ($value == 1)
    {
        $numOne++;
    }
    else
    {
        $numZero++;
    }
}

echo abs($numZero - $numOne);

<?php
// $n=fgets(STDIN);
// settype($n,'int');
// $array=explode(' ',fgets(STDIN));
// $max=max($array);
// $s=0;
// $min=min($array);
// $smin=0;
// $smax=1000;
// settype($array[0],'int');
// settype($array[$n-1],'int');
// settype($max,'int');
// settype($min,'int');
// for ($i=0; $i <count($array) ; $i++) {
//       if($array[$i] == $min){
//             $smin=$i;
//       }
// }
// if ($array[0] == max($array) && $array[count($array)-1] ==$min) {
//       echo '0';
//       exit;
// }
// for ($i=$smin; $i <count($array) ; $i++) {
//       if($i !=count($array)-1 and $array[$i] < @$array[$i+1]){
//             $x=$array[$i];
//             $array[$i]=$array[$i+1];
//             $array[$i+1]=$x;
//             $s++;
//       }
// }
// for ($i=0; $i <count($array)-1 ; $i++) {
//       settype($array[$i],'int');
//       if(max($array) == $array[$i]){
//           $smax=$i;
//           break;
//       }
// }

// for ($i=$smax; $i >= 0 ; $i--) {
// if($i !=0){
//       $x=$array[$i];
//       $array[$i]=$array[$i-1];
//       $array[$i-1]=$x;
//       $s++;
// }
// }
// echo $s;

$n=fgets(STDIN);
$one=0;
$zero=0;
$input=str_split(fgets(STDIN),1);
foreach ($input as $key => $value) {
      if ($value == 1) {
            $one++;
      }else if($value == 0){
         $zero++;
      }
}
$zero-=2;
echo max($zero,$one)-min($zero,$one);
# thanks danial !

<?php
    $length = trim(fgets(STDIN));
    $val = trim(fgets(STDIN));

    $arr = array();

    for($i=0; $i<$length; $i++)
        $arr[$val[$i]]++;

    echo $length - min( $arr[0], $arr[1] ) * 2 . PHP_EOL;
?>

<?php

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

$len = strlen($str);

$cnt = 0;

for($i = 0; $i < $len; $i++) {
    if($str[$i] == '0') {
        $cnt++;
    } else {
        $cnt--;
    }
}

echo $cnt < 0 ? -1*$cnt : $cnt;

?>

<?php
    $length = trim(fgets(STDIN));
    $val = trim(fgets(STDIN));
    $res = 0;
    $initLength = $length;

    $val = str_replace('01', '', $val, $cnt);
    $res += $cnt;
    $val = str_replace("10", '', $val, $cnt);
    $res += $cnt;
    $val = str_replace("01", '', $val, $cnt);
    $res += $cnt;
    $val = str_replace("10", '', $val, $cnt);
    $res += $cnt;

    echo $initLength - $res * 2 . PHP_EOL;
?>

<?php
    $length = trim(fgets(STDIN));
    $val = trim(fgets(STDIN));
    $res = 0;
    $cnt = 1;
    $initLength = $length;

    $flag = true;

    while($flag)
    {
        $val = str_replace('01', '', $val, $cnt);
            $res += $cnt;

        if($cnt)
            $flag = true;
        else $flag = false;

        $val = str_replace("10", '', $val, $cnt);
            $res += $cnt;

        if($cnt)
            $flag = true;
        else $flag = false;
    }

    echo $initLength - $res * 2 . PHP_EOL;
?>


Caisa solved the problem with the sugar and now he is on the way back to home. Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as k) to the next one (its number will be k + 1). When the player have made such a move, its energy increases by hk - hk + 1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time. Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers h1, h2, ..., hn (1  ≤  hi  ≤  105) representing the heights of the pylons.

Print a single number representing the minimum number of dollars paid by Caisa.

NoteIn the first sample he can pay 4 dollars and increase the height of pylon with number 0 by 4 units. Then he can safely pass to the last pylon.

<?php
// 463B     Caisa и колонны
$in = fopen("php://stdin", 'r');

$input_line = fgets($in);
$n = (int) $input_line;

$input_line = fgets($in);
$arrH = preg_split('/ /', substr($input_line, 0, strlen($input_line)-2), -1, PREG_SPLIT_NO_EMPTY);

$energy = 0;
$price = $arrH[0];
$height = $arrH[0];

for ($i=0; $i < $n-1; $i++) {
    $energy += $height - $arrH[$i];
    $height = $arrH[$i];
    if (($energy + ($height - $arrH[$i+1])) < 0) {
        $price += - ($energy + ($height - $arrH[$i+1]));
        $energy = - ($height - $arrH[$i+1]);
    }
}

echo $price;

?>


We guessed some integer number $$$x$$$. You are given a list of almost all its divisors. Almost all means that there are all divisors except $$$1$$$ and $$$x$$$ in the list.Your task is to find the minimum possible integer $$$x$$$ that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 25$$$) — the number of queries. Then $$$t$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 300$$$) — the number of divisors in the list. The second line of the query contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$2 \le d_i \le 10^6$$$), where $$$d_i$$$ is the $$$i$$$-th divisor of the guessed number. It is guaranteed that all values $$$d_i$$$ are distinct.

For each query print the answer to it. If the input data in the query is contradictory and it is impossible to find such number $$$x$$$ that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible $$$x$$$.

<?php
# 1165D

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = getPrimeNumbersViaErastofen(1000);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    sort($delimiters);
    $minDelimiter = $delimiters[0];
    $maxDelimiter = $delimiters[$n - 1];

    $digit = (float)$minDelimiter * (float)$maxDelimiter;
    $halfOfDigit = $digit / 2;

    $baseDelimiters = [$minDelimiter => $minDelimiter];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $halfOfDigit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    if (count($baseDelimiters) > $n) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = $a * $b;
                $strResult = sprintf('%.0f', $result);
                if ($result < $digit && !isset ($baseDelimiters[$strResult]) && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    foreach ($baseDelimiters as $delimiter) {
        $result = sprintf('%.0f', $digit / $delimiter);
        if (!isset($baseDelimiters[$result]) && bcmod($digit, $delimiter) === '0') {
            $baseDelimiters[$result] = $result;
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters == $delimiters ? $digit : '-1') . PHP_EOL;
}

<?php
# 1165D

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = getPrimeNumbersViaErastofen(1000);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    sort($delimiters);
    $minDelimiter = $delimiters[0];
    $maxDelimiter = $delimiters[$n - 1];

    $digit = (float)$minDelimiter * (float)$maxDelimiter;
    $halfOfDigit = $digit / 2;

    $baseDelimiters = [$minDelimiter => $minDelimiter];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $halfOfDigit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    if (count($baseDelimiters) > $n) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = $a * $b;
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $result = sprintf('%.0f', $result);
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    foreach ($baseDelimiters as $delimiter) {
        if (bcmod($digit, $delimiter) === '0') {
            $result = sprintf('%.0f', $digit / $delimiter);
            $baseDelimiters[$result] = $result;
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters == $delimiters ? $digit : '-1') . PHP_EOL;
}

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    $digit = bcmul($delimiters[0], $maxDelimiter);
    $halfOfDigit = bcdiv($digit, '2');

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(10000);
    }
    $baseDelimiters = [$delimiters[0] => $delimiters[0]];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $halfOfDigit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    if (count($baseDelimiters) > $n) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    foreach ($baseDelimiters as $delimiter) {
        if (bcmod($digit, $delimiter) === '0') {
            $result = bcdiv($digit, $delimiter);
            $baseDelimiters[$result] = $result;
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters == $delimiters ? $digit : '-1') . PHP_EOL;
}

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
//$stdin = fopen('/home/vilnitskiy/.PhpStorm2019.1/config/scratches/data.txt', 'rb');
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    $digit = bcmul($delimiters[0], $maxDelimiter);

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(100000);
    }
    $baseDelimiters = [$delimiters[0] => $delimiters[0]];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $digit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    if (count($baseDelimiters) > $n) {
        echo '-1' . PHP_EOL;
        continue;
    }

    foreach ($baseDelimiters as $delimiter) {
        $i = 2;
        $result = $delimiter;
        $valid = true;
        $result = bcpow($delimiter, (string)$i);
        $valid = $result < $digit;
        while ($valid) {
            $result = bcpow($delimiter, (string)$i);
            $valid = $result < $digit;
            if ($valid && bcmod($digit, $result) === '0') {
                $baseDelimiters[$result] = $result;
            }
            $i++;
        }
    }
    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    foreach ($baseDelimiters as $delimiter) {
        if (bcmod($digit, $delimiter) === '0') {
            $result = bcdiv($digit, $delimiter);
            $baseDelimiters[$result] = $result;
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters == $delimiters ? $digit : '-1') . PHP_EOL;
}

//echo microtime(true) - $start;

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
//$stdin = fopen('/home/vilnitskiy/.PhpStorm2019.1/config/scratches/data.txt', 'rb');
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    if ($n <= 2) {
        echo bcmul($delimiters[0], $maxDelimiter) . PHP_EOL;
        continue;
    }

    for ($i = 0; $i < $n; $i++) {
        if (bcmod($maxDelimiter, $delimiters[$i]) !== '0') {
            $wrongDigit = false;
            break;
        }
    }
    if ($wrongDigit === true) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $digit = bcmul($delimiters[0], $maxDelimiter);

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(100000);
    }
    $baseDelimiters = [];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $digit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    foreach ($baseDelimiters as $prime) {
        $i = 2;
        $result = $prime;
        $valid = true;
        do {
            $result = bcpow($prime, (string)$i);
            $valid = $result <= $digit;
            if ($valid && bcmod($digit, $result) === '0') {
                $baseDelimiters[$result] = $result;
            }
            $i++;
        } while ($valid);
    }
    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters === $delimiters ? $digit : '-1') . PHP_EOL;
}

//echo microtime(true) - $start;

<?php
# 1165D
declare(strict_types=1);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    sort($delimiters);
    $digit = bcmul($delimiters[0], $delimiters[$n - 1]);
    for ($i = 0; $i < $n; $i++) {
        if (bcmod($digit, $delimiters[$i]) !== '0') {
            $digit = bcmul($digit, $delimiters[$i]);
        }
    }
    for ($i = 0; $i < $n; $i++) {
        if ($digit === $delimiters[$i]) {
            $digit = '-1';
            break;
        }
    }

    echo $digit . PHP_EOL;
}

<?php
# 1165D
declare(strict_types=1);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];
    $digit = bcmul($delimiters[0], $maxDelimiter);
    for ($i = 0; $i < $n; $i++) {
        if (bcmod($digit, $delimiters[$i]) !== '0') {
            $digit = '-1';
            break;
        }
    }
    if ($digit === '-1') {
        $digit = bcmul($maxDelimiter, $maxDelimiter);
        for ($i = 0; $i < $n; $i++) {
            if (bcmod($digit, $delimiters[$i]) !== '0') {
                $digit = '-1';
                break;
            }
        }
    }

    echo $digit . PHP_EOL;
}

<?php
# 1165D
//declare(strict_types=1);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

$primes = getPrimeNumbersViaErastofen(1000000);

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $minDelimiter = $delimiters[0];
    $maxDelimiter = $delimiters[$n - 1];

    if ($n <= 2) {
        echo bcmul($delimiters[0], $maxDelimiter) . PHP_EOL;
        continue;
    }

    for ($i = 0; $i < $n; $i++) {
        if (bcmod($maxDelimiter, $delimiters[$i]) !== '0') {
            $wrongDigit = false;
            break;
        }
    }
    if ($wrongDigit === true) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $multiPlies = bcmul($minDelimiter, $maxDelimiter);

    $primeDelimiters = [];
    foreach ($primes as $prime) {
        if (bccomp($prime, $multiPlies) === 1) {
            break;
        }
        if (bcmod($multiPlies, $prime) === '0') {
            $primeDelimiters[] = $prime;
        }
    }
    $primeDelimitersCount = count($primeDelimiters);

    $powerMask = [];
    $maxPower = $primeDelimitersCount * $primeDelimitersCount;
    $baseMask = $arrayMask = array_fill(0, $primeDelimitersCount, 0);
    for ($j = 0; $j < $primeDelimitersCount; $j++) {
        $arrayMask = $baseMask;
        $arrayMask[$j] = 1;
        for($i = 0; $i <= $maxPower; $i++) {
            $powerMask[] = implode(' ', $arrayMask);
            $ind = $i % $primeDelimitersCount;
            $arrayMask[$ind]++;
            $tmp = $baseMask;
            $tmp[$ind] = $arrayMask[$ind];
            $powerMask[] = implode(' ', $tmp);
        }
        $powerMask[] = implode(' ', $arrayMask);
    }
    $powerMask = array_unique($powerMask);
    sort($powerMask);
    $baseDelimiters = [];

    foreach ($powerMask as $m) {
        $m = explode(' ', $m);
        $baseDelimiter = 1;
        foreach ($primeDelimiters as $i => $prime) {
            $baseDelimiter = bcmul($baseDelimiter, bcpow($prime, $m[$i]));
        }
        if (bcmod($multiPlies, $baseDelimiter) === '0') {
            $baseDelimiters[] = $baseDelimiter;
        }
    }
    unset($powerMask, $baseMask, $arrayMask, $tmp);
    sort($baseDelimiters);
    if ($delimiters === $baseDelimiters) {
        echo $multiPlies . PHP_EOL;
    } else {
        echo '-1' . PHP_EOL;
    }
}

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
//$stdin = fopen('/home/vilnitskiy/.PhpStorm2019.1/config/scratches/data.txt', 'rb');
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    if ($n <= 2) {
        echo bcmul($delimiters[0], $maxDelimiter) . PHP_EOL;
        continue;
    }

    for ($i = 0; $i < $n; $i++) {
        if (bcmod($maxDelimiter, $delimiters[$i]) !== '0') {
            $wrongDigit = false;
            break;
        }
    }
    if ($wrongDigit === true) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $digit = bcmul($delimiters[0], $maxDelimiter);

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(1000000);
    }
    $baseDelimiters = [];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $digit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    foreach ($baseDelimiters as $prime) {
        $i = 2;
        $result = $prime;
        $valid = true;
        do {
            $result = bcpow($prime, (string)$i);
            $valid = $result <= $digit;
            if ($valid && bcmod($digit, $result) === '0') {
                $baseDelimiters[$result] = $result;
            }
            $i++;
        } while ($valid);
    }
    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters === $delimiters ? $digit : '-1') . PHP_EOL;
}

echo microtime(true) - $start;

<?php
# 1165D
declare(strict_types=1);
$start = microtime(true);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    if ($n === 1) {
        $digit = $delimiters[0] ** 2;
    } else {
        $digit = max($delimiters) * 2;
        for ($i = 0; $i < $n; $i++) {
            if (($digit % $delimiters[$i]) !== 0) {
                $digit = -1;
                break;
            }
        }
    }
    echo $digit . PHP_EOL;
}

<?php
# 1165D
declare(strict_types=1);
$start = microtime(true);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    sort($delimiters);
    $digit = (float)$delimiters[0] * (float)$delimiters[$n - 1];
    for ($i = 0; $i < $n; $i++) {
        if (($digit % (float)$delimiters[$i]) !== 0) {
            $digit *= (float)$delimiters[$i];
        }
    }
    for ($i = 0; $i < $n; $i++) {
        if ($digit === (float)$delimiters[$i]) {
            $digit = '-1';
            break;
        }
    }

    echo sprintf('%.0f', $digit) . PHP_EOL;
}

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
//$stdin = fopen('/home/vilnitskiy/.PhpStorm2019.1/config/scratches/data.txt', 'rb');
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    if ($n <= 2) {
        echo bcmul($delimiters[0], $maxDelimiter) . PHP_EOL;
        continue;
    }

    for ($i = 0; $i < $n; $i++) {
        if (bcmod($maxDelimiter, $delimiters[$i]) !== '0') {
            $wrongDigit = false;
            break;
        }
    }
    if ($wrongDigit === true) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $digit = bcmul($delimiters[0], $maxDelimiter);

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(100000);
    }
    $baseDelimiters = [];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $digit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    foreach ($baseDelimiters as $delimiter) {
        $i = 2;
        $result = $delimiter;
        $valid = true;
        do {
            $result = bcpow($delimiter, (string)$i);
            $valid = $result <= $digit;
            if ($valid && bcmod($digit, $result) === '0') {
                $baseDelimiters[$result] = $result;
            }
            $i++;
        } while ($valid);
    }
    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    foreach ($baseDelimiters as $delimiter) {
        if (bcmod($digit, $delimiter) === '0') {
            $result = bcdiv($digit, $delimiter);
            $baseDelimiters[$result] = $result;
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters == $delimiters ? $digit : '-1') . PHP_EOL;
}

//echo microtime(true) - $start;

<?php
# 1165D
declare(strict_types=1);
$start = microtime(true);

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $digit = max($delimiters) * 2;
    for ($i = 0; $i < $n; $i++) {
        if (($digit % $delimiters[$i]) !== 0) {
            $digit = -1;
            break;
        }
    }
    echo $digit . PHP_EOL;
}

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
//$stdin = fopen('/home/vilnitskiy/.PhpStorm2019.1/config/scratches/data.txt', 'rb');
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    if ($n <= 2) {
        echo bcmul($delimiters[0], $maxDelimiter) . PHP_EOL;
        continue;
    }

    for ($i = 0; $i < $n; $i++) {
        if (bcmod($maxDelimiter, $delimiters[$i]) !== '0') {
            $wrongDigit = false;
            break;
        }
    }
    if ($wrongDigit === true) {
        echo '-1' . PHP_EOL;
        continue;
    }

    $digit = bcmul($delimiters[0], $maxDelimiter);

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(100000);
    }
    $baseDelimiters = [];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if (bccomp($prime, $digit) > -1) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    foreach ($baseDelimiters as $prime) {
        $i = 2;
        $result = $prime;
        $valid = true;
        do {
            $result = bcpow($prime, (string)$i);
            $valid = bccomp($result, $digit) < 1;
            if ($valid && bcmod($digit, $result) === '0') {
                $baseDelimiters[$result] = $result;
            }
            $i++;
        } while ($valid);
    }
    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if (bccomp($result, $digit) < 0 && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters === $delimiters ? $digit : '-1') . PHP_EOL;
}

//echo microtime(true) - $start;

<?php
# 1165D
declare(strict_types=1);

$start = microtime(true);

function getPrimeNumbersViaErastofen($n)
{
    /** @var int[] $result */
    $result[2] = 2;
    for ($i = 3; $i <= $n; $i += 2) {
        if ($i >= 10 && (($i % 5) === 0)) {
            continue;
        }
        $result[$i] = $i;
    }

    $i = reset($result);
    while ($i !== false) {
        if (isset($result[$i])) {
            /** @var int $j */
            $j = $i * 2;
            while ($j < $n) {
                unset($result[$j]);
                $j += $i;
            }
        }
        $i = next($result);
    }
    return $result;
}

$primes = [];

$stdin = STDIN;
[$t] = fscanf($stdin, '%u');

for ($tI = 0; $tI < $t; $tI++) {
    $wrongDigit = true;
    [$n] = fscanf($stdin, '%u');
    $delimiters = explode(' ', trim(fgets($stdin)));
    $delimitersMap = array_keys($delimiters);
    sort($delimiters);
    $maxDelimiter = $delimiters[$n - 1];

    $digit = bcmul($delimiters[0], $maxDelimiter);

    if ($primes === []) {
        $primes = getPrimeNumbersViaErastofen(100000);
    }
    $baseDelimiters = [];
    foreach ($primes as $prime) {
        $prime = (string)$prime;
        if ($prime >= $digit) {
            break;
        }
        if (bcmod($digit, $prime) === '0') {
            $baseDelimiters[$prime] = $prime;
        }
    }

    foreach ($baseDelimiters as $delimiter) {
        $i = 2;
        $result = $delimiter;
        $valid = true;
        $result = bcpow($delimiter, (string)$i);
        $valid = $result < $digit;
        while ($valid) {
            $result = bcpow($delimiter, (string)$i);
            $valid = $result < $digit;
            if ($valid && bcmod($digit, $result) === '0') {
                $baseDelimiters[$result] = $result;
            }
            $i++;
        }
    }
    $tmp = [];
    while ($tmp !== $baseDelimiters) {
        $tmp = $baseDelimiters;
        foreach ($baseDelimiters as $a) {
            foreach ($baseDelimiters as $b) {
                $result = bcmul($a, $b);
                if ($result < $digit && bcmod($digit, $result) === '0') {
                    $baseDelimiters[$result] = $result;
                }
            }
        }
    }
    foreach ($baseDelimiters as $delimiter) {
        if (bcmod($digit, $delimiter) === '0') {
            $result = bcdiv($digit, $delimiter);
            $baseDelimiters[$result] = $result;
        }
    }
    sort($baseDelimiters);

    echo ($baseDelimiters == $delimiters ? $digit : '-1') . PHP_EOL;
}

//echo microtime(true) - $start;


The store sells $$$n$$$ items, the price of the $$$i$$$-th item is $$$p_i$$$. The store's management is going to hold a promotion: if a customer purchases at least $$$x$$$ items, $$$y$$$ cheapest of them are free.The management has not yet decided on the exact values of $$$x$$$ and $$$y$$$. Therefore, they ask you to process $$$q$$$ queries: for the given values of $$$x$$$ and $$$y$$$, determine the maximum total value of items received for free, if a customer makes one purchase.Note that all queries are independent; they don't affect the store's stock.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of items in the store and the number of queries, respectively. The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le 10^6$$$), where $$$p_i$$$ — the price of the $$$i$$$-th item. The following $$$q$$$ lines contain two integers $$$x_i$$$ and $$$y_i$$$ each ($$$1 \le y_i \le x_i \le n$$$) — the values of the parameters $$$x$$$ and $$$y$$$ in the $$$i$$$-th query.

For each query, print a single integer — the maximum total value of items received for free for one purchase.

NoteIn the first query, a customer can buy three items worth $$$5, 3, 5$$$, the two cheapest of them are $$$3 + 5 = 8$$$.In the second query, a customer can buy two items worth $$$5$$$ and $$$5$$$, the cheapest of them is $$$5$$$.In the third query, a customer has to buy all the items to receive the three cheapest of them for free; their total price is $$$1 + 2 + 3 = 6$$$.

<?php
$no = 'NO';
$yes = 'YES';
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647
define("ALPH", 'abcdefghijklmnopqrstuvwxyz');
$inter = "\n";
define("INTMAXVALUE",     2147483646);

 $loop = false;
 $t = $loop ? IO::getInt() : 1;
 while($t--) {
      solve();
 }

 function solve()
 {
     list($n, $q) = IO::getArray();
     $a = IO::getArray();
     rsort($a);
     $temp = [];
     for($i=$n-1; $i>=0; $i--) {
          if(isset($temp[$i+1])) {
              $temp[$i] =$temp[$i+1] + $a[$i];
          } else {
               $temp[$i] = $a[$i];
          }

     }
    while($q--) {
          list($x, $y) = IO::getArray();
          $ans = $temp[$x-$y] -$temp[$x];

          IO::pr($ans);
      }

 }

 class IO {
      public static function getInt()
      {
          return trim(fgets(STDIN));
      }

     public static function getArray()
     {
         return explode(' ', trim(fgets(STDIN)));
     }
     public static function pr($s)
     {
          echo $s, PHP_EOL;
     }
     public static function prArray($s)
     {
          echo implode( ' ', $s), PHP_EOL;
     }
     public static function getMinValue($x, $y) {
         return $x > $y ? $y : $x;
     }
     public static function getMaxValue($x, $y) {
         return $x > $y ? $x : $y;
     }
 }

 class Algor {
     public static function efclidLcm($a, $b) {
         return ($a  / self::efclidGcd($a, $b)) * $b;
     }
     public static function efclidGcd($a, $b) {
             return $b > 0 ? self::efclidGcd($b, $a % $b) : $a;
     }
    public static function isPrime($n) {
         $d = 2;
         while ($n % $d != 0) {
         $d += 1;
         }

        return $d == $n;
    }

     public static function fabicon($n, $a) {
         if($n <= 1) {
             return $a[$n];
         }
         for($i=2; $i<=$n; $i++) {
             $a[$i] = $a[$i-1] + $a[$i-2];
         }

         return $a[$n];
     }

     function getRotate($a, $s, $e, $ind) {
         $ar = [];
         for ($i= $s; $i<=$e; $i++) {
             $ar[$i] = $a[$i];
             $j = $i + $ind > $e ? $i + $ind - $e - 1 : $i + $ind;
             // echo $i, ' ', $j, ' ', $j < $i ? $ar[$j] : $a[$j] , "\n";
             $a[$i] = $j < $i ? $ar[$j] : $a[$j];
         }
         return $a;
     }

}

class bigOperation {
     public static function efclidLcm($a, $b) {
         return bcmul(bcdiv($a,  self::efclidGcd($a, $b)), $b);
     }
     public static function efclidGcd($a, $b) {
             return bccomp($b, 0) == 1 ? self::efclidGcd($b, bcmod($a, $b)) : $a;
     }
    public static function  isBigNumber($n)
    {
        return bccomp($n, INTMAXVALUE) == 1;
    }
    // bcadd — Сложить 2 числа произвольной точности
    public static function  bcAdd($x, $y)
    {
        return bcadd($x, $y);
    }
// bccomp — Сравнение двух чисел произвольной точности
//return 1 if x>y, 0= x==y, -1 x < y
    public static function  bcComp($x, $y)
    {
        return bccomp($x, $y);
    }
// bcdiv — Операция деления для чисел произвольной точности
    public static function  bcDiv($x, $y)
    {
        return bcdiv($x, $y);
    }
// bcmod — Получает остаток от деления чисел с произвольной точностью
    public static function  bcMod($x, $y)
    {
        return bcmod($x, $y);
    }
// bcmul — Умножение двух чисел с произвольной точностью
    public static function  bcMul($x, $y)
    {
        return bcmul($x, $y);
    }
// bcpow — Возведение в степень чисел с произвольной точностью
    public static function  bcPow($x, $y)
    {
        return bcpow($x, $y);
    }
// bcpowmod — Возводит одно число в степень другого и возвращает остаток от деления результата на третье число
// bcscale — Задает количество чисел после десятичной точки по умолчанию для всех bc math функций.
// bcsqrt — Извлекает квадратный корень из числа с произвольной точностью
    public static function  bcSqrt($x, $y)
    {
        return bcsqrt($x, $y);
    }
// bcsub — Вычитает одно число с произвольной точностью из другого
    public static function  bcSub($x, $y)
    {
        return bcsub($x, $y);
    }
    public static function getMaxValue($x, $y) {
        return bccomp($x, $y) == 1 ? $x : $y;
    }
    public static function getMinValue($x, $y) {
        return bccomp($x, $y) == 1 ? $y : $x;
    }

    public static function getDareje($n, $k) {
        if($k == 0) {
            return 1;
        }
        return bcmul($n, self::getDareje($n, $k-1));
    }
}

class Sorting
{
    public static function mergeSort($aArray) {
        if(count($aArray) <= 1) {
            return $aArray;
        }
        $aLeft = [];
        $aRight = [];
        $n =floor(count($aArray) / 2);
        for($i = 0; $i <$n; $i++) {
            $aLeft[] = $aArray[$i];
        }
        for($i = $n; $i <count($aArray); $i++) {
            $aRight[] = $aArray[$i];
        }

        return self::merge(self::mergeSort($aLeft), self::mergeSort($aRight));
    }

    public static function merge($aLeft, $aRight) {
        $aResult = [];
        $iL = 0;
        $iR = 0;

        while($iL < count($aLeft) && $iR < count($aRight)) {
            if($aLeft[$iL] <= $aRight[$iR]) {
                $aResult[] = $aLeft[$iL];
                $iL++;
            } else {
                $aResult[] = $aRight[$iR];
                $iR++;
            }
        }

        while($iL < count($aLeft)) {
            $aResult[] = $aLeft[$iL];
            $iL++;
        }
        while($iR < count($aRight)) {
            $aResult[] = $aRight[$iR];
            $iR++;
        }

        return $aResult;

    }
}

class SolveArchive
{

}


Innokentiy likes tea very much and today he wants to drink exactly n cups of tea. He would be happy to drink more but he had exactly n tea bags, a of them are green and b are black.Innokentiy doesn't like to drink the same tea (green or black) more than k times in a row. Your task is to determine the order of brewing tea bags so that Innokentiy will be able to drink n cups of tea, without drinking the same tea more than k times in a row, or to inform that it is impossible. Each tea bag has to be used exactly once.

The first line contains four integers n, k, a and b (1 ≤ k ≤ n ≤ 105, 0 ≤ a, b ≤ n) — the number of cups of tea Innokentiy wants to drink, the maximum number of cups of same tea he can drink in a row, the number of tea bags of green and black tea. It is guaranteed that a + b = n.

If it is impossible to drink n cups of tea, print "NO" (without quotes). Otherwise, print the string of the length n, which consists of characters 'G' and 'B'. If some character equals 'G', then the corresponding cup of tea should be green. If some character equals 'B', then the corresponding cup of tea should be black. If there are multiple answers, print any of them.


You are given two polynomials:  P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and  Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm.  Calculate limit .

The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly. The second line contains n + 1 space-separated integers — the factors of polynomial P(x): a0, a1, ..., an - 1, an ( - 100 ≤ ai ≤ 100, a0 ≠ 0). The third line contains m + 1 space-separated integers — the factors of polynomial Q(x): b0, b1, ..., bm - 1, bm ( - 100 ≤ bi ≤ 100, b0 ≠ 0).

If the limit equals  + ∞, print "Infinity" (without quotes). If the limit equals  - ∞, print "-Infinity" (without the quotes). If the value of the limit equals zero, print "0/1" (without the quotes). Otherwise, print an irreducible fraction — the value of limit , in the format "p/q" (without the quotes), where p is the — numerator, q (q > 0) is the denominator of the fraction.

NoteLet's consider all samples:           You can learn more about the definition and properties of limits if you follow the link: http://en.wikipedia.org/wiki/Limit_of_a_function

<?php

function gcd($a, $b)
{
  if ($b == 0)
    return $a;
  return gcd($b, $a % $b);
}

fscanf(STDIN, '%d %d', $n, $m);
$pa = explode(' ', trim(fgets(STDIN)));
$pb = explode(' ', trim(fgets(STDIN)));
$a = intval($pa[0]);
$b = intval($pb[0]);

if ($b < 0) {
  $a = -$a;
  $b = -$b;
}
if ($n < $m)
  printf("0/1\n");
else if ($n > $m)
  printf(($a < 0 ? "-" : "") . "Infinity\n");
else
{
  $d = gcd(abs($a), $b);
  printf("%d/%d\n", $a / $d, $b / $d);
}
?>

<?php
$in = fopen('php://stdin', 'r');
$read = split(' ', fgets($in));

$n = (int)$read[0];
$m = (int)$read[1];

$a = split(' ', fgets($in));
$a = (int)$a[0];
$b = split(' ', fgets($in));
$b = (int)$b[0];

if ($n > $m){
	if ($a * $b < 0){
		echo '-';
	}
	echo 'Infinity', PHP_EOL;
}else if ($n < $m){
	echo '0/1', PHP_EOL;
}else{
	$c = abs(gcd($a, $b));
	if ($b < 0){
		$a = -$a;
		$b = -$b;
	}

	echo $a/$c,'/',$b/$c, PHP_EOL;
}

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

<?php
// Retrieve input and show output
$stream = fopen("php://stdin", "r");
$input = stream_get_contents($stream);
echo func($input);

// Actual function
function func($in) {
$ins = preg_split("/[\s]+/", $in);
$n = $ins[0];
$m = $ins[1];
$dn = $ins[2];
$dm = $ins[$n+3];
if ($n > $m) {
	if ($dn * $dm > 0) {return "Infinity";} else {return "-Infinity";}
} else if ($n < $m) {
	return "0/1";
} else {
	$tn = abs($dn);
	$tm = abs($dm);
	while ($tn != $tm) {
		if ($tn > $tm) {$tn -= $tm;} else {$tm -= $tn;}
	}
	return (($dn * $dm > 0) ? "" : "-") . (abs($dn) / $tn) . "/" . (abs($dm) / $tm);
}
}
?>

<?php
function nsd($i, $j){
 if($i == $j) return $i;
 if($i > $j) return nsd($i - $j, $j); else return nsd($i, $j - $i);
}

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

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

if($n > $m) if($a[0] * $b[0] > 0) {print 'Infinity'; exit(0);}
                             else {print '-Infinity'; exit(0);}
elseif($n < $m){print '0/1'; exit(0);}

$ns = nsd(abs($a[0]),abs($b[0]));
print (($a[0] * $b[0] < 0)?'-':'').abs($a[0] / $ns).'/'.abs($b[0] / $ns);
?>

<?php

function gcd($a, $b)
{
  if ($b == 0)
    return $a;
  return gcd($b, $a % $b);
}

fscanf(STDIN, '%d %d', $n, $m);
$pa = explode(' ', trim(fgets(STDIN)));
$pb = explode(' ', trim(fgets(STDIN)));
$a = intval($pa[0]);
$b = intval($pb[0]);

if ($b < 0) {
  $a = -$a;
  $b = -$b;
}
if ($n < $m)
  printf("0/1\n");
else if ($n > $m)
  printf(($a < 0 ? "-" : "") . "Infinity\n");
else
{
  $d = gcd($a, $b);
  printf("%d/%d\n", $a / $d, $b / $d);
}
?>

<?php

function gcd($a, $b)
{
  if ($b == 0)
    return $a;
  return gcd($b, $a % $b);
}

fscanf(STDIN, '%d %d', $n, $m);
$pa = str_split(trim(fgets(STDIN)));
$pb = str_split(trim(fgets(STDIN)));
$a = $pa[0];
$b = $pb[0];

fprintf(STDERR, "%d %d\n", $a, $b);

if ($b < 0) {
  $a = -$a;
  $b = -$b;
}
if ($n < $m)
  printf("0/1\n");
else if ($n > $m)
  printf(($a < 0 ? "-" : "") . "Infinity\n");
else
{
  $d = gcd($a, $b);
  printf("%d/%d\n", $a / $d, $b / $d);
}
?>

<?php

function gcd($a, $b)
{
  if ($b == 0)
    return $a;
  return gcd($b, $a % $b);
}

fscanf(STDIN, '%d%d%d', $n, $m, $a);
for ($i = 0; $i < n; ++$i)
  fscanf(STDIN, '%d', $dummy);
fscanf(STDIN, '%d', $b);
for ($i = 0; $i < m; ++$i)
  fscanf(STDIN, '%d', $dummy);

if ($b < 0) {
  $a = -$a;
  $b = -$b;
}
if (n < m)
  printf("0/1\n");
else if (n > m)
  printf(($a < 0 ? "-" : "") + "-Infinity\n");
else
{
  $d = gcd($a, $b);
  printf("%d/%d\n", $a / $d, $b / $d);
}
?>

<?php

function gcd($a, $b)
{
  if ($b == 0)
    return $a;
  return gcd($b, $a % $b);
}

fscanf(STDIN, '%d %d', $n, $m);
$pa = str_split(trim(fgets(STDIN)));
$pb = str_split(trim(fgets(STDIN)));
$a = $pa[0];
$b = $pb[0];

if ($b < 0) {
  $a = -$a;
  $b = -$b;
}
if ($n < $m)
  printf("0/1\n");
else if ($n > $m)
  printf(($a < 0 ? "-" : "") + "Infinity\n");
else
{
  $d = gcd($a, $b);
  printf("%d/%d\n", $a / $d, $b / $d);
}
?>

<?php
// Retrieve input and show output
$stream = fopen("php://stdin", "r");
$input = stream_get_contents($stream);
echo func($input);

// Actual function
function func($in) {
$ins = preg_split("/[\s]+/", $in);
$n = $ins[0];
$m = $ins[1];
$dn = $ins[2];
$dm = $ins[$n+3];
if ($n > $m) {
	if ($dn * $dm > 0) {return "Infinity";} else {return "-Infinity";}
} else if ($m < $n) {
	return "0/1";
} else {
	$tn = $dn;
	$tm = $dm;
	while ($tn != $tm) {
		if ($tn > $tm) {$tn -= $tm;} else {$tm -= $tn;}
	}
	return ($dn / $tn) . "/" . ($dm / $tm);
}
}
?>

<?php
// Retrieve input and show output
$stream = fopen("php://stdin", "r");
$input = stream_get_contents($stream);
echo func($input);

// Actual function
function func($in) {
$ins = preg_split("/[\s]+/", $in);
$n = $ins[0];
$m = $ins[1];
$dn = $ins[2];
$dm = $ins[$n+3];
if ($m > $n) {
	if ($dn * $dm > 0) {return "Infinity";} else {return "-Infinity";}
} else if ($m < $n) {
	return "0/1";
} else {
	$tn = $dn;
	$tm = $dm;
	while ($tn != $tm) {
		if ($tn > $tm) {$tn -= $tm;} else {$tm -= $tn;}
	}
	return ($dn / $tn) . "/" . ($dm / $tm);
}
}
?>

<?php
function nsd($i, $j){
 if($i == $j) return $i;
 if($i > $j) return nsd($i - $j, $j); else return nsd($i, $j - $i);
}

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

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

if($n > $m) if($a[0] > 0) {print 'Infinity'; exit(0);}
                     else {print '-Infinity'; exit(0);}
elseif($n < $m){print '0/1'; exit(0);}

$ns = nsd(abs($a[0]),abs($b[0]));
print (($a[0] * $b[0] < 0)?'-':'').abs($a[0] / $ns).'/'.abs($b[0] / $ns);
?>


You are given a prime number $$$p$$$, $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, and an integer $$$k$$$. Find the number of pairs of indexes $$$(i, j)$$$ ($$$1 \le i < j \le n$$$) for which $$$(a_i + a_j)(a_i^2 + a_j^2) \equiv k \bmod p$$$.

The first line contains integers $$$n, p, k$$$ ($$$2 \le n \le 3 \cdot 10^5$$$, $$$2 \le p \le 10^9$$$, $$$0 \le k \le p-1$$$). $$$p$$$ is guaranteed to be prime. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le p-1$$$). It is guaranteed that all elements are different.

Output a single integer — answer to the problem.


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.

<?php

list($n, $a, $b) = explode(' ', trim(fgets(STDIN)));
$table = array();
for ($i = 0; $i < $a; $i++) {
	for ($j = 0; $j < $b; $j++) {
		$table[$i][$j] = 0;
	}
}
$setNum = 1;
$setMax = 0;
for ($i = 0; $i < $a; $i++) {
	$start = 0;
	if ($j % 2 == 0) {
		$start++;
	}
	for ($j = $start; $j < $b; $j+=2) {
		if ($setNum > $n) {
			break 2;
		}
		$table[$i][$j] = $setNum;
		$setMax = $setNum;
		$setNum+=2;
	}
}
$setNum = 2;
for ($i = 0; $i < $a; $i++) {
	for ($j = 0; $j < $b; $j++) {
		if ($setNum > $n) {
			break 2;
		}
		if (!empty($table[$i][$j])) {
			continue;
		}
		$table[$i][$j] = $setNum;
		$setMax = max($setMax, $setNum);
		$setNum+=2;
	}
}
if ($setMax == $n) {
	for ($i = 0; $i < $a; $i++) {
		for ($j = 0; $j < $b; $j++) {
			echo $table[$i][$j] . " ";
		}
		echo "\n";
	}
} else {
	echo '-1';
}

<?php
$h = fopen("php://stdin", "r");

$input=trim(fgets($h));
$input_arr=explode(' ', $input);
$n=intval($input_arr[0]);
$a=intval($input_arr[1]);
$b=intval($input_arr[2]);

$pos=array();
if($a*$b<$n)
    echo -1;
else {
    $good_rows=($b%2===1)?true:false;
    for($i=1; $i<=$n; $i++) {
        $row=intval(ceil($i/$b));
        if($good_rows) {
            $row_pos=$i-(($row-1)*$b);
        } else {
            if($row%2===1)
                $row_pos=$i-(($row-1)*$b);
            else
                $row_pos=$b+1-($i-(($row-1)*$b));
        }
        $pos[$row][$row_pos]=$i;
    }

    for($j=1; $j<=$a; $j++) {
        for($k=1; $k<=$b; $k++) {
            if(isset($pos[$j][$k]))
                echo $pos[$j][$k];
            else
                echo '0';

            if($k<=$b)
                echo ' ';
        }
        echo "\n";
    }

}


Reminder: the median of the array $$$[a_1, a_2, \dots, a_{2k+1}]$$$ of odd number of elements is defined as follows: let $$$[b_1, b_2, \dots, b_{2k+1}]$$$ be the elements of the array in the sorted order. Then median of this array is equal to $$$b_{k+1}$$$.There are $$$2n$$$ students, the $$$i$$$-th student has skill level $$$a_i$$$. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the $$$2$$$ classes such that each class has odd number of students (not divisible by $$$2$$$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of students halved. The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2 n}$$$ ($$$1 \le a_i \le 10^9$$$) — skill levels of students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.

NoteIn the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be $$$|1 - 1| = 0$$$.In the second test, one of the possible partitions is to make the first class of students with skill levels $$$[6, 4, 2]$$$, so that the skill level of the first class will be $$$4$$$, and second with $$$[5, 1, 3]$$$, so that the skill level of the second class will be $$$3$$$. Absolute difference will be $$$|4 - 3| = 1$$$.Note that you can't assign like $$$[2, 3]$$$, $$$[6, 5, 4, 1]$$$ or $$$[]$$$, $$$[6, 5, 4, 1, 2, 3]$$$ because classes have even number of students.$$$[2]$$$, $$$[1, 3, 4]$$$ is also not possible because students with skills $$$5$$$ and $$$6$$$ aren't assigned to a class.In the third test you can assign the students in the following way: $$$[3, 4, 13, 13, 20], [2, 5, 8, 16, 17]$$$ or $$$[3, 8, 17], [2, 4, 5, 13, 13, 16, 20]$$$. Both divisions give minimal possible absolute difference.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     $c = explode(" ", trim(fgets(STDIN)));
     sort($c);
     print abs($c[$b - 1] - $c[$b]) . "\n";
}
?>

<?php

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

$cases = fgets($f);

for ($k = 0; $k < $cases; $k++) {
  $line = trim(fgets($f));
  $line = trim(fgets($f));

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

  sort($arr);

  print abs($arr[intdiv(count($arr), 2)] - $arr[intdiv(count($arr), 2) - 1]) . "\n";
}

?>

<?php
$cases = fgets(STDIN);
for($c=0;$c<$cases;$c++)
{
    $students=trim(fgets(STDIN));
    $skills=explode(' ',trim(fgets(STDIN)));
    sort($skills);
    print abs($skills[$students-1]-$skills[$students]) . "\n";
}
?>

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$h = trim(fgets($handle));

for ($j = 0; $j < $h; $j++) {
    $f = trim(fgets($handle));
    $arr = trim(fgets($handle));
    $arr = explode(' ', $arr);
    sort($arr);
    echo $arr[$f] - $arr[$f - 1];
    echo "\n";

}
/*shajkjs*/

?>

<?php

class ArgsHelper
{
	private $useStd;

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

	public function calculateResult($input)
	{
		$numbers = array_map('intval', explode(' ', $input));
		sort($numbers);
		$c = count($numbers);
		return abs($numbers[$c / 2] - $numbers[$c / 2 - 1]);
	}

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

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

}

##################################################
$testInput = '3
1
1 1
3
6 5 4 1 2 3
5
13 4 20 13 2 5 8 3 17 16
';
$helper = new ArgsHelper();
$lines = $helper->getInputLines();

$result = '';
#
array_shift($lines);
foreach ($lines as $index => $line)
{
	if ($index % 2 === 0)
	{
		continue;
	}
	$result .= $helper->calculateResult($line) . "\n";
}
$result = trim($result);
#

$helper->printResult($result);

<?php
$server = "php://stdin";
$local = "input.txt";
$handle = fopen($server, "r");
$t= trim(fgets($handle));

for($j=0;$j<$t;$j++)
{
    $n=trim(fgets($handle));
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    sort($a);
    echo $a[$n]-$a[$n-1]."\n";

}

?>

<?php
$cases = fgets(STDIN);
for($c=0;$c<$cases;$c++)
{
    $students=fgets(STDIN);
    $students=(float)$students;
    $skills=explode(' ',fgets(STDIN));
    sort($skills);
    print abs((float)$skills[$students-1]-(float)$skills[$students]) . "\n";
}
?>

<?php
$cases = fgets(STDIN);
for($c=0;$c<$cases;$c++)
{
    $students=fgets(STDIN);
    $students=(int)$students;
    $skills=explode(' ',fgets(STDIN));
    sort($skills);
    print abs((int)$skills[$students-1]-(int)$skills[$students]) . "\n";
}
?>

<?php
$cases = fgets(STDIN);
$cases=(int)$cases;
for($c=0;$c<$cases;$c++)
{
    $students=fgets(STDIN);
    $students=(int)$students;
    $skills=fgets(STDIN);
    $skills=explode(' ', $skills);
    sort($skills);
    echo abs((int)$skills[$students-1]-(int)$skills[$students]);
    echo "\n";

}
?>


ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?

The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.

Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.


Another Codeforces Round has just finished! It has gathered $$$n$$$ participants, and according to the results, the expected rating change of participant $$$i$$$ is $$$a_i$$$. These rating changes are perfectly balanced — their sum is equal to $$$0$$$.Unfortunately, due to minor technical glitches, the round is declared semi-rated. It means that all rating changes must be divided by two.There are two conditions though:   For each participant $$$i$$$, their modified rating change $$$b_i$$$ must be integer, and as close to $$$\frac{a_i}{2}$$$ as possible. It means that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. In particular, if $$$a_i$$$ is even, $$$b_i = \frac{a_i}{2}$$$. Here $$$\lfloor x \rfloor$$$ denotes rounding down to the largest integer not greater than $$$x$$$, and $$$\lceil x \rceil$$$ denotes rounding up to the smallest integer not smaller than $$$x$$$.  The modified rating changes must be perfectly balanced — their sum must be equal to $$$0$$$. Can you help with that?

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 13\,845$$$), denoting the number of participants. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$-336 \le a_i \le 1164$$$), denoting the rating change of the $$$i$$$-th participant. The sum of all $$$a_i$$$ is equal to $$$0$$$.

Output $$$n$$$ integers $$$b_i$$$, each denoting the modified rating change of the $$$i$$$-th participant in order of input. For any $$$i$$$, it must be true that either $$$b_i = \lfloor \frac{a_i}{2} \rfloor$$$ or $$$b_i = \lceil \frac{a_i}{2} \rceil$$$. The sum of all $$$b_i$$$ must be equal to $$$0$$$. If there are multiple solutions, print any. We can show that a solution exists for any valid input.

NoteIn the first example, $$$b_1 = 5$$$, $$$b_2 = -3$$$ and $$$b_3 = -2$$$ is another correct solution.In the second example there are $$$6$$$ possible solutions, one of them is shown in the example output.


Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of $$$a$$$.The thermostat can only be set to a temperature from $$$l$$$ to $$$r$$$ inclusive, the temperature cannot change by less than $$$x$$$. Formally, in one operation you can reconfigure the thermostat from temperature $$$a$$$ to temperature $$$b$$$ if $$$|a - b| \ge x$$$ and $$$l \le b \le r$$$.You are given $$$l$$$, $$$r$$$, $$$x$$$, $$$a$$$ and $$$b$$$. Find the minimum number of operations required to get temperature $$$b$$$ from temperature $$$a$$$, or say that it is impossible.

The first line of input data contains the single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of each case contains three integers $$$l$$$, $$$r$$$ and $$$x$$$ ($$$-10^9 \le l \le r \le 10^9$$$, $$$1 \le x \le 10^9$$$) — range of temperature and minimum temperature change. The second line of each case contains two integers $$$a$$$ and $$$b$$$ ($$$l \le a, b \le r$$$) — the initial and final temperatures.

Output $$$t$$$ numbers, each of which is the answer to the corresponding test case. If it is impossible to achieve the temperature $$$b$$$, output -1, otherwise output the minimum number of operations.

NoteIn the first example, the thermostat is already set up correctly.In the second example, you can achieve the desired temperature as follows: $$$4 \rightarrow 10 \rightarrow 5$$$.In the third example, you can achieve the desired temperature as follows: $$$3 \rightarrow 8 \rightarrow 2 \rightarrow 7$$$.In the fourth test, it is impossible to make any operation.

<?php

$tests = getLineInt();

$pattern = "Yes";

$patternLength = strlen($pattern);

$results = array();

for ($test = 0; $test < $tests; $test++)
{
    list($minT, $maxT, $stepT) = getLineInts();

    list($initT, $endT) = getLineInts();

    $diffInitEndT = abs($initT - $endT);
    $diffInitMinT = abs($initT - $minT);
    $diffInitMaxT = abs($initT - $maxT);
    $diffEndMinT = abs($endT - $minT);
    $diffEndMaxT = abs($endT - $maxT);
    $diffMinMaxT = abs($minT - $maxT);

    if ($diffInitEndT <= 0)
    {
        $results[] = 0;
    }

    else if ($diffInitEndT >= $stepT)
    {
        $results[] = 1;
    }

    else if ($diffInitMinT >= $stepT && $diffEndMinT >= $stepT)
    {
        $results[] = 2;
    }

    else if ($diffInitMaxT >= $stepT && $diffEndMaxT >= $stepT)
    {
        $results[] = 2;
    }

    else if ($diffInitMinT >= $stepT && $diffMinMaxT >= $stepT && $diffEndMaxT >= $stepT)
    {
        $results[] = 3;
    }

    else if ($diffInitMaxT >= $stepT && $diffMinMaxT >= $stepT && $diffEndMinT >= $stepT)
    {
        $results[] = 3;
    }

    else {
        $results[] = -1;
    }
}

echo(implode(PHP_EOL, $results));

// Helpers

function getLineInt()
{
    return (int) trim(fgets(STDIN));
}

function getLineInts()
{
    return array_map("intval", explode(' ', trim(fgets(STDIN))));
}

function getString()
{
    return trim(fgets(STDIN));
}

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

<?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++){
    [$l,$r,$x] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    [$a,$b] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $cnt = 0;
    if($a == $b){
        $ans[] = 0;
        continue;
    }
    if(abs($a-$b) >= $x) {
        $ans[] = 1;
        continue;
    }
    if($a < $b){
        if($r >= $b + $x){
            $ans[] = 2;
            continue;
        }
        if($l <= $a - $x){
            $ans[] = 2;
            continue;
        }
        if($a + $x <= $r && (abs($r-$b) >= $x || abs($l-$b) >= $x)){
            $ans[] = 3;
            continue;
        }
        $ans[] = -1;
        continue;
    }else{
        if($l <= $b - $x){
            $ans[] = 2;
            continue;
        }
        if($r >= $a + $x){
            $ans[] = 2;
            continue;
        }
        if($a - $x >= $l  && (abs($r-$b) >= $x || abs($l-$b) >= $x)){
            $ans[] = 3;
            continue;
        }
        $ans[] = -1;
        continue;
    }
}
echo implode(PHP_EOL, $ans);


Cheaterius is a famous in all the Berland astrologist, magician and wizard, and he also is a liar and a cheater. One of his latest inventions is Cheaterius' amulets! They bring luck and wealth, but are rather expensive. Cheaterius makes them himself. The technology of their making is kept secret. But we know that throughout long nights Cheaterius glues together domino pairs with super glue to get squares 2 × 2 which are the Cheaterius' magic amulets!    That's what one of Cheaterius's amulets looks like After a hard night Cheaterius made n amulets. Everyone of them represents a square 2 × 2, every quarter contains 1 to 6 dots. Now he wants sort them into piles, every pile must contain similar amulets. Two amulets are called similar if they can be rotated by 90, 180 or 270 degrees so that the following condition is met: the numbers of dots in the corresponding quarters should be the same. It is forbidden to turn over the amulets.Write a program that by the given amulets will find the number of piles on Cheaterius' desk.

The first line contains an integer n (1 ≤ n ≤ 1000), where n is the number of amulets. Then the amulet's descriptions are contained. Every description occupies two lines and contains two numbers (from 1 to 6) in each line. Between every pair of amulets the line "**" is located.

<?php

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

for($i = 0; $i< $n; $i++){
    $row1 = readline();
    $row2 = readline();
    if($i != $n -1){
        $ignore = readline();
    }
    $cur = str_split($row1 . $row2[1] . $row2[0]);
    $existed = 0;
    foreach($stacks as $stack){
        if($existed == 1){
            break;
        }
        for($j=0;$j<4;$j++){
            array_push($cur, array_shift($cur));
            if($stack == implode('', $cur)){
                $existed = 1;
                break;
            }
        }
    }
    if($existed == 0){
        array_push($stacks , implode('', $cur));
    }
}

echo sizeof($stacks);


Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. The student can't send messages to himself. In early morning Polycarp knew important news that the programming credit will be tomorrow. For this reason it is necessary to urgently inform all groupmates about this news using private messages. Your task is to make a plan of using private messages, so that:  the student i sends no more than ai messages (for all i from 1 to n);  all students knew the news about the credit (initially only Polycarp knew it);  the student can inform the other student only if he knows it himself. Let's consider that all students are numerated by distinct numbers from 1 to n, and Polycarp always has the number 1.In that task you shouldn't minimize the number of messages, the moment of time, when all knew about credit or some other parameters. Find any way how to use private messages which satisfies requirements above.

The first line contains the positive integer n (2 ≤ n ≤ 100) — the number of students.  The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 100), where ai equals to the maximum number of messages which can the i-th student agree to send. Consider that Polycarp always has the number 1.

Print -1 to the first line if it is impossible to inform all students about credit.  Otherwise, in the first line print the integer k — the number of messages which will be sent. In each of the next k lines print two distinct integers f and t, meaning that the student number f sent the message with news to the student number t. All messages should be printed in chronological order. It means that the student, who is sending the message, must already know this news. It is assumed that students can receive repeated messages with news of the credit.  If there are several answers, it is acceptable to print any of them.

NoteIn the first test Polycarp (the student number 1) can send the message to the student number 2, who after that can send the message to students number 3 and 4. Thus, all students knew about the credit.

<?php
$n = intval(fgets(STDIN));
$a = array_map('intval', explode(" ", fgets(STDIN)));

$messageList = array();

$aSorted = array_slice($a, 1);
arsort($aSorted);

$aNotInformed = array_keys($aSorted);

function canBeSolved($a, $n){
    $result = true;
    if((array_sum($a) < $n - 1) || $a[0] == 0) $result = false;
    return $result;
}

function getResult($result){
    echo $result;
    exit(false);
}

function echoResultArray($array){
    echo count($array).PHP_EOL;
    foreach($array as $key => $string){
        echo $string.PHP_EOL;
    }
}

function isEverybodyInformed($aNotInformed){
    $result = false;

    if(!count($aNotInformed)) $result = true;

    return $result;
}

function solveTask($a, $n, $aSorted, $aNotInformed, $messageList){
    if(!canBeSolved($a, $n)) getResult(-1);

    $policarpMessages = $a[0];

    foreach($aSorted as $key => $value){
        if($policarpMessages > 0){
            $niKey = array_shift($aNotInformed);
            $messageList[] = '1 '.($niKey + 2);
            --$policarpMessages;
        }else break;
    }

    if(!isEverybodyInformed($aNotInformed)){
        foreach($aSorted as $guyId => $guyMessages){
            while($guyMessages){
                $niKey = array_shift($aNotInformed);
                $messageList[] = ($guyId + 2).' '.($niKey + 2);
                --$guyMessages;
                if(!count($aNotInformed)) break 2;
            }
        }
    }

    return $messageList;
}

$messageList = solveTask($a, $n, $aSorted, $aNotInformed, $messageList);

echoResultArray($messageList);

<?php
error_reporting(E_ALL);
ini_set("memory_limit", "256M");
ini_set("max_execution_time", 3);

$fd = fopen("php://stdin", 'r');
$count = (int) fgets($fd);
$send  = explode(" ", trim(fgets($fd)));

$rootSenderId = 1;
$rootSenderMessages = (int)$send[0];

if ($rootSenderMessages == 0) {
    echo "-1";
    die();
}

unset($send[0]);
arsort($send);

$senders = [[$rootSenderId, $rootSenderMessages]];
foreach ($send as $key => $value) {
    $senders[] = [$key + 1, (int)$value];
}

$messages = [];
$receivePointer = 1;
foreach ($senders as $senderInfo) {
    list($id, $sendCount) = $senderInfo;
    for($i = 0; $i < $sendCount; $i++) {
        if (!isset($senders[$receivePointer][0])) {
            break;
        }
        $messages[] = $id . " " . $senders[$receivePointer][0];
        $receivePointer++;
    }
}

if (count($messages) < count($send)) {
    echo "-1";
    die();
}

echo count($messages) . "\n";
echo implode("\n", $messages);

<?
$stdin = fopen('php://stdin', 'r');
$lines = stream_get_contents($stdin);
$lines = explode("\n", $lines);

$n = $lines[0];
$users = explode(' ', $lines[1]);

$from = 0;
$groups = array(array(1, $users[0]));
arsort($users);
foreach ($users as $key => $value) {
    if ($key + 1 != $groups[$from][0]) {
        array_push($groups, array($key + 1, $value));
    }
}

$fromMsgCount = 0;
$msgCount = 0;
$logs = '';

for ($i = 1; $i < $n; $i++) {
    if ($fromMsgCount < $groups[$from][1]) {
        $msgCount++;
        $logs .= ($groups[$from][0]) . ' ' . ($groups[$i][0]) . "\n";
        $fromMsgCount++;
        if ($fromMsgCount == $groups[$from][1]) {
            $fromMsgCount = 0;
            $from++;
        }
    } else {
        break;
    }
}

if ($msgCount == (int)$n - 1) {
    echo $msgCount . "\n";
    echo $logs;
} else {
    echo -1;
}
?>

<?php
$n = intval(fgets(STDIN));
$a = array_map('intval', explode(" ", fgets(STDIN)));

$messageList = array();

$aSorted = array_slice($a, 1);
arsort($aSorted);

$aNotInformed = array_keys($aSorted);

function canBeSolved($a, $n){
    $result = true;
    if((array_sum($a) < $n - 1) || $a[0] == 0) $result = false;
    return $result;
}

function getResult($result){
    echo $result;
    exit(false);
}

function echoResultArray($array){
    echo count($array).PHP_EOL;
    foreach($array as $key => $string){
        echo $string.PHP_EOL;
    }
}

function solveTask($a, $n, $aSorted, $aNotInformed, $messageList){
    if(!canBeSolved($a, $n)) getResult(-1);

    $policarpMessages = $a[0];

    foreach($aSorted as $key => $value){
        if($policarpMessages > 0){
            $niKey = array_shift($aNotInformed);
            $messageList[] = '1 '.($niKey + 2);
            --$policarpMessages;
        }else break;
    }

    foreach($aSorted as $guyId => $guyMessages){
        while($guyMessages){
            $niKey = array_shift($aNotInformed);
            $messageList[] = ($guyId + 2).' '.($niKey + 2);
            --$guyMessages;
            if(!count($aNotInformed)) break 2;
        }
    }

    return $messageList;
}

$messageList = solveTask($a, $n, $aSorted, $aNotInformed, $messageList);

echoResultArray($messageList);


Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.Dima can buy boxes at a factory. The factory produces boxes of K kinds, boxes of the i-th kind can contain in themselves ai hamsters. Dima can buy any amount of boxes, but he should buy boxes of only one kind to get a wholesale discount.Of course, Dima would buy boxes in such a way that each box can be completely filled with hamsters and transported to the city. If there is no place for some hamsters, Dima will leave them on the farm.Find out how many boxes and of which type should Dima buy to transport maximum number of hamsters.

The first line contains two integers N and K (0 ≤ N ≤ 1018, 1 ≤ K ≤ 105) — the number of hamsters that will grow up on Dima's farm and the number of types of boxes that the factory produces. The second line contains K integers a1, a2, ..., aK (1 ≤ ai ≤ 1018 for all i) — the capacities of boxes.

Output two integers: the type of boxes that Dima should buy and the number of boxes of that type Dima should buy. Types of boxes are numbered from 1 to K in the order they are given in input. If there are many correct answers, output any of them.