In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.

The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.

For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.

NoteThe picture corresponds to the first example test case.  When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
array_unshift($b, " ");
unset($b[0]);
for($x = 1; $x <= $a; $x++)
{
     $c = array_fill(1, $a, 0);
     $d = $x;
     while(TRUE)
     {
          $c[$d]++;
          if($c[$d] > 1)
          {
               print $d . " ";
               break;
          }
          else
          {
               $d = $b[$d];
          }
     }
}
?>

<?php
// define('DEBUG', true);
define('DEBUG', false);

ini_set('error_reporting', E_ALL & ~E_NOTICE);

fscanf(STDIN, "%d", $n);
$p = explode(" ", trim(fgets(STDIN)));
if (DEBUG) {
	var_dump($p);
}

for ($i = 1; $i <= $n; $i++) {
	$array = array_pad(array(), $n + 1, 0);
	if (DEBUG) {
		var_dump($array);
	}

	$point = $i;
	while (true) {
		if (DEBUG) {
			echo "-----\n";
		}

		if (DEBUG) {
			echo $point . PHP_EOL;
		}

		$array[$point]++;
		if ($array[$point] == 2) {
			$answer[] = $point;
			break;
		}
		$point = $p[$point - 1];
	}
}
echo implode(" ", $answer);

<?php
$z = fopen('php://stdin','r');
$n = intval(fgets($z));
$a = array_map(function($v) {return intval($v);}, explode(' ', fgets($z)));
array_unshift($a,0);

for($i = 1; $i <= $n; $i++) {
    $b = array_pad(array(0), $n+1, 0);
    $j = $i;
    $b[$j]=1;
    do {
        $j = $a[$j];
        $b[$j]++;
    } while ($b[$j] < 2);
    echo $j . " ";
}


Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).Polycarpus knows m words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these m words.At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.

The first line contains one integer n (1 ≤ n ≤ 50) — the length of the hidden word. The following line describes already revealed letters. It contains the string of length n, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed. The third line contains an integer m (1 ≤ m ≤ 1000) — the number of words of length n, which Polycarpus knows. The following m lines contain the words themselves — n-letter strings of lowercase Latin letters. All words are distinct. It is guaranteed that the hidden word appears as one of the given m words. Before the current move Polycarp has told exactly the letters which are currently revealed.

Output the single integer — the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.

NoteIn the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns.


Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.


The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1, a2, ..., an (16 ≤ ai ≤ 32768); number ai denotes the maximum data transfer speed on the i-th computer.

Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.

NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
rsort($c);
print $c[$b - 1];
?>

<?php
/*
 * Secdra @2020
 */

fscanf(STDIN, "%d %d", $n, $k);
$a = explode(' ', trim(fgets(STDIN)));
sort($a);
$a = array_slice($a, -$k);
printf("%d", $a[0]);

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

sort($s);

$i = $c - $p;

echo $s[$i];


You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive.  All the written labels are distinct.  The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.

The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.

Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).


Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1, a2, ..., an. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105), that denote the number of counters Valera has and the number of pairs of counters connected by wires. Each of the following m lines contains two space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that mean that counters with numbers ui and vi are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input. The last line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 105), where ai is the value that Ignat choose for the i-th counter.

If Valera can't win the dispute print in the first line -1. Otherwise, print in the first line integer k (0 ≤ k ≤ n). In the second line print k distinct space-separated integers — the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order. If there exists multiple answers, you are allowed to print any of them.

<?php

/**
 * Counter $u needs to be pressed because it has a value equal to the predicted
 * value in $a[$u].
 */
function dfs($u, array $graph, array $a, array & $values, array & $pressed)
{
    $pressed[$u] = true;
    $values[$u]++;
    foreach ($graph[$u] as $v)
    {
        $values[$v]++;
        if ($values[$v] == $a[$v])
            dfs($v, $graph, $a, $values, $pressed);
    }
}

function determineCounters($n, array $graph, array $a)
{
    $values = array_fill(1, $n, 0);
    $pressed = array_fill(1, $n, false);
    for ($i = 1; $i <= $n; ++$i)
        if ($a[$i] == $values[$i])
            dfs($i, $graph, $a, $values, $pressed);
    $counters = array();
    for ($i = 1; $i <= $n; ++$i)
        if ($pressed[$i])
            $counters[] = $i;
    return $counters;
}

function main()
{
    fscanf(STDIN, "%d %d", $n, $m);
    $graph = array_fill(1, $n, array());
    for ($i = 0; $i < $m; ++$i)
    {
        fscanf(STDIN, "%d %d", $u, $v);
        $graph[$u][] = $v;
        $graph[$v][] = $u;
    }
    $a = explode(" ", fgets(STDIN));
    foreach ($a as $index => $value)
        $a[$index + 1] = (int)$value;
    $counters = determineCounters($n, $graph, $a);
    fprintf(STDOUT, "%d\n", count($counters));
    foreach ($counters as $counter)
        fprintf(STDOUT, "%d ", $counter);
}

main();


You are a coach of a group consisting of $$$n$$$ students. The $$$i$$$-th student has programming skill $$$a_i$$$. All students have distinct programming skills. You want to divide them into teams in such a way that:  No two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ belong to the same team (i.e. skills of each pair of students in the same team have the difference strictly greater than $$$1$$$);  the number of teams is the minimum possible. You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of students in the query. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$, all $$$a_i$$$ are distinct), where $$$a_i$$$ is the programming skill of the $$$i$$$-th student.

For each query, print the answer on it — the minimum number of teams you can form if no two students $$$i$$$ and $$$j$$$ such that $$$|a_i - a_j| = 1$$$ may belong to the same team (i.e. skills of each pair of students in the same team has the difference strictly greater than $$$1$$$)

NoteIn the first query of the example, there are $$$n=4$$$ students with the skills $$$a=[2, 10, 1, 20]$$$. There is only one restriction here: the $$$1$$$-st and the $$$3$$$-th students can't be in the same team (because of $$$|a_1 - a_3|=|2-1|=1$$$). It is possible to divide them into $$$2$$$ teams: for example, students $$$1$$$, $$$2$$$ and $$$4$$$ are in the first team and the student $$$3$$$ in the second team.In the second query of the example, there are $$$n=2$$$ students with the skills $$$a=[3, 6]$$$. It is possible to compose just a single team containing both students.


A number is ternary if it contains only digits $$$0$$$, $$$1$$$ and $$$2$$$. For example, the following numbers are ternary: $$$1022$$$, $$$11$$$, $$$21$$$, $$$2002$$$.You are given a long ternary number $$$x$$$. The first (leftmost) digit of $$$x$$$ is guaranteed to be $$$2$$$, the other digits of $$$x$$$ can be $$$0$$$, $$$1$$$ or $$$2$$$.Let's define the ternary XOR operation $$$\odot$$$ of two ternary numbers $$$a$$$ and $$$b$$$ (both of length $$$n$$$) as a number $$$c = a \odot b$$$ of length $$$n$$$, where $$$c_i = (a_i + b_i) \% 3$$$ (where $$$\%$$$ is modulo operation). In other words, add the corresponding digits and take the remainders of the sums when divided by $$$3$$$. For example, $$$10222 \odot 11021 = 21210$$$.Your task is to find such ternary numbers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^4$$$) — the length of $$$x$$$. The second line of the test case contains ternary number $$$x$$$ consisting of $$$n$$$ digits $$$0, 1$$$ or $$$2$$$. It is guaranteed that the first digit of $$$x$$$ is $$$2$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^4$$$ ($$$\sum n \le 5 \cdot 10^4$$$).

For each test case, print the answer — two ternary integers $$$a$$$ and $$$b$$$ both of length $$$n$$$ and both without leading zeros such that $$$a \odot b = x$$$ and $$$max(a, b)$$$ is the minimum possible. If there are several answers, you can print any.


The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? Nobody yet knows an algorithm that finds a solution to this problem in polynomial time of the size of the graph. However, as with many other NP-complete problems, the clique problem is easier if you consider a specific type of a graph.Consider n distinct points on a line. Let the i-th point have the coordinate xi and weight wi. Let's form graph G, whose vertices are these points and edges connect exactly the pairs of points (i, j), such that the distance between them is not less than the sum of their weights, or more formally: |xi - xj| ≥ wi + wj.Find the size of the maximum clique in such graph.

The first line contains the integer n (1 ≤ n ≤ 200 000) — the number of points. Each of the next n lines contains two numbers xi, wi (0 ≤ xi ≤ 109, 1 ≤ wi ≤ 109) — the coordinate and the weight of a point. All xi are different.

Print a single number — the number of vertexes in the maximum clique of the given graph.

NoteIf you happen to know how to solve this problem without using the specific properties of the graph formulated in the problem statement, then you are able to get a prize of one million dollars!The picture for the sample test.

<?php

    $n = trim(fgets(STDIN));
    $segments = array();
    for ($i = 0; $i < $n; $i++) {
        list($center, $radius) = explode(" ", trim(fgets(STDIN)));
        $segments[$i] = new stdClass();
        $segments[$i] -> left = $center - $radius;
        $segments[$i] -> right = $center + $radius;
    }

    usort($segments, function($seg1, $seg2) { return $seg1 -> right > $seg2 -> right; });

    $last = -2000000111;
    $ans = 0;
    for ($i = 0; $i <$n; $i++) {
        if ($segments[$i] -> left >= $last) {
            $ans++;
            $last = $segments[$i] -> right;
        }
    }

    echo $ans;

<?php

    $n = trim(fgets(STDIN));
    $segments = array();
    for ($i = 0; $i < $n; $i++) {
        list($center, $radius) = explode(" ", trim(fgets(STDIN)));
        $segments[$i] = (object) array('left' => $center - $radius, 'right' => $center + $radius);
    }

    usort($segments, function($seg1, $seg2) { return $seg1 -> right > $seg2 -> right; });

    $last = -2000000111;
    $ans = 0;
    for ($i = 0; $i <$n; $i++) {
        if ($segments[$i] -> left >= $last) {
            $ans++;
            $last = $segments[$i] -> right;
        }
    }

    echo $ans;

<?php

    class Segment {
        public $left, $right;

        public function __construct() {}

        public function setLeft($left) {
            $this -> left = $left;
        }

        public function setRight($right) {
            $this -> right = $right;
        }
    }

    function cmp($seg1, $seg2) {
        return $seg1 -> right - $seg2 -> right;
    }

    $n = trim(fgets(STDIN));
    $segments = array();
    for ($i = 0; $i < $n; $i++) {
        list($center, $radius) = explode(" ", trim(fgets(STDIN)));
        $segments[$i] = new Segment();
        $segments[$i] -> setLeft($center - $radius);
        $segments[$i] -> setRight($center + $radius);
    }

    usort($segments, "cmp");

    $last = -2000000111;
    $ans = 0;
    for ($i = 0; $i <$n; $i++) {
        if ($segments[$i] -> left >= $last) {
            $ans++;
            $last = $segments[$i] -> right;
        }
    }

    echo $ans;

<?php

    class Segment {
        public $left, $right;

        public function __construct($left, $right) {
            $this -> left = $left;
            $this -> right = $right;
        }
    }

    function cmp($seg1, $seg2) {
        return $seg1 -> right - $seg2 -> right;
    }

    $n = trim(fgets(STDIN));
    $segments = array();
    for ($i = 0; $i < $n; $i++) {
        list($center, $radius) = explode(" ", trim(fgets(STDIN)));
        $segments[$i] = new Segment($center - $radius, $center + $radius);
    }

    usort($segments, "cmp");

    $last = -2000000111;
    $ans = 0;
    for ($i = 0; $i <$n; $i++) {
        if ($segments[$i] -> left >= $last) {
            $ans++;
            $last = $segments[$i] -> right;
        }
    }

    echo $ans;


There are $$$n$$$ kids, numbered from $$$1$$$ to $$$n$$$, dancing in a circle around the Christmas tree. Let's enumerate them in a clockwise direction as $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ (all these numbers are from $$$1$$$ to $$$n$$$ and are distinct, so $$$p$$$ is a permutation). Let the next kid for a kid $$$p_i$$$ be kid $$$p_{i + 1}$$$ if $$$i < n$$$ and $$$p_1$$$ otherwise. After the dance, each kid remembered two kids: the next kid (let's call him $$$x$$$) and the next kid for $$$x$$$. Each kid told you which kids he/she remembered: the kid $$$i$$$ remembered kids $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$. However, the order of $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ can differ from their order in the circle.    Example: 5 kids in a circle, $$$p=[3, 2, 4, 1, 5]$$$ (or any cyclic shift). The information kids remembered is: $$$a_{1,1}=3$$$, $$$a_{1,2}=5$$$; $$$a_{2,1}=1$$$, $$$a_{2,2}=4$$$; $$$a_{3,1}=2$$$, $$$a_{3,2}=4$$$; $$$a_{4,1}=1$$$, $$$a_{4,2}=5$$$; $$$a_{5,1}=2$$$, $$$a_{5,2}=3$$$. You have to restore the order of the kids in the circle using this information. If there are several answers, you may print any. It is guaranteed that at least one solution exists.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$) — the number of the kids. The next $$$n$$$ lines contain $$$2$$$ integers each. The $$$i$$$-th line contains two integers $$$a_{i, 1}$$$ and $$$a_{i, 2}$$$ ($$$1 \le a_{i, 1}, a_{i, 2} \le n, a_{i, 1} \ne a_{i, 2}$$$) — the kids the $$$i$$$-th kid remembered, given in arbitrary order.

Print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ — permutation of integers from $$$1$$$ to $$$n$$$, which corresponds to the order of kids in the circle. If there are several answers, you may print any (for example, it doesn't matter which kid is the first in the circle). It is guaranteed that at least one solution exists.


After reaching your destination, you want to build a new colony on the new planet. Since this planet has many mountains and the colony must be built on a flat surface you decided to flatten the mountains using boulders (you are still dreaming so this makes sense to you).  You are given an array $$$h_1, h_2, \dots, h_n$$$, where $$$h_i$$$ is the height of the $$$i$$$-th mountain, and $$$k$$$ — the number of boulders you have.You will start throwing boulders from the top of the first mountain one by one and they will roll as follows (let's assume that the height of the current mountain is $$$h_i$$$):   if $$$h_i \ge h_{i + 1}$$$, the boulder will roll to the next mountain;  if $$$h_i < h_{i + 1}$$$, the boulder will stop rolling and increase the mountain height by $$$1$$$ ($$$h_i = h_i + 1$$$);  if the boulder reaches the last mountain it will fall to the waste collection system and disappear. You want to find the position of the $$$k$$$-th boulder or determine that it will fall into the waste collection system.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line in each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$; $$$1 \le k \le 10^9$$$) — the number of mountains and the number of boulders. The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ ($$$1 \le h_i \le 100$$$) — the height of the mountains. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case, print $$$-1$$$ if the $$$k$$$-th boulder will fall into the collection system. Otherwise, print the position of the $$$k$$$-th boulder.

NoteLet's simulate the first case:  The first boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,2,2,3]$$$.  The second boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ the boulder rolls to $$$i = 2$$$; since $$$h_2 \ge h_3$$$ the boulder rolls to $$$i = 3$$$ and stops there because $$$h_3 < h_4$$$.  The new heights are $$$[4,2,3,3]$$$.  The third boulder starts at $$$i = 1$$$; since $$$h_1 \ge h_2$$$ it rolls to $$$i = 2$$$ and stops there because $$$h_2 < h_3$$$.  The new heights are $$$[4,3,3,3]$$$. The positions where each boulder stopped are the following: $$$[2,3,2]$$$.In the second case, all $$$7$$$ boulders will stop right at the first mountain rising its height from $$$1$$$ to $$$8$$$.The third case is similar to the first one but now you'll throw $$$5$$$ boulders. The first three will roll in the same way as in the first test case. After that, mountain heights will be equal to $$$[4, 3, 3, 3]$$$, that's why the other two boulders will fall into the collection system.In the fourth case, the first and only boulders will fall straight into the collection system.

<?php

$times = (int) trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $ki[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $hi[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
}
for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $k = &$ki[$idx];
    $h = &$hi[$idx];
    for ($i = 0; $i < $k; ++$i) {
        for ($j = 0; $j < $n - 1; ++$j) {
            if ($h[$j] < $h[$j + 1]) {
                ++$h[$j];
                $pos = $j + 1;
                continue 2;
            }
        }
        echo -1 .PHP_EOL;
        continue 2;
    }
    echo $pos.PHP_EOL;
}

<?php
$t = trim(fgets(STDIN));
for ($o = 0; $o < $t; $o++) {
  list($n, $k) = explode(" ", trim(fgets(STDIN)));
  $h = explode(" ", trim(fgets(STDIN)));
  $wasted = false;
  for ($i = 0; $i < $k; $i++) {
    for ($j = 0; $j < $n; $j++) {
      if ($j === $n - 1) {
        $wasted = true;
        break;
      }
      if ($h[$j] < $h[$j + 1]) {
        if ($i === $k - 1) echo ($j + 1) . "\n";
        else $h[$j] += 1;
        break;
      }
    }
    if ($wasted) {
      echo (-1) . "\n";
      break;
    }
  }
}

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $n; $i++) {
    list($x,$y) = explode(' ', trim(fgets(STDIN)));
    $aList = explode(' ', trim(fgets(STDIN)));
    $bFlag = false;
    $iPosition = 0;
    while ($y < 0 || !$bFlag) {
        if ($y == 0) {
            break;
        }
        $k = b($aList);
        if ($k >= 0) {
            $aList[$k] = $aList[$k] + 1;
            $iPosition = $k;
            $y--;
        } else {
            $bFlag = true;
        }
    }
    if ($bFlag) {
        echo "-1\n";
    } else {
        echo ($iPosition + 1)."\n";
    }
}

function b ($aList, $j = 0) {
    for ($i = $j; $i < count($aList) - 1; $i++) {
        if ($aList[$i] < $aList[$i+1]) {
            return $i;
        }
    }
    return -1;
}

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    list($n, $k1) = IO::arr();
    $h = IO::arr();
    $res = -1;
    $last = 0;
    for($i = 1; $i <= $k1; $i++) {
        for($k = 0; $k < count($h); $k++) {
            $b = false;
            if(isset($h[$k+1])) {
                if((int)$h[$k] < (int)$h[$k+1]) {
                    $h[$k] += 1;
                    $b = true;
                    $last = $k+1;
                    break;
                }
            }
        }
        if(!$b) {
            break;
        }
    }
    if($b) {
        IO::line($last);
    } else {
        IO::line($res);
    }

}

<?php

$times = (int) trim(fgets(STDIN));
for ($idx = 0; $idx < $times; ++$idx) {
    list($ni[], $ki[]) = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $hi[] = array_map('intval', explode(' ', trim(fgets(STDIN))));
}
for ($idx = 0; $idx < $times; ++$idx) {
    $n = &$ni[$idx];
    $k = &$ki[$idx];
    $h = &$hi[$idx];
    for ($i = 0; $i < $n - 1; ++$i) {
        if ($h[$i + 1] > $h[$i]) {
            for ($j = $i; $j >= 0; --$j) {
                if ($h[$i + 1] > $h[$j]) {
                    $k -= $h[$i + 1] - $h[$j];
                    $h[$j] = $h[$i + 1];
                    if ($k <= 0) {
                        echo ($j+1).PHP_EOL;
                        continue 3;
                    }
                } else {
                    break;
                }
            }
        }
    }
    echo -1 .PHP_EOL;
}

<?php
$t = trim(fgets(STDIN));
for ($o = 0; $o < $t; $o++) {
  list($n, $k) = explode(" ", trim(fgets(STDIN)));
  $h = explode(" ", trim(fgets(STDIN)));
  $wasted = false;
  for ($i = 0; $i < $k; $i++) {
    for ($j = 0; $j < $n; $j++) {
      if ($j === $n - 1) {
        $wasted = true;
        break;
      }
      if ($h[$j] < $h[$j + 1]) {
        if ($i === $k - 1) echo $j + 1;
        else $h[$j] += 1;
        break;
      }
    }
    if ($wasted) {
      echo -1;
      break;
    }
  }
}


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.


Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.

<?php
define('LOCAL_ENV', false);
if (LOCAL_ENV) {
    error_reporting(E_ALL);
    $stdin = fopen('401bin.txt', 'r+');
} else {
    error_reporting(0);
    $stdin = STDIN;
}
list($x, $k) = explode(' ', trim(fgets($stdin)));
$a = array();
for ($i = 0; $i < $k; $i++) {
    $s = trim(fgets($stdin));
    $arr = explode(' ', $s);
    $a[$i] = array((int) $arr[1], isset($arr[2]) ? (int) $arr[2] : (int) $arr[1]);
}

usort($a, function($x, $y) {
    if ($x[0] == $y[0]) {
        return 0;
    }
    return $x[0] < $y[0] ? -1 : 1;
});

$min = 0; $max = 0;
array_unshift($a, array(0, 0));
array_push($a, array($x, $x));
for ($i = 1; $i < count($a); $i++) {
    $r = $a[$i][0] - $a[$i-1][1] - 1;
    if ($r > 0) {
        $max += $r;
        $min += floor($r * 0.5) + $r % 2;
    }
}

echo $min . ' ' . $max;


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

<?php
$a = trim(fgets(STDIN));
$b = range(1, $a);
$c = array_slice($b, 0, -1);
array_unshift($c, $a);
print implode(" ", $c);
?>


Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.

The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.  Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.

Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.

NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.


In a building where Polycarp lives there are equal number of flats on each floor. Unfortunately, Polycarp don't remember how many flats are on each floor, but he remembers that the flats are numbered from 1 from lower to upper floors. That is, the first several flats are on the first floor, the next several flats are on the second and so on. Polycarp don't remember the total number of flats in the building, so you can consider the building to be infinitely high (i.e. there are infinitely many floors). Note that the floors are numbered from 1.Polycarp remembers on which floors several flats are located. It is guaranteed that this information is not self-contradictory. It means that there exists a building with equal number of flats on each floor so that the flats from Polycarp's memory have the floors Polycarp remembers.Given this information, is it possible to restore the exact floor for flat n?

The first line contains two integers n and m (1 ≤ n ≤ 100, 0 ≤ m ≤ 100), where n is the number of the flat you need to restore floor for, and m is the number of flats in Polycarp's memory. m lines follow, describing the Polycarp's memory: each of these lines contains a pair of integers ki, fi (1 ≤ ki ≤ 100, 1 ≤ fi ≤ 100), which means that the flat ki is on the fi-th floor. All values ki are distinct. It is guaranteed that the given information is not self-contradictory.

Print the number of the floor in which the n-th flat is located, if it is possible to determine it in a unique way. Print -1 if it is not possible to uniquely restore this floor.

NoteIn the first example the 6-th flat is on the 2-nd floor, while the 7-th flat is on the 3-rd, so, the 6-th flat is the last on its floor and there are 3 flats on each floor. Thus, the 10-th flat is on the 4-th floor.In the second example there can be 3 or 4 flats on each floor, so we can't restore the floor for the 8-th flat.


You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands:  for $$$n$$$ — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every "for $$$n$$$" is matched with "end", thus the function is guaranteed to be valid. "for $$$n$$$" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some "add" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

The first line contains a single integer $$$l$$$ ($$$1 \le l \le 10^5$$$) — the number of lines in the function. Each of the next $$$l$$$ lines contains a single command of one of three types:   for $$$n$$$ ($$$1 \le n \le 100$$$) — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$.

If overflow happened during execution of $$$f(0)$$$, then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

9
add
for 43
end
for 10
for 15
add
end
add
end

11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end

NoteIn the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for $$$n$$$" can be immediately followed by "end" and that "add" can be outside of any for loops.In the second example there are no commands "add", thus the returning value is 0.In the third example "add" command is executed too many times, which causes $$$x$$$ to go over $$$2^{32}-1$$$.

<?php
# 1175B
$stdin = STDIN;
$t = (int)trim(fgets($stdin));
$limit = (2**32);

$ind = 0;
$values = [];
$ops = [];
while ($t-- > 0) {
    $cmd = trim(fgets($stdin));
    $op = $cmd[0];
    switch($op) {
        case 'a':
            $values[] = 1;
            $ops[] = true;
            break;
        case 'f':
            $values[] = substr($cmd, 4);
            $ops[] = false;
            break;
        case 'e':
            $num = 0;
            while (array_pop($ops) === true) {
                $num += array_pop($values);
            }
            $num *= array_pop($values);
            $values[] = $num;
            $ops[] = true;
            break;
    }
}
$result = array_sum($values);
echo $limit > $result ? $result : 'OVERFLOW!!!';

<?php
# 1175B
$stdin = STDIN;
$t = (int)trim(fgets($stdin));
$limit = 2**32 - 1;
$ind = 0;
$values = [];
$ops = [];
while ($t-- > 0) {
    $cmd = trim(fgets($stdin));
    $op = $cmd[0];
    switch($op) {
        case 'a':
            $values[] = 1;
            $ops[] = true;
            break;
        case 'f':
            $values[] = substr($cmd, 4);
            $ops[] = false;
            break;
        case 'e':
            $num = 0;
            while (array_pop($ops) === true) {
                $num += array_pop($values);
            }
            $num *= array_pop($values);
            $values[] = $num;
            $ops[] = true;
            break;
    }
}
$result = array_sum($values);
echo $limit > $result ? $result : 'OVERFLOW!!!';


Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Print a single number — the maximum number of not disappointed people in the queue.

NoteValue 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

<?php
	$n = trim(fgets(STDIN));
	$a = explode(' ', trim(fgets(STDIN)));
	$sum = $c = 0;
	sort($a);
	for($i = 0; $i < $n; $i++)
		if($sum <= $a[$i])
		{
			$c++;
			$sum += $a[$i];
		}
	echo $c;
?>


Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output the number of pieces of sausage that lay on the crust.

NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

<?php

$handle = fopen ("php://stdin", "r");
fscanf($handle, "%d %d", $radius, $k);
echo d($handle, (int)$radius, (int)$k);

function d($handle, $radius, $k){
    $j = (int)fgets($handle);
    $count = 0;
    for($i = 1; $i <= $j; $i++){
        fscanf($handle, "%d %d %d", $x, $y, $r);
        $min = sqrt(pow($x, 2) + pow($y, 2)) - $r;
        $max = sqrt(pow($x, 2) + pow($y, 2)) + $r;
        if($min >= ($radius - $k) & $max <= $radius){
            $count++;
        }
    }
    return $count;
}

<?php

$handle = fopen ("php://stdin", "r");
fscanf($handle, "%d %d", $radius, $k);
if($radius === 0 || $k === 0){
    echo 0;
    return;
}
$j = (int)fgets($handle);
$count = 0;
for($i = 1; $i <= $j; $i++){
    fscanf($handle, "%d %d %d", $x, $y, $r);
    $min = sqrt(pow($x, 2) + pow($y, 2)) - $r;
    $max = sqrt(pow($x, 2) + pow($y, 2)) + $r;
    if($min > $radius/2 & $max < ($radius/2 + $k)){
        $count++;
    }
}
echo $count;

<?php
//$handle = fopen ("php://stdin", "r");
//scanf($handle, "%d %d %d", $a, $b, $k);
//fgets($f);
//$a = array_map('intval', $a);
//$handle = fopen ("D:\input.txt", "r");

$handle = fopen ("php://stdin", "r");
fscanf($handle, "%d %d", $radius, $k);
if($k > 0){
    echo d($handle, $radius, $k);
}else{
    echo 0;
}

function d($handle, $radius, $k){
    $j = (int)fgets($handle);
    $count = 0;
    for($i = 1; $i <= $j; $i++){
        fscanf($handle, "%d %d %d", $x, $y, $r);
        $min = sqrt(pow($x, 2) + pow($y, 2)) - $r;
        $max = sqrt(pow($x, 2) + pow($y, 2)) + $r;
        if($min >= ($radius - $k) & $max <= $radius){
            $count++;
        }
    }
    return $count;
}

<?php

$handle = fopen ("php://stdin", "r");
fscanf($handle, "%d %d", $radius, $k);
$j = (int)fgets($handle);
$count = 0;
for($i = 1; $i <= $j; $i++){
    fscanf($handle, "%d %d %d", $x, $y, $r);
    $min = sqrt(pow($x, 2) + pow($y, 2)) - $r;
    $max = sqrt(pow($x, 2) + pow($y, 2)) + $r;
    if($min >= $radius/2 && $max <= ($radius/2 + $k)){
        $count++;
    }
}
echo $count;

<?php
$handle = fopen ("php://stdin", "r");
fscanf($handle, "%d %d", $radius, $k);
$j = (int)fgets($handle);
$count = 0;
for($i = 1; $i <= $j; $i++){
    fscanf($handle, "%d %d %d", $x, $y, $r);
    $min = sqrt(pow($x, 2) + pow($y, 2)) - $r;
    $max = sqrt(pow($x, 2) + pow($y, 2)) + $r;
    if($min > $radius/2 && $max < ($radius/2 + $k)){
        $count++;
    }
}
echo $count;


When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.Find the length of the longest almost constant range.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Print a single number — the maximum length of an almost constant range of the given sequence.

NoteIn the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.In the second sample, there are three almost constant ranges of length 4: [1, 4], [6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].


A binary string is a string consisting only of the characters 0 and 1. You are given a binary string $$$s$$$.For some non-empty substring$$$^\dagger$$$ $$$t$$$ of string $$$s$$$ containing $$$x$$$ characters 0 and $$$y$$$ characters 1, define its cost as:  $$$x \cdot y$$$, if $$$x > 0$$$ and $$$y > 0$$$;  $$$x^2$$$, if $$$x > 0$$$ and $$$y = 0$$$;  $$$y^2$$$, if $$$x = 0$$$ and $$$y > 0$$$. Given a binary string $$$s$$$ of length $$$n$$$, find the maximum cost across all its non-empty substrings.$$$^\dagger$$$ A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the maximum cost across all substrings.

NoteIn the first test case, we can take a substring $$$111$$$. It contains $$$3$$$ characters 1 and $$$0$$$ characters 0. So $$$a = 3$$$, $$$b = 0$$$ and its cost is $$$3^2 = 9$$$.In the second test case, we can take the whole string. It contains $$$4$$$ characters 1 and $$$3$$$ characters 0. So $$$a = 4$$$, $$$b = 3$$$ and its cost is $$$4 \cdot 3 = 12$$$.In the third test case, we can can take a substring $$$1111$$$ and its cost is $$$4^2 = 16$$$.In the fourth test case, we can take the whole string and cost is $$$4 \cdot 3 = 12$$$.In the fifth test case, we can take a substring $$$000$$$ and its cost is $$$3 \cdot 3 = 9$$$.In the sixth test case, we can only take the substring $$$0$$$ and its cost is $$$1 \cdot 1 = 1$$$.

<?php
//[$n,$m] = array_map('intval', explode(' ', trim(fgets(STDIN))));
[$x] = 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<$x;$i++){
    [$n] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    [$s] = explode(' ', trim(fgets(STDIN)));
    $o = 0;
    $z = 0;
    for($j=0;$j<$n;$j++){
        if($s[$j]=="0") $z++;
        else $o++;
    }
    $sum = $z * $o;

    $t = explode("0", $s);
    $cnt = [];
    for($j=0;$j<count($t);$j++){
        $cnt[] = strlen($t[$j]);
    }
    $cnt = max($cnt);

    $t = explode("1", $s);
    $cnt2 = [];
    for($j=0;$j<count($t);$j++){
        $cnt2[] = strlen($t[$j]);
    }
    $cnt2 = max($cnt2);
    $ans[] = max($sum, $cnt*$cnt, $cnt2*$cnt2);
}

echo implode(PHP_EOL, $ans);


You are given two arrays $$$a$$$ and $$$b$$$, each consisting of $$$n$$$ positive integers, and an integer $$$x$$$. Please determine if one can rearrange the elements of $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$).

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. $$$t$$$ blocks follow, each describing an individual test case. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 50$$$; $$$1 \leq x \leq 1000$$$) — the length of arrays $$$a$$$ and $$$b$$$, and the parameter $$$x$$$, described in the problem statement. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_1 \le a_2 \le \dots \le a_n \leq x$$$) — the elements of array $$$a$$$ in non-descending order. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_1 \le b_2 \le \dots \le b_n \leq x$$$) — the elements of array $$$b$$$ in non-descending order. Test cases are separated by a blank line.

For each test case print Yes if one can rearrange the corresponding array $$$b$$$ so that $$$a_i + b_i \leq x$$$ holds for each $$$i$$$ ($$$1 \le i \le n$$$) or No otherwise. Each character can be printed in any case.

NoteIn the first test case, one can rearrange $$$b$$$ so it'll look like $$$[1, 2, 1]$$$. In this case, $$$1 + 1 \leq 4$$$; $$$2 + 2 \leq 4$$$; $$$3 + 1 \leq 4$$$.In the second test case, one can set $$$b$$$ to $$$[5, 2]$$$, then $$$1 + 5 \leq 6$$$; $$$4 + 2 \leq 6$$$.In the third test case, no matter how one shuffles array $$$b$$$, $$$a_4 + b_4 = 4 + b_4 > 4$$$.In the fourth test case, there is only one rearrangement of array $$$b$$$ and it doesn't satisfy the condition since $$$5 + 5 > 5$$$.

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t = trim(fgets($handle));
for ($i = 0; $i < $t; $i++) {
    $x = trim(fgets($handle));
    $x = explode(' ', $x);
    $a = trim(fgets($handle));
    $a = explode(' ', $a);
    $b = trim(fgets($handle));
    $b = explode(' ', $b);
    $b = array_reverse($b);
    $res = 1;
    for ($j = 0; $j < $x[0]; $j++) {
        if($a[$j] + $b[$j] > $x[1])
        {
            $res = 0;
            break;
        }
    }
    if ($res > 0) {
        echo "Yes" . "\n";
    } else {
        echo "No" . "\n";
    }
    $x = trim(fgets($handle));
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t = trim(fgets($handle));
for ($i = 0; $i < $t; $i++) {
    $x = trim(fgets($handle));
    $x = explode(' ', $x);
    $a = trim(fgets($handle));
    $a = explode(' ', $a);
    $b = trim(fgets($handle));
    $b = explode(' ', $b);
    $maxa = 0;
    $maxb = 0;
    $minb = 1001;
    $mina = 1001;
    for ($j = 0; $j < $x[0]; $j++) {
        if ($maxa < $a[$j]) {
            $maxa = $a[$j];
        }
        if ($maxb < $b[$j]) {
            $maxb = $b[$j];
        }

        if ($mina > $a[$j]) {
            $mina = $a[$j];
        }

        if ($minb > $b[$j]) {
            $minb = $b[$j];
        }
    }
    if ($maxa + $minb <= $x[1] || $maxb + $mina <= $x[1]) {
        echo "Yes" . "\n";
    } else {
        echo "No" . "\n";
    }
    $x = trim(fgets($handle));
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $maxa = 0;
    $minb = 1001;
    for ($j=0;$j<$x[0];$j++)
    {
        if($maxa < $a[$j])
        {
            $maxa= $a[$j];
        }

        if($minb > $b[$j])
        {
            $minb= $b[$j];
        }
    }
    if($maxa + $minb <= $x[1])
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
    $x=trim(fgets($handle));
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $counta = 0;
    $countb = 0;
    for ($j=0;$j<$x[0];$j++)
    {
        $counta= $counta + $a[$j];
        $countb= $countb + $b[$j];
    }
    var_dump($counta);
    var_dump($countb);
    if($x[1] < max($countb,$counta) && $x[1] >= min($countb,$counta))
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
        $x=trim(fgets($handle));
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $counta = 0;
    $countb = 0;
    for ($j=0;$j<$x[0];$j++)
    {
        $counta= $counta + $a[$j];
        $countb= $countb + $b[$j];
    }
    if($x[1] < max($countb,$counta) && $x[1] > min($countb,$counta))
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $res = array_diff($b,$a);
    if(sizeof($res) > 0)
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $counta = 0;
    $countb = 0;
    for ($j=0;$j<$x[0];$j++)
    {
        $counta= $counta + $a[$j];
        $countb= $countb + $b[$j];
    }
    if($x[1] < max($countb,$counta) && $x[1] >= min($countb,$counta))
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t = trim(fgets($handle));
for ($i = 0; $i < $t; $i++) {
    $x = trim(fgets($handle));
    $x = explode(' ', $x);
    $a = trim(fgets($handle));
    $a = explode(' ', $a);
    $b = trim(fgets($handle));
    $b = explode(' ', $b);
    array_reverse($b);
    $res = 1;
    for ($j = 0; $j < $x[0]; $j++) {
        if($a[$j] + $b[$j] > $x[1])
        {
            $res = 0;
            break;
        }
    }
    if ($res > 0) {
        echo "Yes" . "\n";
    } else {
        echo "No" . "\n";
    }
    $x = trim(fgets($handle));
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $counta = 0;
    $countb = 0;
    for ($j=0;$j<$x[0];$j++)
    {
        $counta= $counta + $a[$j];
        $countb= $countb + $b[$j];
    }
    if($x[1] < max($countb,$counta) && $x[1] >= min($countb,$counta))
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
        $x=trim(fgets($handle));
}

<?php
$server = "php://stdin";
$handle = fopen($server, "r");
$t= trim(fgets($handle));
for($i=0;$i<$t;$i++)
{
    $x=trim(fgets($handle));
    $x=explode(' ',$x);
    $a=trim(fgets($handle));
    $a=explode(' ',$a);
    $b=trim(fgets($handle));
    $b=explode(' ',$b);
    $counta = 0;
    $countb = 0;
    for ($j=0;$j<$x[0];$j++)
    {
        $counta= $counta + $a[$j];
        $countb= $countb + $b[$j];
    }
    if($x[1] < max($countb,$countb) && $x[1] > min($countb,$counta))
    {
        echo "Yes"."\n";
    }else {
        echo "No"."\n";
    }
}


Let's denote a $$$k$$$-step ladder as the following structure: exactly $$$k + 2$$$ wooden planks, of which  two planks of length at least $$$k+1$$$ — the base of the ladder;  $$$k$$$ planks of length at least $$$1$$$ — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal.For example, ladders $$$1$$$ and $$$3$$$ are correct $$$2$$$-step ladders and ladder $$$2$$$ is a correct $$$1$$$-step ladder. On the first picture the lengths of planks are $$$[3, 3]$$$ for the base and $$$[1]$$$ for the step. On the second picture lengths are $$$[3, 3]$$$ for the base and $$$[2]$$$ for the step. On the third picture lengths are $$$[3, 4]$$$ for the base and $$$[2, 3]$$$ for the steps.   You have $$$n$$$ planks. The length of the $$$i$$$-th planks is $$$a_i$$$. You don't have a saw, so you can't cut the planks you have. Though you have a hammer and nails, so you can assemble the improvised "ladder" from the planks.The question is: what is the maximum number $$$k$$$ such that you can choose some subset of the given planks and assemble a $$$k$$$-step ladder using them?

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. The queries are independent. Each query consists of two lines. The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of planks you have. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^5$$$) — the lengths of the corresponding planks. It's guaranteed that the total number of planks from all queries doesn't exceed $$$10^5$$$.

Print $$$T$$$ integers — one per query. The $$$i$$$-th integer is the maximum number $$$k$$$, such that you can choose some subset of the planks given in the $$$i$$$-th query and assemble a $$$k$$$-step ladder using them. Print $$$0$$$ if you can't make even $$$1$$$-step ladder from the given set of planks.

NoteExamples for the queries $$$1-3$$$ are shown at the image in the legend section.The Russian meme to express the quality of the ladders:

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     $c = explode(" ", trim(fgets(STDIN)));
     rsort($c);
     $d = array_slice($c, 0, 2);
     $e = array_slice($c, 2);
     $f = min($d) - 1;
     print min($f, count($e)) . "\n";
}
?>

<?php
list($c) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $c; $i++){
    list($d) = explode(' ', trim(fgets(STDIN)));
    $aArray = explode(' ', trim(fgets(STDIN)));
    arsort($aArray);
    $iCount = 0;
    $aTest = [];
    foreach ($aArray as $sK => $sV){
        $aTest[] = $sV;
    }
    $iTotal = $aTest[1] - 1;
    if($d < 3){
        echo "0"."\n";
    } elseif($iTotal <= ($d - 2)){
        echo $iTotal."\n";
    } else if ($iTotal > ($d - 2)){
        echo ($d-2)."\n";
    }

}

<?php
#1197A
$start = microtime(1);
$t = trim(fgets(STDIN));
while ($t--) {
    $n = trim(fgets(STDIN));
    $a = trim(fgets(STDIN));
    if ($n < 3) {
        fwrite(STDOUT, 0);
    } else {
        $a = explode(' ', $a);
        sort($a);
        $l = array_pop($a);
        $r = array_pop($a);
        fwrite(STDOUT, min($l - 1, $r - 1, count($a)));
    }
    fwrite(STDOUT,  PHP_EOL);
}
#echo PHP_EOL . (microtime(1) - $start);

<?php
$t = trim(fgets(STDIN));
while ($t--) {
    $n = trim(fgets(STDIN));
    $a = explode(' ', trim(fgets(STDIN)));
    rsort($a);
    fwrite(STDOUT, min($a[0] - 1, $a[1] - 1, count($a) - 2) . PHP_EOL);
}

<?php
$t = trim(fgets(STDIN));
while ($t--) {
    $n = trim(fgets(STDIN));
    $a = explode(' ', trim(fgets(STDIN)));
    sort($a);
    $l = array_pop($a);
    $r = array_pop($a);
    fwrite(STDOUT, min($l - 1, $r - 1, count($a)) . PHP_EOL);
}

<?php
    $n = trim(fgets(STDIN));
    for($i = 1; $i <= $n; $i++){
         $c = trim(fgets(STDIN));
         $a = explode(" ", trim(fgets(STDIN)));
         $count = 0;
         $arr = array();
         arsort($a);
         foreach($a as $v){
             $count+=1;
             if($count == 2){
                 $k = $v-1;
             }
         }
         if($c < 3){
             echo "0\n";
         } else if($k <= ($c - 2)){
             echo $k."\n";
         } else if ($k > ($c - 2)){
             echo ($c-2)."\n";
         }
    }

 ?>

<?php
list($c) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $c; $i++){
    list($d) = explode(' ', trim(fgets(STDIN)));
    $aArray = explode(' ', trim(fgets(STDIN)));
    $iMax1= max($aArray);
    $iMaxIndex = array_keys($aArray, max($aArray));
    unset($aArray[$iMaxIndex[0]]);
    $iMax2 = max($aArray);
    $iMaxIndex = array_keys($aArray, max($aArray));
    unset($aArray[$iMaxIndex[0]]);

    $iCount = 0;
    foreach ($aArray as $sK => $sV){
        if($sV + 1 <= $iMax1 && $sV + 1 <= $iMax2){
            $iCount++;
        }
    }
    if($iCount > $d - 2){
        echo ($d - 2) . "\n";
    } else {
        echo $iCount."\n";
    }
}

<?php
list($c) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $c; $i++){
    list($d) = explode(' ', trim(fgets(STDIN)));
    $aArray = explode(' ', trim(fgets(STDIN)));
    $iMax1= max($aArray);
    $iMaxIndex = array_keys($aArray, max($aArray));
    unset($aArray[$iMaxIndex[0]]);
    $iMax2 = max($aArray);
    $iMaxIndex = array_keys($aArray, max($aArray));
    unset($aArray[$iMaxIndex[0]]);

    $iCount = 0;
    foreach ($aArray as $sK => $sV){
        if($sV + 1 <= $iMax1 && $sV + 1 <= $iMax2){
            $iCount++;
        }
    }
    if($iCount >= $d - 2){
        echo ($d - 2) . "\n";
    } else {
        echo $iCount."\n";
    }
}

<?php
list($c) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $c; $i++){
    list($d) = explode(' ', trim(fgets(STDIN)));
    $aArray = explode(' ', trim(fgets(STDIN)));
    $iMax1= max($aArray);
    $iMaxIndex = array_keys($aArray, max($aArray));
    unset($aArray[$iMaxIndex[0]]);
    $iMax2 = max($aArray);
    $iMaxIndex = array_keys($aArray, max($aArray));
    unset($aArray[$iMaxIndex[0]]);
    $iCount = 0;
    foreach ($aArray as $sK => $sV){
        if($sV < $iMax1 && $sV < $iMax2){
            $iCount++;
        }
    }
    if($iCount > $d - 2){
        echo ($d - 2) . "\n";
    } else {
        echo $iCount."\n";
    }
}

<?php
list($c) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $c; $i++){
    list($d) = explode(' ', trim(fgets(STDIN)));
    $aArray = explode(' ', trim(fgets(STDIN)));
    arsort($aArray);
    $iCount = 0;
    $aTest = [];
    foreach ($aArray as $sK => $sV){
        $aTest[] = $sV;
    }
    if(($aTest[0] >= ($d - 2)) && ($aTest[1] >= ($d - 2))){
        if($aTest[1] <= $d - 2){
            echo ($d - 2 - 1)."\n";
        } else {
            echo $d - 2 ."\n";
        }
    } else {
        echo "0"."\n";
    }

}

<?php
#1197A
$start = microtime(1);
$t = trim(fgets(STDIN));
while ($t--) {
    $n = trim(fgets(STDIN));
    if ($n < 3) {
        fwrite(STDOUT, 0);
    } else {
        $a = explode(' ', trim(fgets(STDIN)));
        sort($a);
        $l = array_pop($a);
        $r = array_pop($a);
        fwrite(STDOUT, min($l - 1, $r - 1, count($a)));
    }
    fwrite(STDOUT,  PHP_EOL);
}
#echo PHP_EOL . (microtime(1) - $start);


Valera is a lazy student. He has m clean bowls and k clean plates. Valera has made an eating plan for the next n days. As Valera is lazy, he will eat exactly one dish per day. At that, in order to eat a dish, he needs exactly one clean plate or bowl. We know that Valera can cook only two types of dishes. He can eat dishes of the first type from bowls and dishes of the second type from either bowls or plates. When Valera finishes eating, he leaves a dirty plate/bowl behind. His life philosophy doesn't let him eat from dirty kitchenware. So sometimes he needs to wash his plate/bowl before eating. Find the minimum number of times Valera will need to wash a plate/bowl, if he acts optimally.

The first line of the input contains three integers n, m, k (1 ≤ n, m, k ≤ 1000) — the number of the planned days, the number of clean bowls and the number of clean plates. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 2). If ai equals one, then on day i Valera will eat a first type dish. If ai equals two, then on day i Valera will eat a second type dish.

Print a single integer — the minimum number of times Valera will need to wash a plate/bowl.

NoteIn the first sample Valera will wash a bowl only on the third day, so the answer is one.In the second sample, Valera will have the first type of the dish during all four days, and since there are only three bowls, he will wash a bowl exactly once.In the third sample, Valera will have the second type of dish for all three days, and as they can be eaten from either a plate or a bowl, he will never need to wash a plate/bowl.

<?php

list($n, $m, $k) = explode(' ', getLine());

$n = (int)$n; // days
$m = (int)$m; // bowls
$k = (int)$k; // plates

$_m = $m;
$_k = $k;

$a = explode(' ', getLine());

$answer = 0;

for ($i = 0, $n = min($n, count($a)); $i < $n; $i ++) {
  if ($a[$i] == 1) {
    if ($m == 0) {
      $answer ++;
      $m = 1;
    }
    $m --;
  } else if ($a[$i] == 2) {
     if ($m == 0 && $k == 0) {
      $answer ++;
      $k = 1;
    }
    if ($k > 0) {
      $k --;
    } else if ($m > 0) {
      $m --;
    }
  }
}

print $answer;

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

<?php
$stdin = fopen('php://stdin', 'r');
$i = 1;
$wash_counter = 0;

while($i <= 2) {
    $line = trim(fgets($stdin));
    $temp_arr = explode(' ', $line);
    if($i == 1) {
        $n = $temp_arr[0];
        $m = $temp_arr[1];
        $k = $temp_arr[2];
    }
    if($i == 2) {
        $dish_arr = $temp_arr;
    }
    $i++;
}

fclose($stdin);
//echo $n."\n";
//echo $m."\n";
//echo $k."\n";

//print_r($dish_arr);
for($j=0;$j<$n;$j++) {
    switch($dish_arr[$j]) {
        case 1:
            if($m != 0) {
                $m--;
            }
            else {
                $wash_counter++;
            }
            break;
        case 2:
            if($k != 0) {
                $k--;
                break;
            }
            if($m != 0) {
                $m--;
                break;
            }

            $wash_counter++;
            break;
    }
}

echo $wash_counter."\n";
?>

<?php
list($n, $m, $k) = explode(" ", trim(fgets(STDIN)));
$a=explode(" ", trim(fgets(STDIN)));
$i=0;
$nofk=0;
$nofm=0;
while($n!==0){
if($a[$i]==1){
$nofm=$nofm+1;
              }else{
			  $nofk=$nofk+1;
			       }
$i++;
$n--;
              }

				 if($nofm>$m){
				 $s=$nofm-$m;
				 if($nofk>$k){
				 $j=$nofk-$k;
				 echo $j+$s;
				 }else{
				 echo $s ;
				 }
				 }else{
				 $s=$m-$nofm;
				 $mk=$s+$k;
				 if($nofk>$mk){
				 echo $nofk-$mk;
				 }else{
				 echo"0";
				 }
				 }

?>

<?php
$stdin = fopen('php://stdin', 'r');
$i = 1;
$wash_counter = 0;

while($i <= 2) {
    $line = trim(fgets($stdin));
    if($i == 1) {
        $n = $line[0];
        $m = $line[2];
        $k = $line[4];
    }
    if($i == 2) {
        $dishes = $line;
        $dish_arr = explode(' ', $dishes);
    }
    $i++;
}

fclose($stdin);
//echo $n."\n";
//echo $m."\n";
//echo $k."\n";

//print_r($dish_arr);
for($j=0;$j<$n;$j++) {
    switch($dish_arr[$j]) {
        case 1:
            if($m != 0) {
                $m--;
            }
            else {
                $wash_counter++;
            }
            break;
        case 2:
            if($k != 0) {
                $k--;
                break;
            }
            if($m != 0) {
                $m--;
                break;
            }

            $wash_counter++;
            break;
    }
}

echo $wash_counter."\n";
?>

<?php
$stdin = fopen('php://stdin', 'r');
$i = 1;
$wash_counter = 0;

while($i <= 2) {
    $line = trim(fgets($stdin));
    if($i == 1) {
        $n = $line[0];
        $m = $line[2];
        $k = $line[4];
    }
    if($i == 2) {
        $dishes = $line;
        $dish_arr = explode(' ', $dishes);
    }
    $i++;
}

fclose($stdin);
//echo $n."\n";
//echo $m."\n";
//echo $k."\n";

//print_r($dish_arr);
for($j=0;$j<$n;$j++) {
    switch($dish_arr[$j]) {
        case 1:
            if($m != 0) {
                $m--;
            }
            else {
                $wash_counter++;
            }
            break;
        case 2:
            if($m != 0) {
                $m--;
                break;
            }
            else if($k != 0) {
                $k--;
                break;
            }
            else if($m == 0 && $k == 0) {
                $wash_counter++;
            }
            break;
    }
}

echo $wash_counter."\n";
?>

<?php
$stdin = fopen('php://stdin', 'r');
$i = 1;
$wash_counter = 0;
$input_arr = array();

while($i <= 2) {
	$line = trim(fgets($stdin));
	if($i == 1) {
		$n = $line[0];
		$m = $line[2];
		$k = $line[4];
	}
	if($i == 2) {
		$dishes = $line;
		$dish_arr = explode(' ', $dishes);
	}
	$i++;
}

fclose($stdin);
//echo $n."\n";
//echo $m."\n";
//echo $k."\n";

//print_r($dish_arr);
for($j=0;$j<$n;$j++) {
	switch($dish_arr[$j]) {
		case 1:
			if($m != 0) {
				$m--;
			}
			else {
				$wash_counter++;
			}
			break;
		case 2:
			if($m != 0) {
				$m--;
				break;
			}
			else if($k != 0) {
				$k--;
				break;
			}
			else if($m == 0 && $k == 0) {
				$wash_counter++;
			}
			break;
	}
}

echo $wash_counter;

?>

<?php
$stdin = fopen('php://stdin', 'r');
$i = 1;
$wash_counter = 0;

while($i <= 2) {
    $line = trim(fgets($stdin));
    if($i == 1) {
        $n = $line[0];
        $m = $line[2];
        $k = $line[4];
    }
    if($i == 2) {
        $dishes = $line;
        $dish_arr = explode(' ', $dishes);
    }
    $i++;
}

fclose($stdin);
//echo $n."\n";
//echo $m."\n";
//echo $k."\n";

//print_r($dish_arr);
for($j=0;$j<$n;$j++) {
    switch($dish_arr[$j]) {
        case 1:
            if($m != 0) {
                $m--;
            }
            else {
                $wash_counter++;
            }
            break;
        case 2:
            if($m != 0) {
                $m--;
                break;
            }
            if($k != 0) {
                $k--;
                break;
            }

            $wash_counter++;
            break;
    }
}

echo $wash_counter."\n";
?>


Berland shop sells $$$n$$$ kinds of juices. Each juice has its price $$$c_i$$$. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.Petya knows that he needs all three types of vitamins to stay healthy. What is the minimum total price of juices that Petya has to buy to obtain all three vitamins? Petya obtains some vitamin if he buys at least one juice containing it and drinks it.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of juices. Each of the next $$$n$$$ lines contains an integer $$$c_i$$$ $$$(1 \le c_i \le 100\,000)$$$ and a string $$$s_i$$$ — the price of the $$$i$$$-th juice and the vitamins it contains. String $$$s_i$$$ contains from $$$1$$$ to $$$3$$$ characters, and the only possible characters are "A", "B" and "C". It is guaranteed that each letter appears no more than once in each string $$$s_i$$$. The order of letters in strings $$$s_i$$$ is arbitrary.

Print -1 if there is no way to obtain all three vitamins. Otherwise print the minimum total price of juices that Petya has to buy to obtain all three vitamins.

NoteIn the first example Petya buys the first, the second and the fourth juice. He spends $$$5 + 6 + 4 = 15$$$ and obtains all three vitamins. He can also buy just the third juice and obtain three vitamins, but its cost is $$$16$$$, which isn't optimal.In the second example Petya can't obtain all three vitamins, as no juice contains vitamin "C".

<?php

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

$n = (int)fgets($h);

$result = -1;

$map = [];

$vals = [
    'A' => 1,
    'B' => 2,
    'C' => 4,
];

$totalSum = array_sum($vals);

for ($i = 0; $i < $n; $i++) {

    fscanf($h, '%d %s', $price, $vits);

    $len = strlen($vits);

    $key = $vals[$vits[0]] + (isset($vits[1]) ? $vals[$vits[1]] : 0) + (isset($vits[2]) ? $vals[$vits[2]] : 0);

    if (!isset($map[$len])) {
        $map[$len] = [];
    }

    if (!isset($map[$len][$key]) || $map[$len][$key] > $price) {
        $map[$len][$key] = $price;
    }
}

$mins = [];

if (isset($map[1]) && count($map[1]) == 3) {
    $mins[] = array_sum($map[1]);
}

if (isset($map[3])) {
    $mins[] = min($map[3]);
}

if (isset($map[2])) {

    foreach ($map[2] as $key => $price) {

        if (isset($map[1]) && isset($map[1][$totalSum - $key])) {

            $mins[] = $price + $map[1][$totalSum - $key];
        }

        if ($key != 3 && isset($map[2][3])) {
            $mins[] = $price + $map[2][3];
        }

        if ($key != 6 && isset($map[2][6])) {
            $mins[] = $price + $map[2][6];
        }

        if ($key != 5 && isset($map[2][5])) {
            $mins[] = $price + $map[2][5];
        }
    }
}

echo $mins ? min($mins) : -1;


You are beta testing the new secret Terraria update. This update will add quests to the game!Simply, the world map can be represented as an array of length $$$n$$$, where the $$$i$$$-th column of the world has height $$$a_i$$$.There are $$$m$$$ quests you have to test. The $$$j$$$-th of them is represented by two integers $$$s_j$$$ and $$$t_j$$$. In this quest, you have to go from the column $$$s_j$$$ to the column $$$t_j$$$. At the start of the quest, you are appearing at the column $$$s_j$$$.In one move, you can go from the column $$$x$$$ to the column $$$x-1$$$ or to the column $$$x+1$$$. In this version, you have Spectre Boots, which allow you to fly. Since it is a beta version, they are bugged, so they only allow you to fly when you are going up and have infinite fly duration. When you are moving from the column with the height $$$p$$$ to the column with the height $$$q$$$, then you get some amount of fall damage. If the height $$$p$$$ is greater than the height $$$q$$$, you get $$$p - q$$$ fall damage, otherwise you fly up and get $$$0$$$ damage.For each of the given quests, determine the minimum amount of fall damage you can get during this quest.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^5; 1 \le m \le 10^5$$$) — the number of columns in the world and the number of quests you have to test, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the height of the $$$i$$$-th column of the world. The next $$$m$$$ lines describe quests. The $$$j$$$-th of them contains two integers $$$s_j$$$ and $$$t_j$$$ ($$$1 \le s_j, t_j \le n; s_j \ne t_j$$$), which means you have to move from the column $$$s_j$$$ to the column $$$t_j$$$ during the $$$j$$$-th quest. Note that $$$s_j$$$ can be greater than $$$t_j$$$.

Print $$$m$$$ integers. The $$$j$$$-th of them should be the minimum amount of fall damage you can get during the $$$j$$$-th quest completion.

<?php
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647

$loop = false;
$t = $loop ? IO::get() : 1;
while($t--) {
    solve();
}
//101
//101
//001
function solve()
{
     list($n, $m) = IO::getArray();
    $a = IO::getArray();
    $l = [0];
    for($i=1; $i<$n; $i++) {
        if($a[$i] < $a[$i-1]) {
            $l[$i] = $l[$i-1] + ($a[$i-1] - $a[$i]);
        } else {
           $l[$i] = $l[$i-1];
        }
    }
    $r = [];
    $r[$n-1] = 0;
    for($i=$n-2; $i>=0; $i--) {
        if($a[$i] < $a[$i+1]) {
            $r[$i] = $r[$i+1] + ($a[$i+1] - $a[$i]);
        } else {
           $r[$i] = $r[$i+1];
        }
    }
//    IO::prArray($r);
    for($i=0; $i<$m; $i++) {
         $ans = 0;
         list($f, $e) = IO::getArray();
         if($f < $e) {
              $ans = $l[$e-1] - $l[$f-1];
         } else {
            $ans = $r[$e-1] - $r[$f-1];
         }
         IO::pr($ans);
    }

}

class IO {
    public static function get()
    {
        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;
    }
}


Petya's friends made him a birthday present — a bracket sequence. Petya was quite disappointed with his gift, because he dreamed of correct bracket sequence, yet he told his friends nothing about his dreams and decided to fix present himself. To make everything right, Petya is going to move at most one bracket from its original place in the sequence to any other position. Reversing the bracket (e.g. turning "(" into ")" or vice versa) isn't allowed. We remind that bracket sequence $$$s$$$ is called correct if:   $$$s$$$ is empty;  $$$s$$$ is equal to "($$$t$$$)", where $$$t$$$ is correct bracket sequence;  $$$s$$$ is equal to $$$t_1 t_2$$$, i.e. concatenation of $$$t_1$$$ and $$$t_2$$$, where $$$t_1$$$ and $$$t_2$$$ are correct bracket sequences. For example, "(()())", "()" are correct, while ")(" and "())" are not. Help Petya to fix his birthday present and understand whether he can move one bracket so that the sequence becomes correct.

First of line of input contains a single number $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — length of the sequence which Petya received for his birthday. Second line of the input contains bracket sequence of length $$$n$$$, containing symbols "(" and ")".

Print "Yes" if Petya can make his sequence correct moving at most one bracket. Otherwise print "No".

NoteIn the first example, Petya can move first bracket to the end, thus turning the sequence into "()", which is correct bracket sequence.In the second example, there is no way to move at most one bracket so that the sequence becomes correct.In the third example, the sequence is already correct and there's no need to move brackets.

<?php
// I'm best and smarter human in the world :)

$n = readline();
$s = readline();
echo solve() . "\n";

function solve() {
	global $n, $s;
	$p_sum = 0;
	for ($i = 0; $i < $n; $i++) {
		$p_sum += ($s[$i] == '('? 1: -1);
		if ($p_sum < -1)
			return "No";
	}
	if ($p_sum != 0)
		return "No";
	return "Yes";
}


The company "Divan's Sofas" is planning to build $$$n + 1$$$ different buildings on a coordinate line so that:   the coordinate of each building is an integer number;  no two buildings stand at the same point. Let $$$x_i$$$ be the coordinate of the $$$i$$$-th building. To get from the building $$$i$$$ to the building $$$j$$$, Divan spends $$$|x_i - x_j|$$$ minutes, where $$$|y|$$$ is the absolute value of $$$y$$$.All buildings that Divan is going to build can be numbered from $$$0$$$ to $$$n$$$. The businessman will live in the building $$$0$$$, the new headquarters of "Divan's Sofas". In the first ten years after construction Divan will visit the $$$i$$$-th building $$$a_i$$$ times, each time spending $$$2 \cdot |x_0-x_i|$$$ minutes for walking.Divan asks you to choose the coordinates for all $$$n + 1$$$ buildings so that over the next ten years the businessman will spend as little time for walking as possible.

Each test contains several test cases. The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of buildings that "Divan's Sofas" is going to build, apart from the headquarters. The second line contains the sequence $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$), where $$$a_i$$$ is the number of visits to the $$$i$$$-th building. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, on the first line print the number $$$T$$$ — the minimum time Divan will spend walking.  On the second line print the sequence $$$x_0, x_1, \ldots, x_n$$$ of $$$n + 1$$$ integers, where $$$x_i$$$ ($$$-10^6 \le x_i \le 10^6$$$) is the selected coordinate of the $$$i$$$-th building. It can be shown that an optimal answer exists with coordinates not exceeding $$$10^6$$$. If there are multiple answers, print any of them.

NoteLet's look at the first example.Divan will visit the first building $$$a_1 = 1$$$ times, the second $$$a_2 = 2$$$ times and the third $$$a_3 = 3$$$ times. Then one of the optimal solution will be as follows:   the headquarters is located in $$$x_0 = 2$$$;  $$$x_1 = 4$$$: Divan will spend $$$2 \cdot |x_0-x_1| \cdot a_1 = 2 \cdot |2-4| \cdot 1 = 4$$$ minutes walking to the first building;  $$$x_2 = 1$$$: Divan will spend $$$2 \cdot |x_0-x_2| \cdot a_2 = 2 \cdot |2-1| \cdot 2 = 4$$$ minutes walking to the second building;  $$$x_3 = 3$$$: Divan will spend $$$2 \cdot |x_0-x_3| \cdot a_3 = 2 \cdot |2-3| \cdot 3 = 6$$$ minutes walking to the third building. In total, Divan will spend $$$4 + 4 + 6 = 14$$$ minutes. It can be shown that it is impossible to arrange buildings so that the businessman spends less time.Among others, $$$x = [1, 3, 2, 0]$$$, $$$x = [-5, -3, -6, -4]$$$ are also correct answers for the first example.

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

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

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

  $mainBuilding = 0;
  $coordinates = [];

  arsort($a);
  $k = 0; $j = 1; $counter = 0; $ans = 0;

  foreach ($a as $key => $val) {
    if ($k % 2 == 0) {
      $coordinates[$key] = $mainBuilding + $j;
      $counter++;
    } else {
      $coordinates[$key] = $mainBuilding - $j;
      $counter++;
    }

    $ans += 2 * (abs($mainBuilding - $coordinates[$key])) * $val;

    if ($counter == 2) {
      $counter = 0;
      $j++;
    }
    $k++;
  }

  printf('%0.0f', $ans);
  echo PHP_EOL;
  ksort($coordinates);

  echo $mainBuilding.' ';
  for ($j = 0; $j <= $n; $j++) {
    echo $coordinates[$j].' ';
  }
  echo PHP_EOL;
}
?>

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

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

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

  $mainBuilding = 0;
  $coordinates = [];

  arsort($a);
  $k = 0; $j = 1; $counter = 0; $ans = 0;

  foreach ($a as $key => $val) {
    if ($k % 2 == 0) {
      $coordinates[$key] = $mainBuilding + $j;
      $counter++;
    } else {
      $coordinates[$key] = $mainBuilding - $j;
      $counter++;
    }

    $ans += 2 * (abs($mainBuilding - $coordinates[$key])) * $val;

    if ($counter == 2) {
      $counter = 0;
      $j++;
    }
    $k++;
  }

  echo $ans.PHP_EOL;
  ksort($coordinates);

  echo $mainBuilding.' ';
  for ($j = 0; $j <= $n; $j++) {
    echo $coordinates[$j].' ';
  }
  echo PHP_EOL;
}
?>

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

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

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

  rsort($a);
  $mainBuilding = 0;

  $coordinates = [];
  $k = 0;
  $ans = 0;
  for ($j = 1; $k < $n; $j++) {
    $coordinate = $mainBuilding + ($j);
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;

    if ($k == $n) break;
    $coordinate = $mainBuilding - ($j);
    if ($coordinate == $mainBuilding) { $coordinate -= 1;}
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;
  }
  $a = array_reverse($coordinates);
  echo $ans.PHP_EOL;
  echo $mainBuilding.' ';
  for ($j = 0; $j <= $n; $j++) {
    echo $a[$j].' ';
  }
  echo PHP_EOL;
}

?>

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

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

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

  rsort($a);
  $mainBuilding = 0;

  $coordinates = [];
  $coordinates[0] = $mainBuilding;
  $k = 0;
  $ans = 0;
  for ($j = 1; $k < $n; $j++) {
    $coordinate = $mainBuilding - ($j);
    if ($coordinate == $mainBuilding) { $coordinate -= 1;}
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;

    if ($k == $n) break;
    $coordinate = $mainBuilding + ($j);
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;
  }

  echo $ans.PHP_EOL;
  for ($j = 0; $j <= $n; $j++) {
    echo $coordinates[$j].' ';
  }
  echo PHP_EOL;
}

?>

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

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

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

  $mainBuilding = floor(($n + 1) / 2);
  rsort($a);

  $coordinates = [];
  $coordinates[0] = $mainBuilding;
  $k = 0;
  $ans = 0;
  for ($j = 1; $k < $n; $j++) {
    $coordinate = $mainBuilding - ($j);
    if ($coordinate == $mainBuilding) { $coordinate -= 1;}
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;

    if ($k == $n) break;
    $coordinate = $mainBuilding + ($j);
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;
  }

  echo $ans.PHP_EOL;
  for ($j = 0; $j <= $n; $j++) {
    echo $coordinates[$j].' ';
  }
  echo PHP_EOL;
}

?>

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

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

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

  $mainBuilding = floor(($n + 1) / 2);

  echo $mainBuilding.PHP_EOL;

  rsort($a);

  $coordinates = [];
  $coordinates[0] = $mainBuilding;
  $k = 0;
  $ans = 0;
  for ($j = 1; $k < $n; $j++) {
    $coordinate = $mainBuilding - ($j);
    if ($coordinate == $mainBuilding) { $coordinate -= 1;}
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;

    if ($k == $n) break;
    $coordinate = $mainBuilding + ($j);
    $coordinates[] = $coordinate;
    $ans += 2 * (abs($mainBuilding - $coordinate)) * $a[$k];
    $k++;
  }

  echo $ans.PHP_EOL;
  for ($j = 0; $j <= $n; $j++) {
    echo $coordinates[$j].' ';
  }
  echo PHP_EOL;
}

?>