Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of the board are adjacent if they share a side.

The first line contains an integer n (1 ≤ n ≤ 100). Then n lines follow containing the description of the checkerboard. Each of them contains n characters (either 'x' or 'o') without spaces.

Print "YES" or "NO" (without the quotes) depending on the answer to the problem.

<?php
// 462A     Яблов и простая задача

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

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

$arr = array();

for ($i=0; $i < $n; $i++) {
    $input_line = fgets($in);
    $arr[$i] = preg_split('//', substr($input_line, 0, strlen($input_line)-2), -1, PREG_SPLIT_NO_EMPTY);
}

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

        $count_o = 0;
        if ($arr[$i-1][$j] === 'o') $count_o ++;
        if ($arr[$i+1][$j] === 'o') $count_o ++;
        if ($arr[$i][$j-1] === 'o') $count_o ++;
        if ($arr[$i][$j+1] === 'o') $count_o ++;

        if (($count_o % 2) != 0) {
            echo "NO";
            exit();
        }
    }
}

echo "YES";

?>


You are given an array of positive integers $$$a_1, a_2, \ldots, a_n$$$.Make the product of all the numbers in the array (that is, $$$a_1 \cdot a_2 \cdot \ldots \cdot a_n$$$) divisible by $$$2^n$$$.You can perform the following operation as many times as you like:  select an arbitrary index $$$i$$$ ($$$1 \leq i \leq n$$$) and replace the value $$$a_i$$$ with $$$a_i=a_i \cdot i$$$. You cannot apply the operation repeatedly to a single index. In other words, all selected values of $$$i$$$ must be different.Find the smallest number of operations you need to perform to make the product of all the elements in the array divisible by $$$2^n$$$. Note that such a set of operations does not always exist.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number test cases. Then the descriptions of the input data sets follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains exactly $$$n$$$ integers: $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ values over all test cases in a test does not exceed $$$2 \cdot 10^5$$$.

For each test case, print the least number of operations to make the product of all numbers in the array divisible by $$$2^n$$$. If the answer does not exist, print -1.

NoteIn the first test case, the product of all elements is initially $$$2$$$, so no operations needed.In the second test case, the product of elements initially equals $$$6$$$. We can apply the operation for $$$i = 2$$$, and then $$$a_2$$$ becomes $$$2\cdot2=4$$$, and the product of numbers becomes $$$3\cdot4=12$$$, and this product of numbers is divided by $$$2^n=2^2=4$$$. In the fourth test case, even if we apply all possible operations, we still cannot make the product of numbers divisible by $$$2^n$$$  — it will be $$$(13\cdot1)\cdot(17\cdot2)\cdot(1\cdot3)\cdot(1\cdot4)=5304$$$, which does not divide by $$$2^n=2^4=16$$$.In the fifth test case, we can apply operations for $$$i = 2$$$ and $$$i = 4$$$.

<?php
//[$n,$m] = array_map('intval', explode(' ', trim(fgets(STDIN))));
[$t] = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$a = array_map('intval', explode(' ', trim(fgets(STDIN))));
//[$s,$t] = explode(' ', trim(fgets(STDIN)));
//[$s] = explode(' ', trim(fgets(STDIN)));
//$s = explode(' ', trim(fgets(STDIN)));
//function decr($v){return --$v;}
//$alpha='abcdefghijklmnopqrstuvwxyz';
//$mod=1000000009;
//$mod=1000000007;
//$mod=998244353;
//$a=[];
//$b=[];
for($i=0;$i<$t;$i++){
    [$n] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $a = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $cnt = 0;
    $add = [];
    for($j=0;$j<$n;$j++){
        $x = $a[$j];
        while($x % 2 == 0){
            $cnt++;
            $x /= 2;
        }
        $x = ($j+1);
        $b = 0;
        $cnt1 = 0;
        while($x % 2 == 0){
            $cnt1++;
            $x /= 2;
        }
        $add[]=$cnt1;
    }
    rsort($add);
    $p = 0;
    for($j=0;$j<$n;$j++){
        if($cnt >= $n) break;
        $p++;
        $cnt += $add[$j];
    }
    //echo ">>".$cnt." ".$n.PHP_EOL;
    if($cnt < $n){
        $ans[] = -1;
    }else{
        $ans[] = $p;
    }
}
echo implode(PHP_EOL,$ans);

<?php
//[$n,$m] = array_map('intval', explode(' ', trim(fgets(STDIN))));
[$t] = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$a = array_map('intval', explode(' ', trim(fgets(STDIN))));
//[$s,$t] = explode(' ', trim(fgets(STDIN)));
//[$s] = explode(' ', trim(fgets(STDIN)));
//$s = explode(' ', trim(fgets(STDIN)));
//function decr($v){return --$v;}
//$alpha='abcdefghijklmnopqrstuvwxyz';
//$mod=1000000009;
//$mod=1000000007;
//$mod=998244353;
//$a=[];
//$b=[];
for($i=0;$i<$t;$i++){
    [$n] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $a = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $cnt = 0;
    for($j=0;$j<$n;$j++){
        $x = $a[$j];
        while($x % 2 == 0){
            $cnt++;
            $x /= 2;
        }
    }
    $p = 0;
    $y = 1;
    $x = 0;
    while($y*2 <= $n){
        $y *= 2;
        $x++;
    }
    //echo ">>".$x.PHP_EOL;
    for($j=$x;$j>=0 && $cnt<$n;$j--){
        $p++;
        $cnt+=$j;
    }
    //echo ">>".$cnt." ".$n.PHP_EOL;
    if($cnt < $n){
        $ans[] = -1;
    }else{
        $ans[] = $p;
    }
}
echo implode(PHP_EOL,$ans);


According to a new ISO standard, a flag of every country should have, strangely enough, a chequered field n × m, each square should be wholly painted one of 26 colours. The following restrictions are set:   In each row at most two different colours can be used.  No two adjacent squares can be painted the same colour. Pay attention, please, that in one column more than two different colours can be used.Berland's government took a decision to introduce changes into their country's flag in accordance with the new standard, at the same time they want these changes to be minimal. By the given description of Berland's flag you should find out the minimum amount of squares that need to be painted different colour to make the flag meet the new ISO standard. You are as well to build one of the possible variants of the new Berland's flag.

The first input line contains 2 integers n and m (1 ≤ n, m ≤ 500) — amount of rows and columns in Berland's flag respectively. Then there follows the flag's description: each of the following n lines contains m characters. Each character is a letter from a to z, and it stands for the colour of the corresponding square.

In the first line output the minimum amount of squares that need to be repainted to make the flag meet the new ISO standard. The following n lines should contain one of the possible variants of the new flag. Don't forget that the variant of the flag, proposed by you, should be derived from the old flag with the minimum amount of repainted squares. If the answer isn't unique, output any.


One way to create a task is to learn from life. You can choose some experience in real life, formalize it and then you will get a new task.Let's think about a scene in real life: there are lots of people waiting in front of the elevator, each person wants to go to a certain floor. We can formalize it in the following way. We have n people standing on the first floor, the i-th person wants to go to the fi-th floor. Unfortunately, there is only one elevator and its capacity equal to k (that is at most k people can use it simultaneously). Initially the elevator is located on the first floor. The elevator needs |a - b| seconds to move from the a-th floor to the b-th floor (we don't count the time the people need to get on and off the elevator).What is the minimal number of seconds that is needed to transport all the people to the corresponding floors and then return the elevator to the first floor?

The first line contains two integers n and k (1 ≤ n, k ≤ 2000) — the number of people and the maximal capacity of the elevator. The next line contains n integers: f1, f2, ..., fn (2 ≤ fi ≤ 2000), where fi denotes the target floor of the i-th person.

Output a single integer — the minimal time needed to achieve the goal.

NoteIn first sample, an optimal solution is:   The elevator takes up person #1 and person #2.  It goes to the 2nd floor.  Both people go out of the elevator.  The elevator goes back to the 1st floor.  Then the elevator takes up person #3.  And it goes to the 2nd floor.  It picks up person #2.  Then it goes to the 3rd floor.  Person #2 goes out.  Then it goes to the 4th floor, where person #3 goes out.  The elevator goes back to the 1st floor.

<?php
list($n, $k) = explode(" ",trim(fgets(STDIN)));
$arr = explode(" ",trim(fgets(STDIN)));
sort($arr);
$ans = 0;
for ($i=$n-1; $i>=0; $i-=$k) {
    $ans += 2*($arr[$i]-1);
}
echo $ans;
?>

<?php
list($n, $k) = explode(" ",trim(fgets(STDIN)));
$f = explode(" ",trim(fgets(STDIN)));
sort($f);
for($i=$n-1;$i>=0;$i-=$k){
	$ans+=2*($f[$i]-1);
}
echo $ans;
?>

<?php

//fscanf(STDIN, "%d", $t);
$values = array_map('intval', explode(' ',trim(fgets(STDIN))));
$n = $values[0];
$k = $values[1];

$ppl = $values = array_map('intval', explode(' ',trim(fgets(STDIN))));
rsort($ppl);
$res = 0;
$last = 0;
for ($i = 1 ; $i <= count($ppl); $i++) {
	if ($i%$k == 0 || $i == count($ppl)) {
		$res += $ppl[$last]*2 - 2;
		$last = $i;
	}
}

echo $res."\n";

<?php

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

list($n, $k) = explode(" ",trim(fgets($in)));

$a = explode(" ",trim(fgets($in)));

rsort($a);

$i = 0;
$s = 0;
while($i<$n){
	$s += ($a[$i]-1)*2;
	$i += $k;
}

echo "$s\n";

<?php

//fscanf(STDIN, "%d", $t);
$values = array_map('intval', explode(' ',trim(fgets(STDIN))));
$n = $values[0];
$k = $values[1];

$ppl = $values = array_map('intval', explode(' ',trim(fgets(STDIN))));
rsort($ppl);
$res = 0;

for ($i = 1 ; $i <= count($ppl); $i++) {
	if ($i%$k == 0 || $i == count($ppl)) {
		$res += $ppl[$i-1]*2 - 2;
	}
}

echo $res."\n";


Tanya has $$$n$$$ candies numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th candy has the weight $$$a_i$$$.She plans to eat exactly $$$n-1$$$ candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.Your task is to find the number of such candies $$$i$$$ (let's call these candies good) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days. Note that at first, she will give the candy, after it she will eat the remaining candies one by one.For example, $$$n=4$$$ and weights are $$$[1, 4, 3, 3]$$$. Consider all possible cases to give a candy to dad:  Tanya gives the $$$1$$$-st candy to dad ($$$a_1=1$$$), the remaining candies are $$$[4, 3, 3]$$$. She will eat $$$a_2=4$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$4+3=7$$$ and in even days she will eat $$$3$$$. Since $$$7 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$2$$$-nd candy to dad ($$$a_2=4$$$), the remaining candies are $$$[1, 3, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_3=3$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$3$$$. Since $$$4 \ne 3$$$ this case shouldn't be counted to the answer (this candy isn't good).  Tanya gives the $$$3$$$-rd candy to dad ($$$a_3=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_4=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good).  Tanya gives the $$$4$$$-th candy to dad ($$$a_4=3$$$), the remaining candies are $$$[1, 4, 3]$$$. She will eat $$$a_1=1$$$ in the first day, $$$a_2=4$$$ in the second day, $$$a_3=3$$$ in the third day. So in odd days she will eat $$$1+3=4$$$ and in even days she will eat $$$4$$$. Since $$$4 = 4$$$ this case should be counted to the answer (this candy is good). In total there $$$2$$$ cases which should counted (these candies are good), so the answer is $$$2$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the weight of the $$$i$$$-th candy.

Print one integer — the number of such candies $$$i$$$ (good candies) that if dad gets the $$$i$$$-th candy then the sum of weights of candies Tanya eats in even days will be equal to the sum of weights of candies Tanya eats in odd days.

NoteIn the first example indices of good candies are $$$[1, 2]$$$.In the second example indices of good candies are $$$[2, 3]$$$.In the third example indices of good candies are $$$[4, 5, 9]$$$.


Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a walk with Cormen 2 times, today he has to go for a walk at least 3 times. Polycarp analysed all his affairs over the next n days and made a sequence of n integers a1, a2, ..., an, where ai is the number of times Polycarp will walk with the dog on the i-th day while doing all his affairs (for example, he has to go to a shop, throw out the trash, etc.).Help Polycarp determine the minimum number of walks he needs to do additionaly in the next n days so that Cormen will feel good during all the n days. You can assume that on the day before the first day and on the day after the n-th day Polycarp will go for a walk with Cormen exactly k times. Write a program that will find the minumum number of additional walks and the appropriate schedule — the sequence of integers b1, b2, ..., bn (bi ≥ ai), where bi means the total number of walks with the dog on the i-th day.

The first line contains two integers n and k (1 ≤ n, k ≤ 500) — the number of days and the minimum number of walks with Cormen for any two consecutive days.  The second line contains integers a1, a2, ..., an (0 ≤ ai ≤ 500) — the number of walks with Cormen on the i-th day which Polycarp has already planned.

In the first line print the smallest number of additional walks that Polycarp should do during the next n days so that Cormen will feel good during all days.  In the second line print n integers b1, b2, ..., bn, where bi — the total number of walks on the i-th day according to the found solutions (ai ≤ bi for all i from 1 to n). If there are multiple solutions, print any of them.

<?php

###### IO ######
error_reporting(E_ALL);
error_reporting(0);

function readString($f) {
	$r = array(
		"\r" => '',
		"\n" => '',
	);
	return strtr(fgets($f), $r);
}

function readNumString($f) {
	return trim(fgets($f));
}

function stringToArray($str) {
	return str_split($str);
}

function readNum($f, $is_int = false) {
	$v = readNumString($f);
	return $is_int ? intval($v) : floatval($v);
}

function readStringExplode($f, $delimiter = ' ') {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = 'trim';
	return array_map($callf, $return);
}

function readStringExplodeNum($f, $delimiter = ' ', $is_int = false) {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = $is_int ? 'intval' : 'floatval';
	return array_map($callf, $return);
}

###### /IO ######

function getAnswer($is_test = false, $f = false) {
	if ($is_test)
		$stream = $f;
	else
		$stream = STDIN;
	/* begin body */
	list($daysCount, $needHour) = readStringExplodeNum($stream, ' ', true);
	$datesPlan = readStringExplodeNum($stream, ' ', true);
	$totalAddHours = 0;

	for ($i = 1; $i < $daysCount; $i++) {
		if ($datesPlan[$i] + $datesPlan[$i - 1] < $needHour) {
			$addHour = $needHour - ($datesPlan[$i] + $datesPlan[$i - 1]);
			$datesPlan[$i]+=$addHour;
			$totalAddHours+=$addHour;
		}
	}
	echo $totalAddHours . "\r\n";
	echo implode(' ', $datesPlan);
	/* / end body */
}

if (empty($is_test))
	getAnswer();

<?php

###### IO ######
error_reporting(E_ALL);
error_reporting(0);

function readString($f) {
	$r = array(
		"\r" => '',
		"\n" => '',
	);
	return strtr(fgets($f), $r);
}

function readNumString($f) {
	return trim(fgets($f));
}

function stringToArray($str) {
	return str_split($str);
}

function readNum($f, $is_int = false) {
	$v = readNumString($f);
	return $is_int ? intval($v) : floatval($v);
}

function readStringExplode($f, $delimiter = ' ') {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = 'trim';
	return array_map($callf, $return);
}

function readStringExplodeNum($f, $delimiter = ' ', $is_int = false) {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = $is_int ? 'intval' : 'floatval';
	return array_map($callf, $return);
}

###### /IO ######

function getAnswer($is_test = false, $f = false) {
	if ($is_test)
		$stream = $f;
	else
		$stream = STDIN;
	/* begin body */
	list($daysCount, $needHour) = readStringExplodeNum($stream, ' ', true);
	$datesPlan = readStringExplodeNum($stream, ' ', true);
	$totalAddHours = 0;

	for ($i = 0; $i < $daysCount - 1; $i++) {
		if ($datesPlan[$i] + $datesPlan[$i + 1] >= $needHour) {
			continue;
		} else {
			if ($i + 2 < $daysCount) {
				if ($datesPlan[$i + 1] + $datesPlan[$i + 2] >= $needHour) {
					$addHours = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
					$totalAddHours+=$addHours;
					$datesPlan[$i]+=$addHours;

				} else {
					$addForRight = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
					$addForLeft = $needHour - ($datesPlan[$i + 1] + $datesPlan[$i + 2]);
					$addHours = max($addForRight, $addForLeft);
					$totalAddHours+=$addHours;
					$datesPlan[$i+1]+=$addHours;

				}
			} else {
				$addHours = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
				$totalAddHours+=$addHours;
				$datesPlan[$i]+=$addHours;

			}
		}
	}
	echo $totalAddHours . "\r\n";
	echo implode(' ', $datesPlan);
	/* / end body */
}

if (empty($is_test))
	getAnswer();

<?php

###### IO ######
error_reporting(E_ALL);
error_reporting(0);

function readString($f) {
	$r = array(
		"\r" => '',
		"\n" => '',
	);
	return strtr(fgets($f), $r);
}

function readNumString($f) {
	return trim(fgets($f));
}

function stringToArray($str) {
	return str_split($str);
}

function readNum($f, $is_int = false) {
	$v = readNumString($f);
	return $is_int ? intval($v) : floatval($v);
}

function readStringExplode($f, $delimiter = ' ') {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = 'trim';
	return array_map($callf, $return);
}

function readStringExplodeNum($f, $delimiter = ' ', $is_int = false) {
	$v = readNumString($f);
	if ($delimiter == '') {
		$return = stringToArray($v);
	} else {
		$return = explode($delimiter, $v);
	}
	$callf = $is_int ? 'intval' : 'floatval';
	return array_map($callf, $return);
}

###### /IO ######

function getAnswer($is_test = false, $f = false) {
	if ($is_test)
		$stream = $f;
	else
		$stream = STDIN;
	/* begin body */
	list($daysCount, $needHour) = readStringExplodeNum($stream, ' ', true);
	$datesPlan = readStringExplodeNum($stream, ' ', true);
	$totalAddHours = 0;

	for ($i = 0; $i < $daysCount - 1; $i++) {
		if ($datesPlan[$i] + $datesPlan[$i + 1] >= $needHour) {
			continue;
		} else {
			if ($i + 2 < $daysCount) {
				$addForThis = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
				$addForNext = $needHour - ($datesPlan[$i + 1] + $datesPlan[$i + 2]);
				if ($datesPlan[$i + 1] + $datesPlan[$i + 2] >= $needHour) {
					$addHours = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
					$totalAddHours+=$addHours;
					$datesPlan[$i]+=$addHours;
				} else {
					if ($i == 0) {
						$addForRight = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
						$addForLeft = $needHour - ($datesPlan[$i + 1] + $datesPlan[$i + 2]);
						$addHours = max($addForRight, $addForLeft);
						$totalAddHours+=$addHours;
						$datesPlan[$i + 1]+=$addHours;
					} else {
						$addForRight = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
						$addForLeft = $needHour - ($datesPlan[$i + 1] + $datesPlan[$i + 2]);
						$addHours = min($addForRight, $addForLeft);
						$totalAddHours+=$addHours;
						$datesPlan[$i + 1]+=$addHours;
					}
				}
			} else {
				$addHours = $needHour - ($datesPlan[$i] + $datesPlan[$i + 1]);
				$totalAddHours+=$addHours;
				$datesPlan[$i]+=$addHours;
			}
		}
	}
	echo $totalAddHours . "\r\n";
	echo implode(' ', $datesPlan);
	/* / end body */
}

if (empty($is_test))
	getAnswer();


Anya has bought a new smartphone that uses Berdroid operating system. The smartphone menu has exactly n applications, each application has its own icon. The icons are located on different screens, one screen contains k icons. The icons from the first to the k-th one are located on the first screen, from the (k + 1)-th to the 2k-th ones are on the second screen and so on (the last screen may be partially empty).Initially the smartphone menu is showing the screen number 1. To launch the application with the icon located on the screen t, Anya needs to make the following gestures: first she scrolls to the required screen number t, by making t - 1 gestures (if the icon is on the screen t), and then make another gesture — press the icon of the required application exactly once to launch it.After the application is launched, the menu returns to the first screen. That is, to launch the next application you need to scroll through the menu again starting from the screen number 1.All applications are numbered from 1 to n. We know a certain order in which the icons of the applications are located in the menu at the beginning, but it changes as long as you use the operating system. Berdroid is intelligent system, so it changes the order of the icons by moving the more frequently used icons to the beginning of the list. Formally, right after an application is launched, Berdroid swaps the application icon and the icon of a preceding application (that is, the icon of an application on the position that is smaller by one in the order of menu). The preceding icon may possibly be located on the adjacent screen. The only exception is when the icon of the launched application already occupies the first place, in this case the icon arrangement doesn't change.Anya has planned the order in which she will launch applications. How many gestures should Anya make to launch the applications in the planned order? Note that one application may be launched multiple times.

The first line of the input contains three numbers n, m, k (1 ≤ n, m, k ≤ 105) — the number of applications that Anya has on her smartphone, the number of applications that will be launched and the number of icons that are located on the same screen. The next line contains n integers, permutation a1, a2, ..., an — the initial order of icons from left to right in the menu (from the first to the last one), ai —  is the id of the application, whose icon goes i-th in the menu. Each integer from 1 to n occurs exactly once among ai. The third line contains m integers b1, b2, ..., bm(1 ≤ bi ≤ n) — the ids of the launched applications in the planned order. One application may be launched multiple times.

Print a single number — the number of gestures that Anya needs to make to launch all the applications in the desired order.

NoteIn the first test the initial configuration looks like (123)(456)(78), that is, the first screen contains icons of applications 1, 2, 3, the second screen contains icons 4, 5, 6, the third screen contains icons 7, 8. After application 7 is launched, we get the new arrangement of the icons — (123)(457)(68). To launch it Anya makes 3 gestures. After application 8 is launched, we get configuration (123)(457)(86). To launch it Anya makes 3 gestures. After application 1 is launched, the arrangement of icons in the menu doesn't change. To launch it Anya makes 1 gesture.In total, Anya makes 7 gestures.


Vasya has an array $$$a_1, a_2, \dots, a_n$$$.You don't know this array, but he told you $$$m$$$ facts about this array. The $$$i$$$-th fact is a triple of numbers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$) and it means:  if $$$t_i=1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is sorted in non-decreasing order;  if $$$t_i=0$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots, a_{r_i}$$$ is not sorted in non-decreasing order. A subarray is not sorted if there is at least one pair of consecutive elements in this subarray such that the former is greater than the latter. For example if $$$a = [2, 1, 1, 3, 2]$$$ then he could give you three facts: $$$t_1=1, l_1=2, r_1=4$$$ (the subarray $$$[a_2, a_3, a_4] = [1, 1, 3]$$$ is sorted), $$$t_2=0, l_2=4, r_2=5$$$ (the subarray $$$[a_4, a_5] = [3, 2]$$$ is not sorted), and $$$t_3=0, l_3=3, r_3=5$$$ (the subarray $$$[a_3, a_5] = [1, 3, 2]$$$ is not sorted).You don't know the array $$$a$$$. Find any array which satisfies all the given facts.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 1000, 1 \le m \le 1000$$$). Each of the next $$$m$$$ lines contains three integers $$$t_i$$$, $$$l_i$$$ and $$$r_i$$$ ($$$0 \le t_i \le 1, 1 \le l_i < r_i \le n$$$). If $$$t_i = 1$$$ then subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is sorted. Otherwise (if $$$t_i = 0$$$) subbarray $$$a_{l_i}, a_{l_i + 1}, \dots , a_{r_i}$$$ is not sorted.

If there is no array that satisfies these facts in only line print NO (in any letter case). If there is a solution, print YES (in any letter case). In second line print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the array $$$a$$$, satisfying all the given facts. If there are multiple satisfying arrays you can print any of them.

<?php
#1187C
[$n, $m] = fscanf(STDIN, '%u %u');
$arr = array_fill(0, $n, null);
$descIntervals = [];
while ($m--) {
    [$t, $l, $r] = fscanf(STDIN, '%u %u %u');
    if ($t === 1) {
        while ($l < $r) {
            $arr[$l] = true;
            $l++;
        }
    } else {
        $descIntervals[] = [$l, $r];
    }
}
foreach ($descIntervals as $interval) {
    $invalidInterval = true;
    for ($i = $interval[0]; $i < $interval[1]; $i++) {
        if ($arr[$i] === null) {
            $invalidInterval = false;
        }
    }
    if ($invalidInterval) {
        die('NO');
    }
}
echo 'YES' . PHP_EOL;
foreach ($arr as $i => $item) {
    if ($i && $item === null) {
        $n--;
    }
    $arr[$i] = $n;
}
echo implode(' ', $arr);

<?php
#1187C
[$n, $m] = fscanf(STDIN, '%u %u');
$arr = array_fill(0, $n, null);
$descIntervals = [];
while ($m--) {
    [$t, $l, $r] = fscanf(STDIN, '%u %u %u');
    if ($t === 1) {
        while ($l < $r) {
            $arr[$l] = true;
            $l++;
        }
    } else {
        $descIntervals[] = [$l, $r];
    }
}
foreach ($descIntervals as $interval) {
    $invalidInterval = true;
    for ($i = $interval[0]; $i < $interval[1]; $i++) {
        if ($arr[$i] === null) {
            $invalidInterval = false;
        }
    }
    if ($invalidInterval) {
        die('NO');
    }
}
unset($descIntervals);
foreach ($arr as $i => $item) {
    if ($i && $item === null) {
        $n--;
    }
    echo ($i ? ' ' : ('YES' . PHP_EOL)) . $n;
}

<?php
#1187C
[$n, $m] = fscanf(STDIN, '%u %u');
$arr = array_fill(0, $n, null);
$descIntervals = [];
while ($m--) {
    [$t, $l, $r] = fscanf(STDIN, '%u %u %u');
    if ($t === 1) {
        while ($l < $r) {
            $arr[$l] = true;
            $l++;
        }
    } else {
        $descIntervals[] = [$l, $r];
    }
}
foreach ($descIntervals as $interval) {
    $invalidInterval = true;
    for ($i = $interval[0]; $i < $interval[1]; $i++) {
        if ($arr[$i] === null) {
            $invalidInterval = false;
        }
    }
    if ($invalidInterval) {
        die('NO');
    }
}
unset($invalidInterval);
echo 'YES' . PHP_EOL;
foreach ($arr as $i => $item) {
    if ($i && $item === null) {
        $n--;
    }
    echo ($i ? ' ' : '') . $n;
}


In the autumn of this year, two Russian teams came into the group stage of the most prestigious football club competition in the world — the UEFA Champions League. Now, these teams have already started to play in the group stage and are fighting for advancing to the playoffs. In this problem we are interested in the draw stage, the process of sorting teams into groups.The process of the draw goes as follows (the rules that are described in this problem, are somehow simplified compared to the real life). Suppose n teams will take part in the group stage (n is divisible by four). The teams should be divided into groups of four. Let's denote the number of groups as m (). Each team has a rating — an integer characterizing the team's previous achievements. The teams are sorted by the rating's decreasing (no two teams have the same rating).After that four "baskets" are formed, each of which will contain m teams: the first m teams with the highest rating go to the first basket, the following m teams go to the second one, and so on.Then the following procedure repeats m - 1 times. A team is randomly taken from each basket, first from the first basket, then from the second, then from the third, and at last, from the fourth. The taken teams form another group. After that, they are removed from their baskets.The four teams remaining in the baskets after (m - 1) such procedures are performed, form the last group.In the real draw the random selection of teams from the basket is performed by people — as a rule, the well-known players of the past. As we have none, we will use a random number generator, which is constructed as follows. Its parameters are four positive integers x, a, b, c. Every time there is a call to the random number generator, it produces the following actions:  calculates ;  replaces parameter x by value y (assigns );  returns x as another random number. Operation  means taking the remainder after division: , .A random number generator will be used in the draw as follows: each time we need to randomly choose a team from the basket, it will generate a random number k. The teams that yet remain in the basket are considered numbered with consecutive integers from 0 to s - 1, in the order of decreasing rating, where s is the current size of the basket. Then a team number  is taken from the basket.Given a list of teams and the parameters of the random number generator, determine the result of the draw.

The first input line contains integer n (4 ≤ n ≤ 64, n is divisible by four) — the number of teams that take part in the sorting. The second line contains four space-separated integers x, a, b, c (1 ≤ x, a, b, c ≤ 1000) — the parameters of the random number generator. Each of the following n lines describes one team. The description consists of the name of the team and its rating, separated by a single space. The name of a team consists of uppercase and lowercase English letters and has length from 1 to 20 characters. A team's rating is an integer from 0 to 1000. All teams' names are distinct. All team's ratings are also distinct.

Print the way the teams must be sorted into groups. Print the groups in the order, in which they are formed in the sorting. Number the groups by consecutive uppercase English letters, starting from letter 'A'. Inside each group print the teams' names one per line, in the order of decreasing of the teams' rating. See samples for a better understanding of the output format.

8
1 3 1 7
Barcelona 158
Milan 90
Spartak 46
Anderlecht 48
Celtic 32
Benfica 87
Zenit 79
Malaga 16

Group A:
Barcelona
Benfica
Spartak
Celtic
Group B:
Milan
Zenit
Anderlecht
Malaga

NoteIn the given sample the random number generator will be executed four times:   ,  ,  ,  .


Stanley and Megan decided to shop in the "Crossmarket" grocery store, which can be represented as a matrix with $$$n$$$ rows and $$$m$$$ columns. Stanley and Megan can move to an adjacent cell using $$$1$$$ unit of power. Two cells are considered adjacent if they share an edge. To speed up the shopping process, Megan brought her portals with her, and she leaves one in each cell she visits (if there is no portal yet). If a person (Stanley or Megan) is in a cell with a portal, that person can use $$$1$$$ unit of power to teleport to any other cell with a portal, including Megan's starting cell.They decided to split up: Stanley will go from the upper-left cell (cell with coordinates $$$(1, 1)$$$) to the lower-right cell (cell with coordinates $$$(n, m)$$$), whilst Megan needs to get from the lower-left cell (cell with coordinates $$$(n, 1)$$$) to the upper-right cell (cell with coordinates $$$(1, m)$$$).What is the minimum total energy needed for them both to do that?Note that they can choose the time they move. Time does not affect energy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The only line in the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$).

For each test case print a single integer on a new line – the answer.

Note  In the first test case they can stick to the following plan:   Megan (red circle) moves to the cell $$$(7, 3)$$$. Then she goes to the cell $$$(1, 3)$$$, and Stanley (blue circle) does the same.  Stanley uses the portal in that cell (cells with portals are grey) to get to the cell $$$(7, 3)$$$. Then he moves to his destination — cell $$$(7, 5)$$$.  Megan also finishes her route and goes to the cell $$$(1, 5)$$$. The total energy spent is $$$(2 + 6) + (2 + 1 + 2) + (2)= 15$$$, which is our final answer.

<?php
function read() {
  return trim(fgets($GLOBALS['file'])) ;
}
function readInt() {
  return (int) read() ;
}
function readStrs() {
  return explode(" ",read()) ;
}
function readIntArray() {
  return array_map('intval', readStrs());
}
function readAsArray() {
  return str_split(read()) ;
}
function puts($arg) {
  if($arg === true) print_r("true");
  elseif($arg === false) print_r("false");
  else {
    print_r($arg) ;
  }
  print_r("\n") ;
}
$file = (file_exists("input.txt")) ? fopen("input.txt","r") : STDIN ;

//-----------------------------------//

$t = readInt();
while($t--) {
    [$n,$m] = readIntArray();
    if($n == 1 && $m == 1) {
        puts(0);

    }
    else puts($n+$m+min($n,$m) - 2);
}

<?php
function read() {
  return trim(fgets($GLOBALS['file'])) ;
}
function readInt() {
  return (int) read() ;
}
function readStrs() {
  return explode(" ",read()) ;
}
function readIntArray() {
  return array_map('intval', readStrs());
}
function readAsArray() {
  return str_split(read()) ;
}
function puts($arg) {
  if($arg === true) print_r("true");
  elseif($arg === false) print_r("false");
  else {
    print_r($arg) ;
  }
  print_r("\n") ;
}
$file = (file_exists("input.txt")) ? fopen("input.txt","r") : STDIN ;

//-----------------------------------//

$t = readInt();
while($t--) {
    [$n,$m] = readIntArray();
    if($n == 1 && $m == 1) {
        puts(0);
    }
    puts($n+$m+min($n,$m) - 2);
}


Let's call a string good if its length is at least $$$2$$$ and all of its characters are $$$\texttt{A}$$$ except for the last character which is $$$\texttt{B}$$$. The good strings are $$$\texttt{AB},\texttt{AAB},\texttt{AAAB},\ldots$$$. Note that $$$\texttt{B}$$$ is not a good string.You are given an initially empty string $$$s_1$$$.You can perform the following operation any number of times:   Choose any position of $$$s_1$$$ and insert some good string in that position. Given a string $$$s_2$$$, can we turn $$$s_1$$$ into $$$s_2$$$ after some number of operations?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single string $$$s_2$$$ ($$$1 \leq |s_2| \leq 2 \cdot 10^5$$$). It is guaranteed that $$$s_2$$$ consists of only the characters $$$\texttt{A}$$$ and $$$\texttt{B}$$$. It is guaranteed that the sum of $$$|s_2|$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if we can turn $$$s_1$$$ into $$$s_2$$$ after some number of operations, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAB}} \to \texttt{A}\color{red}{\texttt{AB}}\texttt{AB}$$$.In the third test case, we transform $$$s_1$$$ as such: $$$\varnothing \to \color{red}{\texttt{AAAAAAAAB}}$$$.In the second and fourth test case, it can be shown that it is impossible to turn $$$s_1$$$ into $$$s_2$$$.

<?php class InputReader{protected $_fh;public function __construct($fileHandler = STDIN)   {$this->_fh = $fileHandler;}
    public function readString(){$s = trim(fgets($this->_fh));return $s;}
    public function readInt(){$d = trim(fgets($this->_fh));return (int)$d;}
    public function readArrayOfInt($separator = ' ', $indexFrom = 0){$a = [];$ind = $indexFrom;foreach (explode($separator, fgets($this->_fh)) as $item) {$a[$ind++] = (int)$item;}return $a;}
    public function readArrayOfFloat($separator = ' ', $indexFrom = 0) { $a = []; $ind = $indexFrom; foreach (explode($separator, fgets($this->_fh)) as $item) {  $a[$ind++] = (float)$item; } return $a; }
    public function readArrayOfString($separator = ' ', $indexFrom = 0) { $a = []; $ind = $indexFrom; foreach (explode($separator, fgets($this->_fh)) as $item) {  $a[$ind++] = $item; } return $a; }
}
/* Perform action N times. Can return values in array */
function ntimes($n, $func, $returnResults = false){ $a = []; for ($i = 1; $i <= $n; $i++) { $result = $func(); if ($returnResults) {  $a[$i] = $result; } } return $a;}
/* Integral. Keys preserved. By reference. */
function cumsum(&$a){ $sum = 0; foreach ($a as $k => $v) { $a[$k] += $sum; $sum = $a[$k]; }}
/* Difference. Keys preserved. By reference. */
function diff(&$a){ $prev = 0; foreach ($a as $k => $v) { $buf = $a[$k]; $a[$k] -= $prev; $prev = $buf; }}
function bitCount($n){ $cnt = 0; for ($j = $n; $j; $j >>= 1) { $cnt += $j & 1; } return $cnt;}
/*****************************************/
$ir = new InputReader();

/* TASK */

$ts = $ir->readInt();

for ($t=0; $t<$ts; $t++) {
	$s = $ir->readString();
	$cumsum = 0;

	if ($s[-1] !== 'B') {
		echo "NO".PHP_EOL;
		continue;
	}

	for ($i = 0; $i < strlen($s); $i++) {
		$cumsum += ($s[$i]=='A' ? 1 : -1);

		if ($cumsum < 0) {
			echo "NO".PHP_EOL;
			continue 2;
		}
	}

	echo "YES".PHP_EOL;
}


Vova has won $$$n$$$ trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as beautiful as possible — that means, to maximize the length of the longest such subsegment.Help Vova! Tell him the maximum possible beauty of the arrangement if he is allowed to do at most one swap.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of trophies. The second line contains $$$n$$$ characters, each of them is either G or S. If the $$$i$$$-th character is G, then the $$$i$$$-th trophy is a golden one, otherwise it's a silver trophy.

Print the maximum possible length of a subsegment of golden trophies, if Vova is allowed to do at most one swap.

NoteIn the first example Vova has to swap trophies with indices $$$4$$$ and $$$10$$$. Thus he will obtain the sequence "GGGGGGGSGS", the length of the longest subsegment of golden trophies is $$$7$$$. In the second example Vova can make no swaps at all. The length of the longest subsegment of golden trophies in the sequence is $$$4$$$. In the third example Vova cannot do anything to make the length of the longest subsegment of golden trophies in the sequence greater than $$$0$$$.


There are n knights sitting at the Round Table at an equal distance from each other. Each of them is either in a good or in a bad mood.Merlin, the wizard predicted to King Arthur that the next month will turn out to be particularly fortunate if the regular polygon can be found. On all vertices of the polygon knights in a good mood should be located. Otherwise, the next month will bring misfortunes.A convex polygon is regular if all its sides have same length and all his angles are equal. In this problem we consider only regular polygons with at least 3 vertices, i. e. only nondegenerated.On a picture below some examples of such polygons are present. Green points mean knights in a good mood. Red points mean ones in a bad mood.  King Arthur knows the knights' moods. Help him find out if the next month will be fortunate or not.

The first line contains number n, which is the number of knights at the round table (3 ≤ n ≤ 105). The second line contains space-separated moods of all the n knights in the order of passing them around the table. "1" means that the knight is in a good mood an "0" means that he is in a bad mood.

Print "YES" without the quotes if the following month will turn out to be lucky. Otherwise, print "NO".

<?php
class INPUT_HELP{
    public function read_array(){
        $a[0] = '';
        $j = 0;
        $input = fgets(STDIN);
        for ($i = 0; $i < strlen($input); $i++){
            if (preg_replace("/[0-9A-zА-я._-]/",null,$input[$i]) == false) {
                $a[$j] = $a[$j].$input[$i];
            } else {
                if ($a[$j] != '') {
                    ++$j;
                    $a[$j] = '';
                }
            }
        }
        return $a;
    }
    public function read_one(){
        $array = $this->read_array();
        return $array[0];
    }
}
?>
<?php
    $input_connect = new INPUT_HELP();
    $n = $input_connect->read_one();
    $a = $input_connect->read_array();
    for ($i = 0; $i < $n; $i++) {
        $num[$i] = $i;
    }
    for ($i = $n; $i < 2 * $n; $i++){
        $a[$i] = $a[$i - $n];
        $num[$i] = $num[$i - $n];
    }
    $h = -1;
    for ($j = 1; $j < $n; $j++){
        if ($n % $j != 0 || $n / $j < 3) continue;
        ++$h;
        $div[$h] = $j;
    }
    for ($i = 0; $i < $n; $i++){
        if ($a[$i] == 0) continue;
        for ($j = 0; $j <= $h; $j++){
            $k = $i + $div[$j];
            while ($a[$k] == 1 && $num[$k] != $i) $k += $div[$j];
            if ($num[$k] == $i) {
                echo "YES";
                die(0);
            }
        }
    }
    echo "NO";
?>

<?php

$RESULT = false;
$arr=array();
$n=(int)trim(fgets(STDIN));
$arr=explode(' ',trim(fgets(STDIN)));
$UBOUND = $n/2;

function check($i,$offset) {
    global $arr,$n;
    for ($k = $offset ; $k<$n ; $k+=$i) {
        if ($arr[$k]==0) return false;
    }
    return true;
}

for ($i = 1; $i < $UBOUND ;$i++) {
    if ($n%$i==0) {
        //$nodes = $n/$i;
        for ($j = 0 ; $j < $i; $j++) {
            if (check($i,$j)) {
                $RESULT = true;
                break 2;
            }
        }
    }
}
echo $RESULT ? 'YES' : 'NO';

?>

<?php
class INPUT_HELP{
    public function read_array(){
        $a[0] = '';
        $j = 0;
        $input = fgets(STDIN);
        for ($i = 0; $i < strlen($input); $i++){
            if (preg_replace("/[0-9A-zА-я._-]/",null,$input[$i]) == false) {
                $a[$j] = $a[$j].$input[$i];
            } else {
                if ($a[$j] != '') {
                    ++$j;
                    $a[$j] = '';
                }
            }
        }
        return $a;
    }
    public function read_one(){
        $array = $this->read_array();
        return $array[0];
    }
}
?>
<?php
    $input_connect = new INPUT_HELP();
    $n = $input_connect->read_one();
    $a = $input_connect->read_array();
    for ($i = 0; $i < $n; $i++) {
        $num[$i] = $i;
    }
    for ($i = $n; $i < 2 * $n; $i++){
        $a[$i] = $a[$i - $n];
        $num[$i] = $num[$i - $n];
    }
    $h = -1;
    for ($j = 1; $j < $n; $j++){
        if ($n % $j != 0 || $n / $j < 3) continue;
        ++$h;
        $div[$h] = $j;
    }
    for ($i = 0; $i < $n; $i++){
        if ($a[$i] == 0) continue;
        for ($j = 1; $j < $h; $j++){
            $k = $i + $div[$j];
            while ($a[$k] == 1 && $num[$k] != $i) $k += $div[$j];
            if ($num[$k] == $i) {
                echo "YES";
                die(0);
            }
        }
    }
    echo "NO";
?>

<?php
class INPUT_HELP{
    public function read_array(){
        $a[0] = '';
        $j = 0;
        $input = fgets(STDIN);
        for ($i = 0; $i < strlen($input); $i++){
            if (preg_replace("/[0-9A-zА-я._-]/",null,$input[$i]) == false) {
                $a[$j] = $a[$j].$input[$i];
            } else {
                if ($a[$j] != '') {
                    ++$j;
                    $a[$j] = '';
                }
            }
        }
        return $a;
    }
    public function read_one(){
        $array = $this->read_array();
        return $array[0];
    }
}
?>
<?php
    $input_connect = new INPUT_HELP();
    $n = $input_connect->read_one();
    $a = $input_connect->read_array();
    for ($i = 0; $i < $n; $i++) {
        $num[$i] = $i;
    }
    for ($i = $n; $i < 2 * $n; $i++){
        $a[$i] = $a[$i - $n];
        $num[$i] = $num[$i - $n];
    }
    $h = -1;
    for ($j = 1; $j < $n; $j++){
        if ($n % $j != 0 || $n / $j < 3) continue;
        ++$h;
        $div[$h] = $j;
    }
    for ($i = 0; $i < $n; $i++){
        if ($a[$i] == 0) continue;
        for ($j = 0; $j < $h; $j++){
            $k = $i + $div[$j];
            while ($a[$k] == 1 && $num[$k] != $i) $k += $div[$j];
            if ($num[$k] == $i) {
                echo "YES";
                die(0);
            }
        }
    }
    echo "NO";
?>

<?php
$arr=array();
$n=(int)trim(fgets(STDIN));
for ($i = 0; $i < $n ;$i++)
    fscanf(STDIN,'%d', $HZ[$i]);
$UBOUND = $n/2;

function check($i,$offset) {
    global $arr,$n;
    for ($k = $offset ; $k<$n ; $k+=$i) {
        if ($arr[$k]==0) return false;
    }
    return true;
}

for ($i = 1; $i < $UBOUND ;$i++) {
    if ($n%$i==0) {
        //$nodes = $n/$i;
        for ($j = 0 ; $j < $i; $j++) {
            if (check($i,$j)) {
                echo 'YES';
                die();
            }
        }
    }
}

echo 'NO';
?>


Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table $$$M$$$ with $$$n$$$ rows and $$$n$$$ columns such that $$$M_{ij}=a_i \cdot a_j$$$ where $$$a_1, \dots, a_n$$$ is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array $$$a_1, \dots, a_n$$$. Help Sasha restore the array!

The first line contains a single integer $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$), the size of the table.  The next $$$n$$$ lines contain $$$n$$$ integers each. The $$$j$$$-th number of the $$$i$$$-th line contains the number $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). The table has zeroes on the main diagonal, that is, $$$M_{ii}=0$$$.

In a single line print $$$n$$$ integers, the original array $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). It is guaranteed that an answer exists. If there are multiple answers, print any.


You came to the exhibition and one exhibit has drawn your attention. It consists of $$$n$$$ stacks of blocks, where the $$$i$$$-th stack consists of $$$a_i$$$ blocks resting on the surface.The height of the exhibit is equal to $$$m$$$. Consequently, the number of blocks in each stack is less than or equal to $$$m$$$.There is a camera on the ceiling that sees the top view of the blocks and a camera on the right wall that sees the side view of the blocks. Find the maximum number of blocks you can remove such that the views for both the cameras would not change.Note, that while originally all blocks are stacked on the floor, it is not required for them to stay connected to the floor after some blocks are removed. There is no gravity in the whole exhibition, so no block would fall down, even if the block underneath is removed. It is not allowed to move blocks by hand either.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$1 \le m \le 10^9$$$) — the number of stacks and the height of the exhibit. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the number of blocks in each stack from left to right.

Print exactly one integer — the maximum number of blocks that can be removed.

NoteThe following pictures illustrate the first example and its possible solution.Blue cells indicate removed blocks. There are $$$10$$$ blue cells, so the answer is $$$10$$$.


A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from  - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist.

The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0.

If the required point exists, output its coordinates, otherwise output -1.

<?php

list($a,$b,$c)=fscanf(STDIN,"%s%s%s");

function exeuclid($a,$b)
{
	if(bccomp($b,'0')==0)
		return array($a,'1','0');
	list($d,$x,$y)=exeuclid($b,bcmod($a,$b));
	return array($d,$y,$x-bcmul(bcdiv($a,$b),$y));
}

list($d,$x,$y)=exeuclid($a,$b);

if(bccomp(bcmod($c,$d),'0')!=0) {
	die("-1");
}

$mul=bcdiv($c,$d);

$wx=bcmul(bcsub('0',$x),$mul);
$wy=bcmul(bcsub('0',$y),$mul);

$MX=bcmul('5',bcpow('10','18'));

function bcabs($x) {
	if(bccomp($x,'0')<0)
		return bcsub('0',$x);
	return $x;
}

if(bccomp(bcabs($x),$MX)>0 || bccomp(bcabs($x),$MX)>0)
	die("-1");

echo $wx," ",$wy;

?>


Limak is a little polar bear. He loves connecting with other bears via social networks. He has n friends and his relation with the i-th of them is described by a unique integer ti. The bigger this value is, the better the friendship is. No two friends have the same value ti.Spring is starting and the Winter sleep is over for bears. Limak has just woken up and logged in. All his friends still sleep and thus none of them is online. Some (maybe all) of them will appear online in the next hours, one at a time.The system displays friends who are online. On the screen there is space to display at most k friends. If there are more than k friends online then the system displays only k best of them — those with biggest ti.Your task is to handle queries of two types:  "1 id" — Friend id becomes online. It's guaranteed that he wasn't online before.  "2 id" — Check whether friend id is displayed by the system. Print "YES" or "NO" in a separate line. Are you able to help Limak and answer all queries of the second type?

The first line contains three integers n, k and q (1 ≤ n, q ≤ 150 000, 1 ≤ k ≤ min(6, n)) — the number of friends, the maximum number of displayed online friends and the number of queries, respectively. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 109) where ti describes how good is Limak's relation with the i-th friend. The i-th of the following q lines contains two integers typei and idi (1 ≤ typei ≤ 2, 1 ≤ idi ≤ n) — the i-th query. If typei = 1 then a friend idi becomes online. If typei = 2 then you should check whether a friend idi is displayed. It's guaranteed that no two queries of the first type will have the same idi becuase one friend can't become online twice. Also, it's guaranteed that at least one query will be of the second type (typei = 2) so the output won't be empty.

For each query of the second type print one line with the answer — "YES" (without quotes) if the given friend is displayed and "NO" (without quotes) otherwise.

NoteIn the first sample, Limak has 4 friends who all sleep initially. At first, the system displays nobody because nobody is online. There are the following 8 queries:  "1 3" — Friend 3 becomes online.  "2 4" — We should check if friend 4 is displayed. He isn't even online and thus we print "NO".  "2 3" — We should check if friend 3 is displayed. Right now he is the only friend online and the system displays him. We should print "YES".  "1 1" — Friend 1 becomes online. The system now displays both friend 1 and friend 3.  "1 2" — Friend 2 becomes online. There are 3 friends online now but we were given k = 2 so only two friends can be displayed. Limak has worse relation with friend 1 than with other two online friends (t1 < t2, t3) so friend 1 won't be displayed  "2 1" — Print "NO".  "2 2" — Print "YES".  "2 3" — Print "YES".

<?php
list ($n, $k, $q) = explode(" ", trim(fgets(STDIN)));

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

$online = [];

for ($i = 0; $i < $q; $i++) {
  list ($type, $id) = explode(" ", trim(fgets(STDIN)));

  if ($type == 1) {
    $online[$id] = $t[$id - 1];
    arsort($online);
    if (count($online) > $k) {
      array_pop($online);
    }
  } else {
    echo isset($online[$id]) ? "YES\n" : "NO\n";
  }
}

<?
$stdin = fopen('php://stdin', 'r');
$a = fgets($stdin);
$t = explode(" ", $a);
$n = trim($t[0]);
$k = trim($t[1]);
$q = trim($t[2]);
$a = fgets($stdin);
$friends = explode(" ", $a);
$show = array();

$stdout = fopen('php://stdout', 'w');
$onlines = 0;
$online = array();
for($i = 0; $i < $q; $i++){
    $a = fgets($stdin);
    $t = explode(" ", $a);
    $type = trim($t[0]);//type
    $id = trim($t[1]);//id
    if($type == 1){

        if($onlines < $k){
            $online[$onlines][0] = $id;
            $online[$onlines][1] = $friends[$id - 1];
            $show[$id] = "YES";
            $onlines++;
        }else{
            $min = -1;
            for($j = 0; $j < $onlines; $j++){
                if($online[$j][1] < $friends[$id - 1] and ($online[$j][1] < $online[$min][1] or $min == -1)) $min = $j;
            }

            if($min != -1){
                $show[$online[$min][0]] = "NO";
                $show[$id] = "YES";
                $online[$min][0] = $id;
                $online[$min][1] = $friends[$id - 1];
            }
        }
    }else{
        if($show[$id]) fwrite($stdout, $show[$id]."\n"); else fwrite($stdout, "NO\n");
    }
}

fclose($stdout);

?>

<?
$k=1;
$online=array();
$handle=fopen("php://stdin",'r');

$vars=explode(' ',trim(fgets($handle)));

$rep2=explode(' ',trim(fgets($handle)));

array_unshift($rep2, 0);

for($i=1;$i<=$vars[2];$i++) {
	$tokens[$i]=explode(' ',trim(fgets($handle)));
}

for($i=1;$i<=$vars[2];$i++) {
	if($tokens[$i][0]==1) {
		if(array_search($tokens[$i][1],$online)===FALSE) {
			if(count($online)==$vars[1]) {
			if($rep2[$tokens[$i][1]]>$rep2[$online[0]]) $online[0]=$tokens[$i][1];
			} else {
			array_push($online, $tokens[$i][1]);
			}
			//Ёбаная сортировка
			for($z=0;$z<count($online);$z++)
				for($y=$z+1;$y<count($online);$y++)
					if($rep2[$online[$y]]<$rep2[$online[$z]])
						list($online[$z], $online[$y]) = array($online[$y], $online[$z]);
			//
		}
	} else {
		if(array_search($tokens[$i][1],$online)!==FALSE) {
			echo "YES".PHP_EOL;
		} else echo "NO".PHP_EOL;
	}
}
?>

<?
$k=1;
$id_session=1;
$online=array();
$handle=fopen("php://stdin",'r');
$l1=trim(fgets($handle));

$vars=explode(' ',$l1);

$l2=trim(fgets($handle));

$rep2=explode(' ',$l2);

for($i=1;$i<=$vars[2];$i++) {
	$tokens[$i]=explode(' ',trim(fgets($handle)));
}

for($i=1;$i<=$vars[0];$i++) {
	$friend[$i]=$rep2[$i-1];
}

for($i=1;$i<=$vars[2];$i++) {
	if($tokens[$i][0]==1) {
		if(array_search($tokens[$i][1],$online)===FALSE) {
			if(count($online)==$vars[1]) {
			if($friend[$tokens[$i][1]]>$friend[$online[0]]) $online[0]=$tokens[$i][1];
			} else {
			array_push($online, $tokens[$i][1]);
			}
			//Ёбаная сортировка
			for($z=0;$z<count($online);$z++)
				for($y=$z+1;$y<count($online);$y++)
					if($friend[$online[$y]]<$friend[$online[$z]])
						list($online[$z], $online[$y]) = array($online[$y], $online[$z]);
			//
		}
	} else {
		if(array_search($tokens[$i][1],$online)!==FALSE) {
			echo "YES".PHP_EOL;
		} else echo "NO".PHP_EOL;
	}
}
?>

<?
$k=1;
$id_session=1;
$online=array();
$handle=fopen("php://stdin",'r');
$l1=trim(fgets($handle));

$vars=explode(' ',$l1);

$l2=trim(fgets($handle));

$rep2=explode(' ',$l2);

for($i=1;$i<=$vars[2];$i++) {
	$tokens[$i]=explode(' ',trim(fgets($handle)));
}

for($i=1;$i<=$vars[0];$i++) {
	$friend[$i]["online"]=0;
	$friend[$i]["rep"]=$rep2[$i-1];
}

for($i=1;$i<=$vars[2];$i++) {
	if($tokens[$i][0]==1) {
		if(array_search($tokens[$i][1],$online)===FALSE) {
			if(count($online)==$vars[1]) {
			if($friend[$tokens[$i][1]]["rep"]>$friend[$online[0]]["rep"]) $online[0]=$tokens[$i][1];
			} else {
			array_push($online, $tokens[$i][1]);
			}
			//Ёбаная сортировка
			for($z=0;$z<count($online);$z++) {
				$xer=$online[$z];
				for($y=$z+1;$y<count($online);$y++) {
					if($friend[$online[$y]]["rep"]<$friend[$online[$z]]["rep"])
						list($online[$z], $online[$y]) = array($online[$y], $online[$z]);
				}
			}
			//
		}
	} else {
		if(array_search($tokens[$i][1],$online)!==FALSE) {
			echo "YES".PHP_EOL;
		} else echo "NO".PHP_EOL;
	}
}
?>

<?
$k=1;
$id_session=1;
$online=array();
$handle=fopen("php://stdin",'r');
$l1=trim(fgets($handle));

$vars=explode(' ',$l1);

$l2=trim(fgets($handle));

$rep2=explode(' ',$l2);

array_unshift($rep2, 0);

for($i=1;$i<=$vars[2];$i++) {
	$tokens[$i]=explode(' ',trim(fgets($handle)));
}

for($i=1;$i<=$vars[2];$i++) {
	if($tokens[$i][0]==1) {
		if(array_search($tokens[$i][1],$online)===FALSE) {
			if(count($online)==$vars[1]) {
			if($rep2[$tokens[$i][1]]>$rep2[$online[0]]) $online[0]=$tokens[$i][1];
			} else {
			array_push($online, $tokens[$i][1]);
			}
			//Ёбаная сортировка
			for($z=0;$z<count($online);$z++)
				for($y=$z+1;$y<count($online);$y++)
					if($rep2[$online[$y]]<$rep2[$online[$z]])
						list($online[$z], $online[$y]) = array($online[$y], $online[$z]);
			//
		}
	} else {
		if(array_search($tokens[$i][1],$online)!==FALSE) {
			echo "YES".PHP_EOL;
		} else echo "NO".PHP_EOL;
	}
}
?>

<?
$k=1;
$id_session=1;
$online=array();
$handle=fopen("php://stdin",'r');
$l1=trim(fgets($handle));

$vars=explode(' ',$l1);

$l2=trim(fgets($handle));

$rep2=explode(' ',$l2);

for($i=1;$i<=$vars[2];$i++) {
	$tokens[$i]=explode(' ',trim(fgets($handle)));
}

for($i=1;$i<=$vars[0];$i++) {
	$friend[$i]["online"]=0;
	$friend[$i]["rep"]=$rep2[$i-1];
}

for($i=1;$i<=$vars[2];$i++) {
	if($tokens[$i][0]==1) {
		if(array_search($tokens[$i][1],$online)===FALSE) {
			if(count($online)==$vars[1]) {
			if($friend[$tokens[$i][1]]["rep"]>$friend[$online[0]]["rep"]) $online[0]=$tokens[$i][1];
			} else {
			array_push($online, $tokens[$i][1]);
			}
			//Ёбаная сортировка
			for($z=0;$z<count($online);$z++)
				for($y=$z+1;$y<count($online);$y++)
					if($friend[$online[$y]]["rep"]<$friend[$online[$z]]["rep"])
						list($online[$z], $online[$y]) = array($online[$y], $online[$z]);
			//
		}
	} else {
		if(array_search($tokens[$i][1],$online)!==FALSE) {
			echo "YES".PHP_EOL;
		} else echo "NO".PHP_EOL;
	}
}
?>

<?
$stdin = fopen('php://stdin', 'r');
$a = fgets($stdin);
$t = explode(" ", $a);
$n = trim($t[0]);
$k = trim($t[1]);
$q = trim($t[2]);
$a = fgets($stdin);
$friends = explode(" ", $a);
$show = array();

$stdout = fopen('php://stdout', 'w');
$onlines = 0;
$online = array();
for($i = 0; $i < $q; $i++){
    $a = fgets($stdin);
    $t = explode(" ", $a);
    $type = trim($t[0]);//type
    $id = trim($t[1]);//id
    if($type == 1){

        if($onlines < $k){
            $online[$onlines][0] = $id;
            $online[$onlines][1] = $friends[$id - 1];
            $show[$id] = "YES";
            $onlines++;
        }else{
            $min = -1;
            for($j = 0; $j < $onlines; $j++){
                if($online[$j][1] < $friends[$id - 1] and ($online[$j][1] < $min[1] or $min == -1)) $min = $online[$j];
            }

            if($min != -1){
                $show[$min[0]] = "NO";
                $show[$id] = "YES";
                $online[$min][0] = $id;
                $online[$min][1] = $friends[$id - 1];
            }
        }
    }else{
        if($show[$id]) fwrite($stdout, $show[$id]."\n"); else fwrite($stdout, "NO\n");
    }
}

fclose($stdout);

?>

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

$a = fgets($stdin);
$t = explode(" ", $a);
$n = trim($t[0]);//druzya
$k = trim($t[1]);//okno
$q = trim($t[2]);//zaprosy
$a = fgets($stdin);
$friends = explode(" ", $a);
$show = array();

$stdout = fopen('php://stdout', 'w');
$onlines = 0;
$online = array();
for($i = 0; $i < $q; $i++){
    $a = fgets($stdin);
    $t = explode(" ", $a);
    $type = trim($t[0]);//type
    $id = trim($t[1]);//id
    if($type == 1){
        $min = -1;
        for($j = 0; $j < $onlines; $j++){
            if($online[$j] < $friends[$id] and ($online[$j] < $online[$min] or $min == -1)) $min = $j;
        }
        if($min != -1){
            $show[$j] = "FALSE";
            $show[$id] = "TRUE";
            $online[$j] = $friends[$id];
        }else{
            if($onlines < $k){
                $online[$onlines] = $friends[$id];
                $show[$id] = "TRUE";
                $onlines++;
            }
        }
    }else{
        if($show[$id]) fwrite($stdout, $show[$id]."\n"); else fwrite($stdout, "FALSE\n");
    }
}

fclose($stdout);

?>

<?
$k=1;
$id_session=1;
$online=array();
$handle=fopen("php://stdin",'r');
$l1=trim(fgets($handle));

$vars=explode(' ',$l1);

$l2=trim(fgets($handle));

$rep2=explode(' ',$l2);

for($i=1;$i<=$vars[2];$i++) {
	$tokens[$i]=explode(' ',trim(fgets($handle)));
}

for($i=1;$i<=$vars[0];$i++) {
	$friend[$i]["online"]=0;
	$friend[$i]["rep"]=$rep2[$i-1];
}

for($i=1;$i<=$vars[2];$i++) {
	if($tokens[$i][0]==1) {
		if(array_search($tokens[$i][1],$online)===FALSE) {
			if(count($online)==$vars[1]) {
			if($friend[$tokens[$i][1]]["rep"]>$friend[$online[0]]["rep"]) $online[0]=$tokens[$i][1];
			} else {
			array_push($online, $tokens[$i][1]);
			}
			//Ёбаная сортировка
			for($z=0;$z<count($online);$z++) {
				$xer=$online[$z];
				for($y=$z+1;$y<count($online);$y++) {
					if($friend[$online[$y]]["rep"]<$friend[$online[$z]]["rep"]) {
						list($online[$z], $online[$y]) = array($online[$y], $online[$z]);
						$z++;
					}
				}
			}
			//
		}
	} else {
		if(array_search($tokens[$i][1],$online)!==FALSE) {
			echo "YES".PHP_EOL;
		} else echo "NO".PHP_EOL;
	}
}
?>


Chilly Willy loves playing with numbers. He only knows prime numbers that are digits yet. These numbers are 2, 3, 5 and 7. But Willy grew rather bored of such numbers, so he came up with a few games that were connected with them.Chilly Willy wants to find the minimum number of length n, such that it is simultaneously divisible by all numbers Willy already knows (2, 3, 5 and 7). Help him with that.A number's length is the number of digits in its decimal representation without leading zeros.

A single input line contains a single integer n (1 ≤ n ≤ 105).

Print a single integer — the answer to the problem without leading zeroes, or "-1" (without the quotes), if the number that meet the problem condition does not exist.

<?php
list($n)=explode(" ",trim(fgets(STDIN)));
$n=  pow(10, $n-1);
if ($n<999) print -1;else
{
$ra=ceil($n/210)*210;
print $ra;}
?>


Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.The stones always fall to the center of Liss's interval. When Liss occupies the interval [k - d, k + d] and a stone falls to k, she will escape to the left or to the right. If she escapes to the left, her new interval will be [k - d, k]. If she escapes to the right, her new interval will be [k, k + d].You are given a string s of length n. If the i-th character of s is "l" or "r", when the i-th stone falls Liss will escape to the left or to the right, respectively. Find the sequence of stones' numbers from left to right after all the n stones falls.

The input consists of only one line. The only line contains the string s (1 ≤ |s| ≤ 106). Each character in s will be either "l" or "r".

Output n lines — on the i-th line you should print the i-th stone's number from the left.

NoteIn the first example, the positions of stones 1, 2, 3, 4, 5 will be , respectively. So you should print the sequence: 3, 5, 4, 2, 1.

<?php

function cin()
{
	$row = explode(" ", trim(fgets(STDIN)));
	return $row[0];
}
$str = cin();
$length = strlen($str);
for($i = 0; $i < $length; ++$i)
	if($str[$i] == 'r') echo ($i + 1)."\n";
for($i = $length - 1; $i >= 0; --$i)
	if($str[$i] == 'l') echo ($i + 1)."\n";

?>


You've got a list of program warning logs. Each record of a log stream is a string in this format:  "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the year of 2012. String "HH:MM:SS" determines a correct time in the 24 hour format.The described record of a log stream means that at a certain time the record has got some program warning (string "MESSAGE" contains the warning's description).Your task is to print the first moment of time, when the number of warnings for the last n seconds was not less than m.

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 10000). The second and the remaining lines of the input represent the log stream. The second line of the input contains the first record of the log stream, the third line contains the second record and so on. Each record of the log stream has the above described format. All records are given in the chronological order, that is, the warning records are given in the order, in which the warnings appeared in the program.  It is guaranteed that the log has at least one record. It is guaranteed that the total length of all lines of the log stream doesn't exceed 5·106 (in particular, this means that the length of some line does not exceed 5·106 characters). It is guaranteed that all given dates and times are correct, and the string 'MESSAGE" in all records is non-empty.

If there is no sought moment of time, print -1. Otherwise print a string in the format "2012-MM-DD HH:MM:SS" (without the quotes) — the first moment of time when the number of warnings for the last n seconds got no less than m.


For a given array $$$a$$$ consisting of $$$n$$$ integers and a given integer $$$m$$$ find if it is possible to reorder elements of the array $$$a$$$ in such a way that $$$\sum_{i=1}^{n}{\sum_{j=i}^{n}{\frac{a_j}{j}}}$$$ equals $$$m$$$? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for example, $$$\frac{5}{2}=2.5$$$.

The first line contains a single integer $$$t$$$ — the number of test cases ($$$1 \le t \le 100$$$). The test cases follow, each in two lines. The first line of a test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$). The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^6$$$) — the elements of the array.

For each test case print "YES", if it is possible to reorder the elements of the array in such a way that the given formula gives the given value, and "NO" otherwise.

NoteIn the first test case one of the reorders could be $$$[1, 2, 5]$$$. The sum is equal to $$$(\frac{1}{1} + \frac{2}{2} + \frac{5}{3}) + (\frac{2}{2} + \frac{5}{3}) + (\frac{5}{3}) = 8$$$. The brackets denote the inner sum $$$\sum_{j=i}^{n}{\frac{a_j}{j}}$$$, while the summation of brackets corresponds to the sum over $$$i$$$.

<?php
function read(){
    return explode(" ",trim(fgets(STDIN)));
}
list($t)=read();
for($i=0; $i<$t;$i++){
    list($n,$m)=read();
    $arr=read();
    $ans=0;
    for($j=0;$j<count($arr);$j++){
        $ans+=$arr[$j];
    }
    if($ans==$m){
        print "YES\n";
    }else{
        print("NO\n");
    }
}


You are given two integers $$$a$$$ and $$$b$$$. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by $$$1$$$; during the second operation you choose one of these numbers and increase it by $$$2$$$, and so on. You choose the number of these operations yourself.For example, if $$$a = 1$$$ and $$$b = 3$$$, you can perform the following sequence of three operations:   add $$$1$$$ to $$$a$$$, then $$$a = 2$$$ and $$$b = 3$$$;  add $$$2$$$ to $$$b$$$, then $$$a = 2$$$ and $$$b = 5$$$;  add $$$3$$$ to $$$a$$$, then $$$a = 5$$$ and $$$b = 5$$$. Calculate the minimum number of operations required to make $$$a$$$ and $$$b$$$ equal.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum numbers of operations required to make $$$a$$$ and $$$b$$$ equal.

NoteFirst test case considered in the statement.In the second test case integers $$$a$$$ and $$$b$$$ are already equal, so you don't need to perform any operations.In the third test case you have to apply the first, the second, the third and the fourth operation to $$$b$$$ ($$$b$$$ turns into $$$20 + 1 + 2 + 3 + 4 = 30$$$).

<?php
/**
 * Created by PhpStorm.
 * User: wanghaixia01
 * Date: 2019/12/30
 * Time: 11:10
 */

class BAandB
{
    public function main(){
        $num = trim(fgets(STDIN));//接收用户输入
        for ($i=0; $i < $num; $i++){
            $arr = explode(" ", trim(fgets(STDIN)));//接收用户输入
            $steps = $this->compMinSteps($arr[0], $arr[1]);
            fwrite(STDOUT, $steps."\n");
        }
    }

    public function compMinSteps($num1, $num2){
        if($num1 == $num2){
            return 0;
        }
        $diff = abs($num1-$num2);
        $i = 1;
        while(true){
            $sum = $i * ($i + 1) / 2;
            if($sum % 2 == $diff % 2 && $sum >= $diff){
                break;
            }
            $i++;
        }
        return $i;
    }
}
$nyg = new BAandB();
$b = $nyg->main();

<?php
/**
 * Created by PhpStorm.
 * User: wanghaixia01
 * Date: 2019/12/30
 * Time: 11:10
 */

class BAandB
{
    public function main(){
        $num = trim(fgets(STDIN));//接收用户输入
        for ($i=0; $i < $num; $i++){
            $line = trim(fgets(STDIN));//接收用户输入
            $arr  = explode(" ", $line);
            $steps = $this->compMinSteps($arr[0], $arr[1]);
            fwrite(STDOUT, $steps."\n");
        }
    }
    //每执行一步就会加1
    public function compMinSteps($num1, $num2){
        if($num1 == $num2){
            return 0;
        }
        if($num1 > $num2){
            $minNum = $num2;
            $maxNum = $num1;
        }else{
            $minNum = $num1;
            $maxNum = $num2;
        }
        $i = 1;
        while($minNum != $maxNum){
            if($minNum + $i < $maxNum){
                $minNum += $i;
            }elseif($minNum + $i > $maxNum){
                $maxNum += $i;
            }elseif($minNum + $i == $maxNum){
                break;
            }
            $i++;
        }
        return $i;
    }
}
$nyg = new BAandB();
$b = $nyg->main();

<?php
/**
 * Created by PhpStorm.
 * User: wanghaixia01
 * Date: 2019/12/30
 * Time: 11:10
 */

class BAandB
{
    public function main(){
        $num = trim(fgets(STDIN));//接收用户输入
        $steps = array();
        for ($i=0; $i < $num; $i++){
            $line = trim(fgets(STDIN));//接收用户输入
            $arr  = explode(" ", $line);
            $steps[] = $this->compMinSteps($arr[0], $arr[1]);
        }
        for ($i = 0; $i < $num; $i++){
            fwrite(STDOUT, $steps[$i]."\n");
        }
    }
    //每执行一步就会加1
    public function compMinSteps($num1, $num2){
        if($num1 == $num2){
            return 0;
        }
        if($num1 > $num2){
            $minNum = $num2;
            $maxNum = $num1;
        }else{
            $minNum = $num1;
            $maxNum = $num2;
        }
        $i = 1;
        while($minNum != $maxNum){
            if($minNum + $i < $maxNum){
                $minNum += $i;
            }elseif($minNum + $i > $maxNum){
                $maxNum += $i;
            }elseif($minNum + $i == $maxNum){
                break;
            }
            $i++;
        }
        return $i;
    }
}
//$nyg = new BAandB();
//$b = $nyg->main();


Very soon Berland will hold a School Team Programming Olympiad. From each of the m Berland regions a team of two people is invited to participate in the olympiad. The qualifying contest to form teams was held and it was attended by n Berland students. There were at least two schoolboys participating from each of the m regions of Berland. The result of each of the participants of the qualifying competition is an integer score from 0 to 800 inclusive.The team of each region is formed from two such members of the qualifying competition of the region, that none of them can be replaced by a schoolboy of the same region, not included in the team and who received a greater number of points. There may be a situation where a team of some region can not be formed uniquely, that is, there is more than one school team that meets the properties described above. In this case, the region needs to undertake an additional contest. The two teams in the region are considered to be different if there is at least one schoolboy who is included in one team and is not included in the other team. It is guaranteed that for each region at least two its representatives participated in the qualifying contest.Your task is, given the results of the qualifying competition, to identify the team from each region, or to announce that in this region its formation requires additional contests.

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 10 000, n ≥ 2m) — the number of participants of the qualifying contest and the number of regions in Berland. Next n lines contain the description of the participants of the qualifying contest in the following format: Surname (a string of length from 1 to 10 characters and consisting of large and small English letters), region number (integer from 1 to m) and the number of points scored by the participant (integer from 0 to 800, inclusive). It is guaranteed that all surnames of all the participants are distinct and at least two people participated from each of the m regions. The surnames that only differ in letter cases, should be considered distinct.

Print m lines. On the i-th line print the team of the i-th region — the surnames of the two team members in an arbitrary order, or a single character "?" (without the quotes) if you need to spend further qualifying contests in the region.

5 2
Ivanov 1 763
Andreev 2 800
Petrov 1 595
Sidorov 1 790
Semenov 2 503

5 2
Ivanov 1 800
Andreev 2 763
Petrov 1 800
Sidorov 1 800
Semenov 2 503

NoteIn the first sample region teams are uniquely determined.In the second sample the team from region 2 is uniquely determined and the team from region 1 can have three teams: "Petrov"-"Sidorov", "Ivanov"-"Sidorov", "Ivanov" -"Petrov", so it is impossible to determine a team uniquely.

<?php
$stdin = explode(' ', trim(fgets(STDIN)));
$people = $stdin[0];
$reg = $stdin[1];

$comands = array();

for ($i = 0; $i < $people; $i++) {
    $child = explode(' ', trim(fgets(STDIN)));
    $child_fio = $child[0];
    $child_reg = $child[1];
    $child_rang= $child[2];

    $top1 = $comands[$child_reg]['top1']['rang'] ? $comands[$child_reg]['top1']['rang'] : 0;
    $top2 = $comands[$child_reg]['top2']['rang'] ? $comands[$child_reg]['top2']['rang'] : 0;
    $comands[$child_reg][$child_rang] += 1;
    if ($child_rang >= $top1) {
        $comands[$child_reg]['top2']['rang'] = $top1;
        $comands[$child_reg]['top2']['fio'] = $comands[$child_reg]['top1']['fio'];
        $comands[$child_reg]['top1']['rang'] = $child_rang;
        $comands[$child_reg]['top1']['fio'] = $child_fio;
    } else if ($child_rang >= $top2) {
        $comands[$child_reg]['top2']['rang'] = $child_rang;
        $comands[$child_reg]['top2']['fio'] = $child_fio;
    }
}
$result = array();
for ($j = 1; $j <= $reg; $j++) {

    if ($comands[$j][$comands[$j]['top1']['rang']] > 2) {
        echo "?\n";
    } else if ( $comands[$j][$comands[$j]['top1']['rang']] == 2) {
        echo $comands[$j]['top1']['fio'] . ' ' . $comands[$j]['top2']['fio'] . "\n";
    } else if ($comands[$j][$comands[$j]['top2']['rang']] == 1 ) {
        echo $comands[$j]['top1']['fio'] . ' ' . $comands[$j]['top2']['fio'] . "\n";
    } else {
        echo "?\n";
    }
}

?>

<?php
$stdin = explode(' ', trim(fgets(STDIN)));
$people = $stdin[0];
$reg = $stdin[1];

$comands = array();

for ($i = 0; $i < $people; $i++) {
    $child = explode(' ', trim(fgets(STDIN)));
    $child_fio = $child[0];
    $child_reg = $child[1];
    $child_rang= $child[2];

    if (!isset($comands[$child_reg])) {

        $comands[$child_reg] = array('can' => 1, 'users' => array(0 => $child));
    } else {
        if (count($comands[$child_reg]['users']) == 1) {
            $comands[$child_reg]['users'][] = $child;

        } else {
            if ($comands[$child_reg]['can'] == 1) {

                $rang_1 = $comands[$child_reg]['users'][0][2] + $child_rang;
                $rang_2 = $comands[$child_reg]['users'][1][2] + $child_rang;
                if ($rang_1 == $rang_2 && $rang_1 != 1600) {
                    $comands[$child_reg]['can'] = 0;
                } else if ($rang_1 >= $rang_2) {
                    $comands[$child_reg]['users'][1] = $child;
                } else {
                    $comands[$child_reg]['users'][0] = $child;
                }

            }

        }
    }

}
$result = array();
for ($j = 1; $j <= $reg; $j++) {
    if ($comands[$j]['can']) {
        $result[] = $comands[$j]['users'][0][0] . ' ' . $comands[$j]['users'][1][0];
    } else {
       $result[] = '?';
    }
}

echo implode('
', $result);

?>

<?php
$stdin = explode(' ', trim(fgets(STDIN)));
$people = $stdin[0];
$reg = $stdin[1];

$comands = array();

for ($i = 0; $i < $people; $i++) {
    $child = explode(' ', trim(fgets(STDIN)));
    $child_fio = $child[0];
    $child_reg = $child[1];
    $child_rang= $child[2];

    if (!isset($comands[$child_reg])) {

        $comands[$child_reg] = array('can' => 1, 'users' => array(0 => $child));
    } else {
        if (count($comands[$child_reg]['users']) == 1) {
            $comands[$child_reg]['users'][] = $child;

        } else {
            if ($comands[$child_reg]['can'] == 1) {

                $rang_1 = $comands[$child_reg]['users'][0][2] + $child_rang;
                $rang_2 = $comands[$child_reg]['users'][1][2] + $child_rang;
                if ($rang_1 == $rang_2) {
                    $comands[$child_reg]['can'] = 0;
                } else if ($rang_1 > $rang_2) {
                    $comands[$child_reg]['users'][1] = $child;
                } else {
                    $comands[$child_reg]['users'][0] = $child;
                }

            }

        }
    }

}
$result = array();
for ($j = 1; $j <= $reg; $j++) {
    if ($comands[$j]['can']) {
        $result[] = $comands[$j]['users'][0][0] . ' ' . $comands[$j]['users'][1][0];
    } else {
       $result[] = '?';
    }
}

echo implode('
', $result);

<?php
$stdin = explode(' ', trim(fgets(STDIN)));
$people = $stdin[0];
$reg = $stdin[1];

$comands = array();

for ($i = 0; $i < $people; $i++) {
    $child = explode(' ', trim(fgets(STDIN)));
    $child_fio = $child[0];
    $child_reg = $child[1];
    $child_rang= $child[2];

    $top1 = $comands[$child_reg]['top1']['rang'] ? $comands[$child_reg]['top1']['rang'] : 0;
    $top2 = $comands[$child_reg]['top2']['rang'] ? $comands[$child_reg]['top2']['rang'] : 0;

    $comands[$child_reg][$child_rang] += 1;
    if ($child_rang >= $top1) {
        $comands[$child_reg]['top2']['rang'] = $top1;
        $comands[$child_reg]['top2']['fio'] = $comands[$child_reg]['top1']['fio'];
        $comands[$child_reg]['top1']['rang'] = $child_rang;
        $comands[$child_reg]['top1']['fio'] = $child_fio;
    } else if ($comands[$child_reg][$child_rang] >= $top2) {
        $comands[$child_reg]['top2'] = $comands[$child_reg][$child_rang];
    }
}
$result = array();
for ($j = 1; $j <= $reg; $j++) {
    if ($comands[$j][$comands[$j]['top1']['rang']] > 2) {
        echo "?\n";
    } else if ( $comands[$j][$comands[$j]['top1']['rang']] == 2) {
        echo $comands[$j]['top1']['fio'] . ' ' . $comands[$j]['top2']['fio'] . "\n";
    } else if ($comands[$j][$comands[$j]['top2']['rang']] == 1 ) {
        echo $comands[$j]['top1']['fio'] . ' ' . $comands[$j]['top2']['fio'] . "\n";
    } else {
        echo "?\n";
    }
}

?>

<?php
$stdin = explode(' ', trim(fgets(STDIN)));
$people = $stdin[0];
$reg = $stdin[1];

$comands = array();

for ($i = 0; $i < $people; $i++) {
    $child = explode(' ', trim(fgets(STDIN)));
    $child_fio = $child[0];
    $child_reg = $child[1];
    $child_rang= $child[2];

    if (!isset($comands[$child_reg])) {

        $comands[$child_reg] = array('can' => 1, 'users' => array(0 => $child));
    } else {
        if (count($comands[$child_reg]['users']) == 1) {
            $comands[$child_reg]['users'][] = $child;

        } else {
            if ($comands[$child_reg]['can'] == 1) {

                $rang_1 = $comands[$child_reg]['users'][0][2] + $child_rang;
                $rang_2 = $comands[$child_reg]['users'][1][2] + $child_rang;
                if ($rang_1 == $rang_2) {
                    $comands[$child_reg]['can'] = 0;
                } else if ($rang_1 > $rang_2) {
                    $comands[$child_reg]['users'][1] = $child;
                } else {
                    $comands[$child_reg]['users'][0] = $child;
                }

            }

        }
    }

}

for ($j = 1; $j <= $reg; $j++) {
    if ($comands[$j]['can']) {
        echo $comands[$j]['users'][0][0] . ' ' . $comands[$j]['users'][1][0];
    } else {
        echo '?';
    }
}

?>


You are given a permutation of length $$$n$$$. Recall that the permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2, 3, 1, 5, 4]$$$ is a permutation, but $$$[1, 2, 2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1, 3, 4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).You can perform at most $$$n-1$$$ operations with the given permutation (it is possible that you don't perform any operations at all). The $$$i$$$-th operation allows you to swap elements of the given permutation on positions $$$i$$$ and $$$i+1$$$. Each operation can be performed at most once. The operations can be performed in arbitrary order.Your task is to find the lexicographically minimum possible permutation obtained by performing some of the given operations in some order.You can see the definition of the lexicographical order in the notes section.You have to answer $$$q$$$ independent test cases.For example, let's consider the permutation $$$[5, 4, 1, 3, 2]$$$. The minimum possible permutation we can obtain is $$$[1, 5, 2, 4, 3]$$$ and we can do it in the following way:  perform the second operation (swap the second and the third elements) and obtain the permutation $$$[5, 1, 4, 3, 2]$$$;  perform the fourth operation (swap the fourth and the fifth elements) and obtain the permutation $$$[5, 1, 4, 2, 3]$$$;  perform the third operation (swap the third and the fourth elements) and obtain the permutation $$$[5, 1, 2, 4, 3]$$$.  perform the first operation (swap the first and the second elements) and obtain the permutation $$$[1, 5, 2, 4, 3]$$$; Another example is $$$[1, 2, 4, 3]$$$. The minimum possible permutation we can obtain is $$$[1, 2, 3, 4]$$$ by performing the third operation (swap the third and the fourth elements).

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of test cases. Then $$$q$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the permutation. The second line of the test case contains $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ — the given permutation.

For each test case, print the answer on it — the lexicograhically minimum possible permutation obtained by performing some of the given operations in some order.

NoteRecall that the permutation $$$p$$$ of length $$$n$$$ is lexicographically less than the permutation $$$q$$$ of length $$$n$$$ if there is such index $$$i \le n$$$ that for all $$$j$$$ from $$$1$$$ to $$$i - 1$$$ the condition $$$p_j = q_j$$$ is satisfied, and $$$p_i < q_i$$$. For example:  $$$p = [1, 3, 5, 2, 4]$$$ is less than $$$q = [1, 3, 5, 4, 2]$$$ (such $$$i=4$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$),  $$$p = [1, 2]$$$ is less than $$$q = [2, 1]$$$ (such $$$i=1$$$ exists, that $$$p_i < q_i$$$ and for each $$$j < i$$$ holds $$$p_j = q_j$$$).


You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time independently). You can place tile in the grid at any position, the only condition is that tiles (and tile parts) should not overlap. Your goal is to proceed all given figures and avoid crossing at any time.

The only line contains a string $$$s$$$ consisting of zeroes and ones ($$$1 \le |s| \le 1000$$$). Zero describes vertical tile, one describes horizontal tile.

Output $$$|s|$$$ lines — for each tile you should output two positive integers $$$r,c$$$, not exceeding $$$4$$$, representing numbers of smallest row and column intersecting with it. If there exist multiple solutions, print any of them.

NoteFollowing image illustrates the example after placing all three tiles:    Then the first row is deleted:


For his birthday, Kevin received the set of pairwise distinct numbers $$$1, 2, 3, \ldots, n$$$ as a gift.He is going to arrange these numbers in a way such that the minimum absolute difference between two consecutive numbers be maximum possible. More formally, if he arranges numbers in order $$$p_1, p_2, \ldots, p_n$$$, he wants to maximize the value $$$$$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert,$$$$$$ where $$$|x|$$$ denotes the absolute value of $$$x$$$.Help Kevin to do that.

Each test consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The only line of each test case contains an integer $$$n$$$ ($$$2 \le n \leq 1\,000$$$) — the size of the set.

For each test case print a single line containing $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) describing the arrangement that maximizes the minimum absolute difference of consecutive elements.  Formally, you have to print a permutation $$$p$$$ which maximizes the value $$$\min \limits_{i=1}^{n - 1} \lvert p_{i + 1} - p_i \rvert$$$. If there are multiple optimal solutions, print any of them.

NoteIn the first test case the minimum absolute difference of consecutive elements equals $$$\min \{\lvert 4 - 2 \rvert, \lvert 1 - 4 \rvert, \lvert 3 - 1 \rvert \} = \min \{2, 3, 2\} = 2$$$. It's easy to prove that this answer is optimal.In the second test case each permutation of numbers $$$1, 2, 3$$$ is an optimal answer. The minimum absolute difference of consecutive elements equals to $$$1$$$.

<?php

//[$a,$b] = array_map('intval', explode(' ', trim(fgets(STDIN))));
//[$s] = explode(' ', trim(fgets(STDIN)));
//$a = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$h = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$mod = 998244353;
//$mod = 1000000007;
//$alpha = "abcdefghijklmnopqrstuvwxyz";

[$t] = array_map('intval', explode(' ', trim(fgets(STDIN))));

for($i=0;$i<$t;$i++){
    [$n] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $cnt = [];
    if($n %  2 == 0){
        $nh = intdiv($n, 2);
        for($j=0;$j<$nh;$j++){
            $cnt[] = $nh-$j;
            $cnt[] = $nh-$j+$nh;
        }
    }else{
        $nh = intdiv($n, 2);
        $nh = intdiv($n, 2);
        for($j=0;$j<$nh;$j++){
            $cnt[] = $nh-$j;
            $cnt[] = ($nh-$j)+$nh;
        }
        $cnt[] = $n;
    }
    $ans[] = implode(" ", $cnt);
}
echo implode(PHP_EOL,$ans);

<?php

//[$a,$b] = array_map('intval', explode(' ', trim(fgets(STDIN))));
//[$s] = explode(' ', trim(fgets(STDIN)));
//$a = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$h = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$mod = 998244353;
//$mod = 1000000007;
//$alpha = "abcdefghijklmnopqrstuvwxyz";

[$t] = array_map('intval', explode(' ', trim(fgets(STDIN))));

for($i=0;$i<$t;$i++){
    [$n] = array_map('intval', explode(' ', trim(fgets(STDIN))));
    $cnt = [];
    if($n %  2 == 0){
        $nh = intdiv($n, 2);
        for($j=0;$j<$nh;$j++){
            $cnt[] = $j+1;
            $cnt[] = $j+$nh+1;
        }
    }else{
        $nh = intdiv($n, 2);
        $nh = intdiv($n, 2);
        for($j=0;$j<$nh;$j++){
            $cnt[] = $j+1;
            $cnt[] = $j+$nh+2;
        }
        $cnt[] = $nh+1;
    }
    $ans[] = implode(" ", $cnt);
}
echo implode(PHP_EOL,$ans);


An array $$$b$$$ is called to be a subarray of $$$a$$$ if it forms a continuous subsequence of $$$a$$$, that is, if it is equal to $$$a_l$$$, $$$a_{l + 1}$$$, $$$\ldots$$$, $$$a_r$$$ for some $$$l, r$$$.Suppose $$$m$$$ is some known constant. For any array, having $$$m$$$ or more elements, let's define it's beauty as the sum of $$$m$$$ largest elements of that array. For example:   For array $$$x = [4, 3, 1, 5, 2]$$$ and $$$m = 3$$$, the $$$3$$$ largest elements of $$$x$$$ are $$$5$$$, $$$4$$$ and $$$3$$$, so the beauty of $$$x$$$ is $$$5 + 4 + 3 = 12$$$. For array $$$x = [10, 10, 10]$$$ and $$$m = 2$$$, the beauty of $$$x$$$ is $$$10 + 10 = 20$$$.You are given an array $$$a_1, a_2, \ldots, a_n$$$, the value of the said constant $$$m$$$ and an integer $$$k$$$. Your need to split the array $$$a$$$ into exactly $$$k$$$ subarrays such that:  Each element from $$$a$$$ belongs to exactly one subarray. Each subarray has at least $$$m$$$ elements. The sum of all beauties of $$$k$$$ subarrays is maximum possible.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le m$$$, $$$2 \le k$$$, $$$m \cdot k \le n$$$) — the number of elements in $$$a$$$, the constant $$$m$$$ in the definition of beauty and the number of subarrays to split to. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$).

In the first line, print the maximum possible sum of the beauties of the subarrays in the optimal partition. In the second line, print $$$k-1$$$ integers $$$p_1, p_2, \ldots, p_{k-1}$$$ ($$$1 \le p_1 < p_2 < \ldots < p_{k-1} < n$$$) representing the partition of the array, in which:  All elements with indices from $$$1$$$ to $$$p_1$$$ belong to the first subarray. All elements with indices from $$$p_1 + 1$$$ to $$$p_2$$$ belong to the second subarray. $$$\ldots$$$. All elements with indices from $$$p_{k-1} + 1$$$ to $$$n$$$ belong to the last, $$$k$$$-th subarray. If there are several optimal partitions, print any of them.

NoteIn the first example, one of the optimal partitions is $$$[5, 2, 5]$$$, $$$[2, 4]$$$, $$$[1, 1, 3, 2]$$$.  The beauty of the subarray $$$[5, 2, 5]$$$ is $$$5 + 5 = 10$$$.  The beauty of the subarray $$$[2, 4]$$$ is $$$2 + 4 = 6$$$.  The beauty of the subarray $$$[1, 1, 3, 2]$$$ is $$$3 + 2 = 5$$$. The sum of their beauties is $$$10 + 6 + 5 = 21$$$.In the second example, one optimal partition is $$$[4]$$$, $$$[1, 3]$$$, $$$[2, 2]$$$, $$$[3]$$$.

<?php
/*****************************************/
class InputReader {protected $_fh;public function __construct($fileHandler = STDIN){$this->_fh = $fileHandler;}
	public function readInt() {$d = trim(fgets($this->_fh));return (int)$d;}
	public function readString() {$d = trim(fgets($this->_fh));return $d;}
	public function readArrayOfInt($size, $indexFrom = 0) {$a = [];$ind = $indexFrom;foreach (explode(' ', fgets($this->_fh)) as $item) {$a[$ind++] = (int)$item;}return $a;}
	public function readArrayOfString($size, $indexFrom = 0) {$a = [];$ind = $indexFrom;foreach (explode(' ', fgets($this->_fh)) as $item) {$a[$ind++] = $item;}return $a;}
}

class Utils {
	/* Perform action N times. Can return values in array */
	static public function ntimes($n, $func, $returnResults = false) {$a = [];for ($i=1; $i<=$n; $i++) {$result = $func();if ($returnResults) {$a[$i] = $result;}}return $a;}
	/* Integral. Keys preserved. By reference. */
	static public function cumsum(&$a){$sum = 0;foreach($a as $k=>$v) {$a[$k] += $sum;$sum = $a[$k];}}
	/* Difference. Keys preserved. By reference. */
	static public function diff(&$a){$prev = 0;foreach($a as $k=>$v) {$buf=$a[$k];$a[$k]-=$prev;$prev = $buf;}}
	static public function bitCount($n){$cnt = 0;for ($j=$n; $j; $j>>=1){$cnt += $j&1;}return $cnt;}
}

class PrimeUtils {static protected $divisors = [1 => [1=>true],2 => [1=>true, 2=>true],];static protected $primes = [];
	static public function primes($limit){$a = str_repeat(chr(85), ($limit>>3) + 1);$a[0] = chr(83);for ($i=3; $i*$i < $limit; $i+=2) {if (ord($a[$i>>3]) & (1<<($i%8))) {;} else {for ($k=$i; $k*$i<$limit; $k++) {$n = $k*$i;$a[$n>>3] = chr(ord($a[$n>>3]) | (1<<($n%8)));}}}yield 2;for ($i=3; $i<$limit; $i+=2) {if (!(ord($a[$i>>3]) & (1<<($i%8)))) {yield $i;}}}
	static public function divisors($n, $lp = 2) {if (isset(self::$divisors[$n])) {return self::$divisors[$n];}if (empty(self::$primes)) {$primes = [];foreach (self::primes(1e3) as $prime) {$primes[$prime] = $prime;}self::$primes = $primes;}$r = [];foreach (self::$primes as $p) {if ($p>=$lp) {if ($n < $p*$p) {$r = [1=>true, $n=>true];break;} elseif ($n%$p==0) {foreach([1, $p] as $pre) {foreach(self::divisors(intdiv($n,$p), $p) as $nxt=>$v) {$r[$nxt*$pre] = true;}}break;}}}self::$divisors[$n] = $r;return self::$divisors[$n];}
}

/*****************************************/

$ir = new InputReader();

/* TASK */

list($n, $m, $k) = $ir->readArrayOfInt(2);
$a = $ir->readArrayOfInt($n, 1);

arsort($a);
$b = [];
$i = $m*$k;
$s = '0';
foreach ($a as $key=>$v) {
	$s = bcadd($s, $v);
	$b[] = $key;
	if (--$i<=0){
		break;
	}
}

sort($b);
echo $s."\n";
$i=1;
$kk = $k-1;
foreach ($b as $key=>$v) {
	if ($i%$m==0 && $kk) {
		echo ($v).' ';
		$kk--;
	}
	$i++;
}

<?php
/*****************************************/
class InputReader {protected $_fh;public function __construct($fileHandler = STDIN){$this->_fh = $fileHandler;}
	public function readInt() {$d = trim(fgets($this->_fh));return (int)$d;}
	public function readString() {$d = trim(fgets($this->_fh));return $d;}
	public function readArrayOfInt($size, $indexFrom = 0) {$a = [];$ind = $indexFrom;foreach (explode(' ', fgets($this->_fh)) as $item) {$a[$ind++] = (int)$item;}return $a;}
	public function readArrayOfString($size, $indexFrom = 0) {$a = [];$ind = $indexFrom;foreach (explode(' ', fgets($this->_fh)) as $item) {$a[$ind++] = $item;}return $a;}
}

class Utils {
	/* Perform action N times. Can return values in array */
	static public function ntimes($n, $func, $returnResults = false) {$a = [];for ($i=1; $i<=$n; $i++) {$result = $func();if ($returnResults) {$a[$i] = $result;}}return $a;}
	/* Integral. Keys preserved. By reference. */
	static public function cumsum(&$a){$sum = 0;foreach($a as $k=>$v) {$a[$k] += $sum;$sum = $a[$k];}}
	/* Difference. Keys preserved. By reference. */
	static public function diff(&$a){$prev = 0;foreach($a as $k=>$v) {$buf=$a[$k];$a[$k]-=$prev;$prev = $buf;}}
	static public function bitCount($n){$cnt = 0;for ($j=$n; $j; $j>>=1){$cnt += $j&1;}return $cnt;}
}

class PrimeUtils {static protected $divisors = [1 => [1=>true],2 => [1=>true, 2=>true],];static protected $primes = [];
	static public function primes($limit){$a = str_repeat(chr(85), ($limit>>3) + 1);$a[0] = chr(83);for ($i=3; $i*$i < $limit; $i+=2) {if (ord($a[$i>>3]) & (1<<($i%8))) {;} else {for ($k=$i; $k*$i<$limit; $k++) {$n = $k*$i;$a[$n>>3] = chr(ord($a[$n>>3]) | (1<<($n%8)));}}}yield 2;for ($i=3; $i<$limit; $i+=2) {if (!(ord($a[$i>>3]) & (1<<($i%8)))) {yield $i;}}}
	static public function divisors($n, $lp = 2) {if (isset(self::$divisors[$n])) {return self::$divisors[$n];}if (empty(self::$primes)) {$primes = [];foreach (self::primes(1e3) as $prime) {$primes[$prime] = $prime;}self::$primes = $primes;}$r = [];foreach (self::$primes as $p) {if ($p>=$lp) {if ($n < $p*$p) {$r = [1=>true, $n=>true];break;} elseif ($n%$p==0) {foreach([1, $p] as $pre) {foreach(self::divisors(intdiv($n,$p), $p) as $nxt=>$v) {$r[$nxt*$pre] = true;}}break;}}}self::$divisors[$n] = $r;return self::$divisors[$n];}
}

/*****************************************/

$ir = new InputReader();

/* TASK */

list($n, $m, $k) = $ir->readArrayOfInt(2);
$a = $ir->readArrayOfInt($n, 1);

arsort($a);
$b = [];
$i = $m*$k;
$s = 0;
foreach ($a as $key=>$v) {
	$s += $v;
	$b[] = $key;
	if (--$i<=0){
		break;
	}
}

sort($b);
echo $s."\n";
$i=1;
$kk = $k-1;
foreach ($b as $key=>$v) {
	if ($i%$m==0 && $kk) {
		echo ($v).' ';
		$kk--;
	}
	$i++;
}