Ilya plays a card game by the following rules.A player has several cards. Each card contains two non-negative integers inscribed, one at the top of the card and one at the bottom. At the beginning of the round the player chooses one of his cards to play it. If the top of the card contains number ai, and the bottom contains number bi, then when the player is playing the card, he gets ai points and also gets the opportunity to play additional bi cards. After the playing the card is discarded.More formally: let's say that there is a counter of the cards that can be played. At the beginning of the round the counter equals one. When a card is played, the counter decreases by one for the played card and increases by the number bi, which is written at the bottom of the card. Then the played card is discarded. If after that the counter is not equal to zero, the player gets the opportunity to play another card from the remaining cards. The round ends when the counter reaches zero or the player runs out of cards.Of course, Ilya wants to get as many points as possible. Can you determine the maximum number of points he can score provided that you know his cards?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of cards Ilya has. Each of the next n lines contains two non-negative space-separated integers — ai and bi (0 ≤ ai, bi ≤ 104) — the numbers, written at the top and the bottom of the i-th card correspondingly.

Print the single number — the maximum number of points you can score in one round by the described rules.

NoteIn the first sample none of two cards brings extra moves, so you should play the one that will bring more points.In the second sample you should first play the third card that doesn't bring any points but lets you play both remaining cards.

<?php
$a = trim(fgets(STDIN));
$b = 1;
$c = 0;
$d = array();
for($x = 1; $x <= $a; $x++)
{
    list($e, $f) = explode(" ", trim(fgets(STDIN)));
    if($f > 0)
    {
        $b += $f;
        $b--;
        $c += $e;
    }
    else
    {
        array_push($d, $e);
    }
}
rsort($d);
$g = array_splice($d, 0, $b);
$h = array_sum($g);
print $c + $h;
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr1 = array();
	$temp_counter = 1;
	$temp_point = 0;
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		if ($inp_c == 0) $inp_arr1[] = $inp_p;
		else {
			$temp_counter = $temp_counter - 1 + $inp_c;
			$temp_point += $inp_p;

		}
	}
	if (arsort($inp_arr1) === false) {
		//print(-1);
		//return;
	}

	foreach ($inp_arr1 as $as_i) {
		$temp_point += $as_i;
		$temp_counter = $temp_counter - 1;

		if ($temp_counter == 0) break;
	}
	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>

<?
error_reporting(0);

$fp = fopen("php://stdin",'r');
$n = (int)(str_replace( "\r\n", '', fgets($fp)));

$score = 0;
$nullCard = array();
$countCardToDrop = 1;
while( $n-- ){
	$card = explode(" ", trim( str_replace( "\r\n", '', fgets($fp)) ) );
	if( $card[1] > 0 ){
		$score += $card[0];
		$countCardToDrop += $card[1] - 1;
	} else {
		$nullCard[] = $card[0];
	}
}
rsort($nullCard);
$i = 0;
while( $countCardToDrop-- ){
	if( !isset($nullCard[$i]) ){
		break;
	}
	$score += $nullCard[$i];
	$i++;
}
echo $score;
fclose($fp);
?>

<?php
function cmp($a, $b){
    if ($a[0] == $b[0]) {
        return 0;
    }
    return ($a[0] > $b[0]) ? -1 : 1;
}
/*ccccccccccccccccccccccccccccccccccccc*/
$s = fopen("php://stdin", 'r');
$n = stream_get_contents($s);
$arr = explode("\n", $n);
$count = (int) $arr[0];
$summ_left = 0;
$summ_right = 0;
$cards = array();
$cards_left = array();
$cards_right = array();
$c_more_right = 0;
for($i = 1; $i <= $count; $i++){
    $exp = explode(" ", $arr[$i]);
    $summ_left+= $exp[0];
    $summ_right+= $exp[1];
    if($exp[1] > 0) $c_more_right++;
    $cards[] = $exp;
    $cards_left[] = $exp[0];
    $cards_right[] = $exp[1];
}
if($summ_right == 0){
    echo max($cards_left);
    exit;
}
$count_step = array_sum($cards_right);
if($count_step >= $count){
    echo array_sum($cards_left);
    exit;
}
usort($cards, cmp);
$count_step-= ($c_more_right - 1);
$countpoint = 0;
for($i = 0; $i < $count; $i++){
    if($cards[$i][1] == 0){
        if($count_step > 0){
            $count_step--;
            $countpoint+= $cards[$i][0];
        }
    } else {
        $countpoint+= $cards[$i][0];
    }
}
echo $countpoint;

<?php
$a = trim(fgets(STDIN));
$b = 1;
$c = 0;
$d = array();
for($x = 1; $x <= $a; $x++)
{
    list($e, $f) = explode(" ", trim(fgets(STDIN)));
    if($f > 0)
    {
        $b += $f;
        $c += $e;
    }
    else
    {
        array_push($d, $e);
    }
}
rsort($d);
$g = array_splice($d, 0, $b);
$h = array_sum($g);
print $c + $h;
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr = array();
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		$inp_arr[$inp_p] = $inp_c;
	}
/*	if (arsort($inp_arr) === false) {
		print(-1);
		return;
	}
*/
	$temp_counter = 1;
	$temp_point = 0;
	$temp = 1;
	//$c = 0;
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) break;

		$temp_point += $as_key;
		$temp_counter = $temp_counter - 1 + $as_val;
		//$c++;
	}

	/*$len = $c;
	for ($i = 0; $i < $len; $i++) {
		$_inp_arr = array_shift($inp_arr);
	}
	*/
	$temp_arr = array();
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) $temp_arr[$as_key] = $as_val;
	}

	//if (ksort($inp_arr) === false) {
	//if (krsort($inp_arr) === false) {
/*	if (krsort($temp_arr) === false) {
		print(-1);
		return;
	}
*/
	$end = $temp_counter;
	//foreach ($inp_arr as $as_key => $as_val) {
	foreach ($temp_arr as $as_key => $as_val) {
		//if ($as_val == 0) print("count err");

		$temp_point += $as_key;
		$temp_counter--;

		if ($temp_counter == 0) break;
	}

	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr1 = array();
	$inp_arr2 = array();
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		if ($inp_c == 0) $inp_arr1[$inp_p] = $inp_c;
		else $inp_arr2[$inp_p] = $inp_c;
	}
	if (arsort($inp_arr2) === false) {
		//print(-1);
		//return;
	}
	$temp_counter = 1;
	$temp_point = 0;
	$temp = 1;
	//$c = 0;
	foreach ($inp_arr2 as $as_key => $as_val) {
		$temp_point += $as_key;
		$temp_counter = $temp_counter - 1 + $as_val;
	}
	if (krsort($inp_arr1) === false) {
		//print(-1);
		//return;
	}
	foreach ($inp_arr1 as $as_key => $as_val) {
		$temp_point += $as_key;
		$temp_counter--;

		if ($temp_counter == 0) break;
	}

	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr = array();
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		$inp_arr[$inp_p] = $inp_c;
	}
	if (arsort($inp_arr) === false) {
		print(-1);
		return;
	}
	$temp_counter = 1;
	$temp_point = 0;
	$temp = 1;
	$c = 0;
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) break;

		$temp_point += $as_key;
		$temp_counter = $temp_counter - 1 + $as_val;
		$c++;
	}

	/*$len = $c;
	for ($i = 0; $i < $len; $i++) {
		$_inp_arr = array_shift($inp_arr);
	}
	*/
	$temp_arr = array();
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) $temp_arr[$as_key] = $as_val;
	}

	//if (ksort($inp_arr) === false) {
	//if (krsort($inp_arr) === false) {
	if (krsort($temp_arr) === false) {
		print(-1);
		return;
	}

	$end = $temp_counter;
	//foreach ($inp_arr as $as_key => $as_val) {
	foreach ($temp_arr as $as_key => $as_val) {
		//if ($as_val == 0) print("count err");

		$temp_point += $as_key;
		$temp_counter--;

		if ($temp_counter == 0) break;
	}

	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr = array();
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		$inp_arr[$inp_p] = $inp_c;
	}
	if (arsort($inp_arr) === false) {
		//print(-1);
		//return;
	}
	$temp_counter = 1;
	$temp_point = 0;
	$temp = 1;
	//$c = 0;
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) break;

		$temp_point += $as_key;
		$temp_counter = $temp_counter - 1 + $as_val;
		//$c++;
	}

	/*$len = $c;
	for ($i = 0; $i < $len; $i++) {
		$_inp_arr = array_shift($inp_arr);
	}
	*/
	$temp_arr = array();
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) $temp_arr[$as_key] = $as_val;
	}

	//if (ksort($inp_arr) === false) {
	//if (krsort($inp_arr) === false) {
	if (krsort($temp_arr) === false) {
		//print(-1);
		//return;
	}

	$end = $temp_counter;
	//foreach ($inp_arr as $as_key => $as_val) {
	foreach ($temp_arr as $as_key => $as_val) {
		//if ($as_val == 0) print("count err");

		$temp_point += $as_key;
		$temp_counter--;

		if ($temp_counter == 0) break;
	}

	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr1 = array();
	$inp_arr2 = array();
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		if ($inp_c == 0) $inp_arr1[$inp_p] = $inp_c;
		else $inp_arr2[$inp_p] = $inp_c;
	}
	if (arsort($inp_arr2) === false) {
		//print(-1);
		//return;
	}
	$temp_counter = 1;
	$temp_point = 0;
	$temp = 1;
	//$c = 0;
	foreach ($inp_arr2 as $as_key => $as_val) {
		$temp_point += $as_key;
		$temp_counter = $temp_counter - 1 + $as_val;
		if ($temp_counter == 0) break;
	}
	if (krsort($inp_arr1) === false) {
		//print(-1);
		//return;
	}
	foreach ($inp_arr1 as $as_key => $as_val) {
		$temp_point += $as_key;
		$temp_counter--;

		if ($temp_counter == 0) break;
	}

	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>

<?php

function solve(){
	$Token = new Token(rtrim(fgets(STDIN)), " ");
	$inp_n = $Token->nextInt();
	$inp_arr = array();
	for ($i = 0; $i < $inp_n; $i++) {
		$Token = new Token(rtrim(fgets(STDIN)), " ");
		$inp_p = $Token->nextInt();
		$inp_c = $Token->nextInt();
		$inp_arr[$inp_p] = $inp_c;
	}
	if (arsort($inp_arr) === false) {
		print(-1);
		return;
	}
	$temp_counter = 1;
	$temp_point = 0;
	$temp = 1;
	$c = 0;
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) break;

		$temp_point += $as_key;
		$temp_counter = $temp_counter - 1 + $as_val;
		$c++;
	}

	/*$len = $c;
	for ($i = 0; $i < $len; $i++) {
		$_inp_arr = array_shift($inp_arr);
	}
	*/
	$temp_arr = array();
	foreach ($inp_arr as $as_key => $as_val) {
		if ($as_val == 0) $temp_arr[$as_key] = $as_val;
	}

	//if (ksort($inp_arr) === false) {
	//if (krsort($inp_arr) === false) {
	if (krsort($temp_arr) === false) {
		print(-1);
		return;
	}

	$end = $temp_counter;
	//foreach ($inp_arr as $as_key => $as_val) {
	foreach ($temp_arr as $as_key => $as_val) {
		//if ($as_val == 0) print("count err");

		$temp_point += $as_key;
		$temp_counter--;
		printf("%d", $as_key);

		if ($temp_counter == 0) break;
	}

	printf("%d", $temp_point);

}

function run(){
	solve();
}

ob_end_clean();
run();

//input -  $inp_
//block    $temp_
//two block$ttemp_
//as 	   $as_
//instance $(Upper)
//ref      $ref
//class menba $_

class Token{
	private $token;
	private $tok;

	public function __construct($str_line, $tok) {
		$this->tok = $tok;
		$this->token = strtok($str_line, $this->tok);
	}

	public function nextToken() {
		$thisToken = $this->token;
		$this->token = strtok($this->tok);
		return $thisToken;
	}

	public function nextFloat() {
		return (float)$this->nextToken();
	}

  	public function nextInt() {
		return (int)$this->nextToken();
	}

	public function nextIntArray() {
		$temp_arr = array();
		$flag = -1;
		while ($flag !== 1) {
			$thisToken = $this->nextToken();
			if ($thisToken !== false) {
				$temp_arr[] = $thisToken;
			} else {
				$flag = 1;
			}
		}
		return $temp_arr;
	}
/*
	public function nnextIntArray($num) {
		$temp_arr = array();
		for ($i = 0; $i < $num; $i++) {
			$temp_arr[] = (int)$this->token;
		}
		return $temp_arr;
	}
}
*/
}

/*
function get_line() {
        $stdin = fopen("php://stdin", "r");
        $line = rtrim($stdin, "\n");
        fclose($stdin);
        return $line;
}
*/

function num_printf($i){
	if (is_float($i)) {
		printf("%.10f", $i);
	}
	if (is_int($i)) {
		printf("%10d", $i);
	}
}

function array_printf(array $array) {
		$message = "";
		foreach ($array as $value) {
			$message .= "$value" . " ";
		}
		$message = rtrim($message);
		printf('%s', $message);
}
?>


Mitya has a rooted tree with $$$n$$$ vertices indexed from $$$1$$$ to $$$n$$$, where the root has index $$$1$$$. Each vertex $$$v$$$ initially had an integer number $$$a_v \ge 0$$$ written on it. For every vertex $$$v$$$ Mitya has computed $$$s_v$$$: the sum of all values written on the vertices on the path from vertex $$$v$$$ to the root, as well as $$$h_v$$$ — the depth of vertex $$$v$$$, which denotes the number of vertices on the path from vertex $$$v$$$ to the root. Clearly, $$$s_1=a_1$$$ and $$$h_1=1$$$.Then Mitya erased all numbers $$$a_v$$$, and by accident he also erased all values $$$s_v$$$ for vertices with even depth (vertices with even $$$h_v$$$). Your task is to restore the values $$$a_v$$$ for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values $$$a_v$$$ for all vertices in the tree.

The first line contains one integer $$$n$$$ — the number of vertices in the tree ($$$2 \le n \le 10^5$$$). The following line contains integers $$$p_2$$$, $$$p_3$$$, ... $$$p_n$$$, where $$$p_i$$$ stands for the parent of vertex with index $$$i$$$ in the tree ($$$1 \le p_i < i$$$). The last line contains integer values $$$s_1$$$, $$$s_2$$$, ..., $$$s_n$$$ ($$$-1 \le s_v \le 10^9$$$), where erased values are replaced by $$$-1$$$.

Output one integer — the minimum total sum of all values $$$a_v$$$ in the original tree, or $$$-1$$$ if such tree does not exist.

<?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;}
}

/* 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;}

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 */

$n = $ir->readInt();
$pp = $ir->readArrayOfInt($n-1, 2);
$ss = $ir->readArrayOfInt($n, 1);

for ($i=1; $i<=$n; $i++) {
	if ($ss[$i]<0) {
		$ss[$i] = -0.5;
	}
}

for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];
	if ($ss[$p]==-0.5) {
		$ss[$p] = -$ss[$i];
	} elseif ($ss[$p]<-0.5) {
		$ss[$p] = $ss[$p]>-$ss[$i] ? $ss[$p] : -$ss[$i];
	}
}

for ($i=2; $i<=$n; $i++) {
	if ($ss[$i]==-0.5) {
		$ss[$i] = $ss[$pp[$i]];
	} else if ($ss[$i]<0) {
		$ss[$i] = -$ss[$i];
	}
}

$sum = $ss[1];
for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];

	if ($ss[$i]>=$ss[$p]) {
		$sum = bcadd($sum, $ss[$i] - $ss[$p]);
	} else {
		echo '-1';
		exit();
	}
}

echo $sum;

<?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;}
}

/* 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;}

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 */

$n = $ir->readInt();
$pp = $ir->readArrayOfInt($n-1, 2);
$ss = $ir->readArrayOfInt($n, 1);

for ($i=1; $i<=$n; $i++) {
	if ($ss[$i]<0) {
		$ss[$i] = -0.5;
	}
}

for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];
	if ($ss[$p]<-0.5) {
		$ss[$p] = $ss[$p]>-$ss[$i] ? $ss[$p] : -$ss[$i];
	}
}

for ($i=2; $i<=$n; $i++) {
	if ($ss[$i]==-0.5) {
		$ss[$i] = $ss[$pp[$i]];
	} else if ($ss[$i]<0) {
		$ss[$i] = -$ss[$i];
	}
}

$sum = $ss[1];
for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];

	if ($ss[$i]>=$ss[$p]) {
		$sum = bcadd($sum, $ss[$i] - $ss[$p]);
	} else {
		echo '-1';
		exit();
	}
}

echo $sum;

<?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;}
}

/* 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;}

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 */

$n = $ir->readInt();
$pp = $ir->readArrayOfInt($n-1, 2);
$ss = $ir->readArrayOfInt($n, 1);

for ($i=1; $i<=$n; $i++) {
	if ($ss[$i]<0) {
		$ss[$i] = -0.5;
	}
}

for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];
	if ($ss[$p]==-0.5) {
		$ss[$p] = $ss[$i];
	} elseif ($ss[$p]<-0.5) {
		$ss[$p] = $ss[$p]>-$ss[$i] ? $ss[$p] : -$ss[$i];
	}
}

for ($i=2; $i<=$n; $i++) {
	if ($ss[$i]==-0.5) {
		$ss[$i] = $ss[$pp[$i]];
	} else if ($ss[$i]<0) {
		$ss[$i] = -$ss[$i];
	}
}

$sum = $ss[1];
for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];

	if ($ss[$i]>=$ss[$p]) {
		$sum = bcadd($sum, $ss[$i] - $ss[$p]);
	} else {
		echo '-1';
		exit();
	}
}

echo $sum;

<?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;}
}

/* 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;}

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 */

$n = $ir->readInt();
$pp = $ir->readArrayOfInt($n-1, 2);
$ss = $ir->readArrayOfInt($n, 1);

for ($i=1; $i<=$n; $i++) {
	if ($ss[$i]<0) {
		$ss[$i] = -0.5;
	}
}

for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];
	if ($ss[$p]<-0.5) {
		$ss[$p] = $ss[$p]>-$ss[$i] ? $ss[$p] : -$ss[$i];
	}
}

for ($i=2; $i<=$n; $i++) {
	if ($ss[$i]==-0.5) {
		$ss[$i] = $ss[$pp[$i]];
	}
}

$sum = $ss[1];
for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];

	if ($ss[$i]>=$ss[$p]) {
		$sum = bcadd($sum, $ss[$i] - $ss[$p]);
	} else {
		echo '-1';
		exit();
	}
}

echo $sum;

<?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;}
}

/* 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;}

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 */

$n = $ir->readInt();
$pp = $ir->readArrayOfInt($n-1, 2);
$ss = $ir->readArrayOfInt($n, 1);

for ($i=1; $i<=$n; $i++) {
	if ($ss[$i]<0) {
		$ss[$i] = -0.5;
	}
}

for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];
	if ($ss[$p]==-0.5) {
		$ss[$p] = $ss[$i];
	}
	if ($ss[$p]<-0.5) {
		$ss[$p] = $ss[$p]>-$ss[$i] ? $ss[$p] : -$ss[$i];
	}
}

for ($i=2; $i<=$n; $i++) {
	if ($ss[$i]==-0.5) {
		$ss[$i] = $ss[$pp[$i]];
	} else if ($ss[$i]<0) {
		$ss[$i] = -$ss[$i];
	}
}

$sum = $ss[1];
for ($i=2; $i<=$n; $i++) {
	$p = $pp[$i];

	if ($ss[$i]>=$ss[$p]) {
		$sum = bcadd($sum, $ss[$i] - $ss[$p]);
	} else {
		echo '-1';
		exit();
	}
}

echo $sum;


Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:  Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.  Increase each array element by yi. In other words, perform n assignments ai = ai + yi (1 ≤ i ≤ n).  Take a piece of paper and write out the qi-th array element. That is, the element aqi. Help Sereja, complete all his operations.

The first line contains integers n, m (1 ≤ n, m ≤ 105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the original array. Next m lines describe operations, the i-th line describes the i-th operation. The first number in the i-th line is integer ti (1 ≤ ti ≤ 3) that represents the operation type. If ti = 1, then it is followed by two integers vi and xi, (1 ≤ vi ≤ n, 1 ≤ xi ≤ 109). If ti = 2, then it is followed by integer yi (1 ≤ yi ≤ 104). And if ti = 3, then it is followed by integer qi (1 ≤ qi ≤ n).

For each third type operation print value aqi. Print the values in the order, in which the corresponding queries follow in the input.


You are given two integers $$$a$$$ and $$$b$$$.In one move, you can choose some integer $$$k$$$ from $$$1$$$ to $$$10$$$ and add it to $$$a$$$ or subtract it from $$$a$$$. In other words, you choose an integer $$$k \in [1; 10]$$$ and perform $$$a := a + k$$$ or $$$a := a - k$$$. You may use different values of $$$k$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer: the minimum number of moves required to obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case of the example, you don't need to do anything.In the second test case of the example, the following sequence of moves can be applied: $$$13 \rightarrow 23 \rightarrow 32 \rightarrow 42$$$ (add $$$10$$$, add $$$9$$$, add $$$10$$$).In the third test case of the example, the following sequence of moves can be applied: $$$18 \rightarrow 10 \rightarrow 4$$$ (subtract $$$8$$$, subtract $$$6$$$).

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     list($b, $c) = explode(" ", trim(fgets(STDIN)));
     if($b <= $c)
     {
          print ceil(($c - $b) / 10) . "\n";
     }
     else
     {
          print ceil(($b - $c) / 10) . "\n";
     }
}
?>

<?php
$tc=readline();
while ($tc--)
 {
	  fscanf(STDIN,"%d %d",$a,$b);
	  echo (int)((abs($a-$b)+9)/10);
	  echo "\n";

 }


Burenka came to kindergarden. This kindergarten is quite strange, so each kid there receives two fractions ($$$\frac{a}{b}$$$ and $$$\frac{c}{d}$$$) with integer numerators and denominators. Then children are commanded to play with their fractions.Burenka is a clever kid, so she noticed that when she claps once, she can multiply numerator or denominator of one of her two fractions by any integer of her choice (but she can't multiply denominators by $$$0$$$). Now she wants know the minimal number of claps to make her fractions equal (by value). Please help her and find the required number of claps!

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then follow the descriptions of each test case. The only line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$d$$$ ($$$0 \leq a, c \leq 10^9$$$, $$$1 \leq b, d \leq 10^9$$$) — numerators and denominators of the fractions given to Burenka initially.

For each test case print a single integer — the minimal number of claps Burenka needs to make her fractions equal.

NoteIn the first case, Burenka can multiply $$$c$$$ by $$$2$$$, then the fractions will be equal.In the second case, fractions are already equal.In the third case, Burenka can multiply $$$a$$$ by $$$4$$$, then $$$b$$$ by $$$3$$$. Then the fractions will be equal ($$$\frac{1 \cdot 4}{2 \cdot 3} = \frac{2}{3}$$$).

<?php

$inp = fopen('php://stdin', 'rb');

fscanf($inp, '%d', $t);

while ($t--) {
    [
        $a,
        $b,
        $c,
        $d
    ] = fscanf($inp, '%d %d %d %d');

    $ad = $a * $d;
    $bc = $b * $c;

    if ($ad === $bc) {
        echo 0 .PHP_EOL;
    } elseif ($ad === 0 || $bc === 0) {
        echo 1 .PHP_EOL;
    } elseif ($ad % $bc === 0 || $bc % $ad === 0) {
        echo 1 .PHP_EOL;
    } else {
        echo 2 .PHP_EOL;
    }
}

<?php
function inputInt($sys)
{
    fscanf($sys, "%d", $n);
    return $n;
}

function inputArray($sys)
{
    fscanf($sys, "%[^\n]", $tempA);
    $arr = array_map('intval', preg_split('/ /', $tempA, -1, PREG_SPLIT_NO_EMPTY));
    return $arr;
}

$stdin = fopen('php://stdin', 'r');
$T = inputInt($stdin);
function solve($sys)
{
    $arr = inputArray($sys);

    $ad = $arr[0] * $arr[3];
    $bc = $arr[1] * $arr[2];

    if ($ad == $bc) {
        echo 0;
    }
    else if ($ad == 0 || $bc == 0) {
        echo 1;
    }
    else if ($bc > $ad && ($bc % $ad == 0)) {
        echo 1;
    }
    else if ($ad > $bc && ($ad % $bc == 0)) {
        echo 1;
    }
    else {
        echo 2;
    }
    echo "\n";
}
while ($T--) {
    solve($stdin);
}


You are given two integers $$$n$$$ and $$$k$$$. You are asked to choose maximum number of distinct integers from $$$1$$$ to $$$n$$$ so that there is no subset of chosen numbers with sum equal to $$$k$$$.A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it.

The first line contains the number of test cases $$$T$$$ ($$$1 \le T \le 100$$$). Each of the next $$$T$$$ lines contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 1000$$$) — the description of test cases.

For each test case output two lines. In the first line output a single integer $$$m$$$ — the number of chosen integers. In the second line output $$$m$$$ distinct integers from $$$1$$$ to $$$n$$$ — the chosen numbers. If there are multiple answers, print any. You can print the numbers in any order.

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

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

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

  $r = ceil($k / 2);

  echo $n - $r.PHP_EOL;
  if ($n - $r != 0) {
    for ($j = $r; $j <= $n; $j++) {
      if ($j != $k) { echo $j.' '; }
    }
    echo PHP_EOL;
  }
}
?>


Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)!He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help!The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two paths have at least one common vertex. Each edge of the tree should be in exactly one path.Help Remesses, find such a decomposition of the tree or derermine that there is no such decomposition.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^{5}$$$) the number of nodes in the tree. Each of the next $$$n - 1$$$ lines contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the edges of the tree. It is guaranteed that the given edges form a tree.

If there are no decompositions, print the only line containing "No". Otherwise in the first line print "Yes", and in the second line print the number of paths in the decomposition $$$m$$$.  Each of the next $$$m$$$ lines should contain two integers $$$u_i$$$, $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \neq v_i$$$) denoting that one of the paths in the decomposition is the simple path between nodes $$$u_i$$$ and $$$v_i$$$.  Each pair of paths in the decomposition should have at least one common vertex, and each edge of the tree should be presented in exactly one path. You can print the paths and the ends of each path in arbitrary order. If there are multiple decompositions, print any.

NoteThe tree from the first example is shown on the picture below:  The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.The tree from the second example is shown on the picture below:  We can show that there are no valid decompositions of this tree.The tree from the third example is shown on the picture below:  The number next to each edge corresponds to the path number in the decomposition. It is easy to see that this decomposition suits the required conditions.


Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.The program cannot delete the letters from the list or rearrange them.Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of letters in the mailbox. The second line contains n space-separated integers (zeros and ones) — the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read.

Print a single number — the minimum number of operations needed to make all the letters read.

NoteIn the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.In the third sample all letters are already read.

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

$op = 0;
$i = 0;
while($i < $n){
	if($status[$i] == 1){
		$op += 2;
		$i++;
		while($status[$i] == 1){
			$op++;
			$i++;
		}
	}else $i++;
}

if($op > 0)
	$op--;
echo $op;
?>


A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \le i \le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print a single integer  — the answer to the problem.

NoteIn the third case, he can connect two sticks with lengths $$$1$$$ and $$$2$$$ and he will get one stick with length $$$3$$$. So, he will have two sticks with lengths $$$3$$$.In the fourth case, he can connect two sticks with lengths $$$1$$$ and $$$3$$$ and he will get one stick with length $$$4$$$. After that, he will have three sticks with lengths $$$\{2, 4, 4\}$$$, so two sticks have the same length, and one stick has the other length.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     print ceil($b / 2) . "\n";
}
?>


You went to the store, selling $$$n$$$ types of chocolates. There are $$$a_i$$$ chocolates of type $$$i$$$ in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $$$x_i$$$ chocolates of type $$$i$$$ (clearly, $$$0 \le x_i \le a_i$$$), then for all $$$1 \le j < i$$$ at least one of the following must hold:  $$$x_j = 0$$$ (you bought zero chocolates of type $$$j$$$) $$$x_j < x_i$$$ (you bought less chocolates of type $$$j$$$ than of type $$$i$$$) For example, the array $$$x = [0, 0, 1, 2, 10]$$$ satisfies the requirement above (assuming that all $$$a_i \ge x_i$$$), while arrays $$$x = [0, 1, 0]$$$, $$$x = [5, 5]$$$ and $$$x = [3, 2]$$$ don't.Calculate the maximum number of chocolates you can buy.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$), denoting the number of types of chocolate. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$), denoting the number of chocolates of each type.

Print the maximum number of chocolates you can buy.

NoteIn the first example, it is optimal to buy: $$$0 + 0 + 1 + 3 + 6$$$ chocolates.In the second example, it is optimal to buy: $$$1 + 2 + 3 + 4 + 10$$$ chocolates.In the third example, it is optimal to buy: $$$0 + 0 + 0 + 1$$$ chocolates.


A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.m buyers will come to the shop. Each of them wants to buy exactly one t-shirt. For the j-th buyer we know his favorite color cj.A buyer agrees to buy a t-shirt, if at least one side (front or back) is painted in his favorite color. Among all t-shirts that have colors acceptable to this buyer he will choose the cheapest one. If there are no such t-shirts, the buyer won't buy anything. Assume that the buyers come one by one, and each buyer is served only after the previous one is served.You are to compute the prices each buyer will pay for t-shirts.

The first line contains single integer n (1 ≤ n ≤ 200 000) — the number of t-shirts. The following line contains sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ 1 000 000 000), where pi equals to the price of the i-th t-shirt. The following line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3), where ai equals to the front color of the i-th t-shirt. The following line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 3), where bi equals to the back color of the i-th t-shirt. The next line contains single integer m (1 ≤ m ≤ 200 000) — the number of buyers.  The following line contains sequence c1, c2, ..., cm (1 ≤ cj ≤ 3), where cj equals to the favorite color of the j-th buyer. The buyers will come to the shop in the order they are given in the input. Each buyer is served only after the previous one is served.

Print to the first line m integers — the j-th integer should be equal to the price of the t-shirt which the j-th buyer will buy. If the j-th buyer won't buy anything, print -1.


A permutation of length $$$n$$$ is an array $$$p=[p_1,p_2,\dots,p_n]$$$, which contains every integer from $$$1$$$ to $$$n$$$ (inclusive) and, moreover, each number appears exactly once. For example, $$$p=[3,1,4,2,5]$$$ is a permutation of length $$$5$$$.For a given number $$$n$$$ ($$$n \ge 2$$$), find a permutation $$$p$$$ in which absolute difference (that is, the absolute value of difference) of any two neighboring (adjacent) elements is between $$$2$$$ and $$$4$$$, inclusive. Formally, find such permutation $$$p$$$ that $$$2 \le |p_i - p_{i+1}| \le 4$$$ for each $$$i$$$ ($$$1 \le i < n$$$).Print any such permutation for the given integer $$$n$$$ or determine that it does not exist.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is described by a single line containing an integer $$$n$$$ ($$$2 \le n \le 1000$$$).

Print $$$t$$$ lines. Print a permutation that meets the given requirements. If there are several such permutations, then print any of them. If no such permutation exists, print -1.


Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other.Galya doesn't know the ships location. She can shoot to some cells and after each shot she is told if that cell was a part of some ship (this case is called "hit") or not (this case is called "miss").Galya has already made k shots, all of them were misses.Your task is to calculate the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship.It is guaranteed that there is at least one valid ships placement.

The first line contains four positive integers n, a, b, k (1 ≤ n ≤ 2·105, 1 ≤ a, b ≤ n, 0 ≤ k ≤ n - 1) — the length of the grid, the number of ships on the grid, the length of each ship and the number of shots Galya has already made. The second line contains a string of length n, consisting of zeros and ones. If the i-th character is one, Galya has already made a shot to this cell. Otherwise, she hasn't. It is guaranteed that there are exactly k ones in this string.

In the first line print the minimum number of cells such that if Galya shoot at all of them, she would hit at least one ship. In the second line print the cells Galya should shoot at. Each cell should be printed exactly once. You can print the cells in arbitrary order. The cells are numbered from 1 to n, starting from the left. If there are multiple answers, you can print any of them.

NoteThere is one ship in the first sample. It can be either to the left or to the right from the shot Galya has already made (the "1" character). So, it is necessary to make two shots: one at the left part, and one at the right part.


Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.It takes the first swimmer exactly $$$a$$$ minutes to swim across the entire pool and come back, exactly $$$b$$$ minutes for the second swimmer and $$$c$$$ minutes for the third. Hence, the first swimmer will be on the left side of the pool after $$$0$$$, $$$a$$$, $$$2a$$$, $$$3a$$$, ... minutes after the start time, the second one will be at $$$0$$$, $$$b$$$, $$$2b$$$, $$$3b$$$, ... minutes, and the third one will be on the left side of the pool after $$$0$$$, $$$c$$$, $$$2c$$$, $$$3c$$$, ... minutes.You came to the left side of the pool exactly $$$p$$$ minutes after they started swimming. Determine how long you have to wait before one of the swimmers arrives at the left side of the pool.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Next $$$t$$$ lines contains test case descriptions, one per line. Each line contains four integers $$$p$$$, $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \leq p, a, b, c \leq 10^{18}$$$), time in minutes after the start, when you came to the pool and times in minutes it take the swimmers to cross the entire pool and come back.

For each test case, output one integer — how long you have to wait (in minutes) before one of the swimmers arrives at the left side of the pool.

NoteIn the first test case, the first swimmer is on the left side in $$$0, 5, 10, 15, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 4, 8, 12, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 8, 16, 24, \ldots$$$ minutes after the start time. You arrived at the pool in $$$9$$$ minutes after the start time and in a minute you will meet the first swimmer on the left side.In the second test case, the first swimmer is on the left side in $$$0, 6, 12, 18, \ldots$$$ minutes after the start time, the second swimmer is on the left side in $$$0, 10, 20, 30, \ldots$$$ minutes after the start time, and the third swimmer is on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$2$$$ minutes after the start time and after $$$4$$$ minutes meet the first swimmer on the left side.In the third test case, you came to the pool $$$10$$$ minutes after the start time. At the same time, all three swimmers are on the left side. A rare stroke of luck!In the fourth test case, all swimmers are located on the left side in $$$0, 9, 18, 27, \ldots$$$ minutes after the start time. You arrived at the pool $$$10$$$ minutes after the start time and after $$$8$$$ minutes meet all three swimmers on the left side.


Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please notice that since the robot moves only along the grid lines, there can be several shortest paths). Then, after it reaches p1, it'll move to p2, again, choosing one of the shortest ways, then to p3, and so on, until he has visited all points in the given order. Some of the points in the sequence may coincide, in that case Robot will visit that point several times according to the sequence order.While Santa was away, someone gave a sequence of points to Robot. This sequence is now lost, but Robot saved the protocol of its unit movements. Please, find the minimum possible length of the sequence.

The first line of input contains the only positive integer n (1 ≤ n ≤ 2·105) which equals the number of unit segments the robot traveled. The second line contains the movements protocol, which consists of n letters, each being equal either L, or R, or U, or D. k-th letter stands for the direction which Robot traveled the k-th unit segment in: L means that it moved to the left, R — to the right, U — to the top and D — to the bottom. Have a look at the illustrations for better explanation.

The only line of input should contain the minimum possible length of the sequence.

NoteThe illustrations to the first three tests are given below.  The last example illustrates that each point in the sequence should be counted as many times as it is presented in the sequence.


The Fair Nut likes kvass very much. On his birthday parents presented him $$$n$$$ kegs of kvass. There are $$$v_i$$$ liters of kvass in the $$$i$$$-th keg. Each keg has a lever. You can pour your glass by exactly $$$1$$$ liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by $$$s$$$ liters of kvass. But he wants to do it, so kvass level in the least keg is as much as possible.Help him find out how much kvass can be in the least keg or define it's not possible to pour his glass by $$$s$$$ liters of kvass.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le s \le 10^{12}$$$) — the number of kegs and glass volume. The second line contains $$$n$$$ integers $$$v_1, v_2, \ldots, v_n$$$ ($$$1 \le v_i \le 10^9$$$) — the volume of $$$i$$$-th keg.

If the Fair Nut cannot pour his glass by $$$s$$$ liters of kvass, print $$$-1$$$. Otherwise, print a single integer — how much kvass in the least keg can be.

NoteIn the first example, the answer is $$$3$$$, the Fair Nut can take $$$1$$$ liter from the first keg and $$$2$$$ liters from the third keg. There are $$$3$$$ liters of kvass in each keg.In the second example, the answer is $$$2$$$, the Fair Nut can take $$$3$$$ liters from the first keg and $$$1$$$ liter from the second keg.In the third example, the Fair Nut can't pour his cup by $$$7$$$ liters, so the answer is $$$-1$$$.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array_sum($c);
if($d < $b)
{
     print "-1";
}
else
{
     $e = 0;
     $f = min($c);
     for($x = 0; $x < $a; $x++)
     {
          $e += $c[$x] - $f;
     }
     if($e >= $b)
     {
          print $f;
     }
     else
     {
          $b -= $e;
          $g = floor($b / $a);
          $h = $b % $a;
          if($h == 0)
          {
               print $f - $g;
          }
          else
          {
               print $f - $g - 1;
          }
     }
}
?>


This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions:   The length of $$$t$$$ does not exceed the length of $$$s$$$.  $$$t$$$ is a palindrome.  There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$5000$$$.

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$.  It is a palindrome.  "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".


Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.How many bars each of the players will consume?

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequence t1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = explode(" ",rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice <= array_sum($t) - $alice - $t[$pos]) {
		$num = $pos + 1;
	} else {
		$num = $pos;
	}
	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	//$n = (int)rtrim(fgets($handle));
	//$t = explode(" ", rtrim(fgets($handle)));

	$n = rtrim(fgets(STDIN));
	$t = explode(" ",rtrim(fgets(STDIN)));

	$sum = array_sum($t);
	$num = 0;

	for ($i = 0; $i < count($t); $i++)
	{
		$temp += $t[$i];
		if ($temp - $t[$i] <= $sum - $temp) $num++;
		else break;
	}

	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	//$n = (int)rtrim(fgets($handle));
	//$t = explode(" ", rtrim(fgets($handle)));

	$n = rtrim(fgets(STDIN));
	$t = explode(" ",rtrim(fgets(STDIN)));

	$dp = array();
	for ($i = 0; $i < count($t); $i++) {
		$dp[$i] = $sum += $t[$i];
	}

	for ($i = 0; $i < count($t); $i++) {

		if ($dp[$i] - $t[$i] <= $sum - $dp[$i]) $num++;
		else break;

		print($temp);
	}
	print($num. " ". ($n - $num));
}
?>

<?php
function input()
{
    return rtrim(fgets(STDIN));
}

function input_array()
{
    return explode(' ', input());
}

$n = input();
$num = input_array();
$dp = array(0);
$sum = 0;
for ($i = 0; $i < $n; $i++)
{
    $dp[$i + 1] = $sum += $num[$i];
}
for ($i = 0; $i < $n; $i++)
{
    if ($dp[$i] <= $sum - $dp[$i + 1]) continue;
    else
    {
        echo $i . ' ' . ($n - $i) . "\n";
        exit();
    }
}
echo  "$n 0\n";
?>

<?php

error_reporting(0);

solve();

function solve(){

	$n = rtrim(fgets(STDIN));
	for ($i = 0; $i < $n; $i++)
	{
		$t[] = rtrim(fgets(STDIN));
	}

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = intval(array_sum($t) / 2);
	else $half = intval(array_sum($t) / 2) + 1;

	for ($i = 0; $i < $n; $i++)
	{
		$temp += $t[$i];
		if ($temp > $half) {
			$num = $i + 1;
			break;
		}
	}

	print($num. " ". $n - $num);
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = str_split(rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice < array_sum($t) - $alice - $t[$pos]) {
		$num = $pos + 2;
	} else {
		$num = $pos + 1;
	}

	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = str_split(rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice < array_sum($t) - $alice - $t[$pos]) {
		$num = $pos;
	} else {
		$num = $pos-1;
	}

	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	//$n = (int)rtrim(fgets($handle));
	//$t = explode(" ", rtrim(fgets($handle)));

	$n = rtrim(fgets(STDIN));
	$t = explode(" ",rtrim(fgets(STDIN)));

	$sum = array_sum($t);
	$num = 0;
	for ($i = 0; $i < count($t); $i++) {
		$temp += $t[$i];
		if ($temp - $t[$i] <= $sum - $temp) $num++;
		else break;

		print($temp);
	}
	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = str_split(rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice > array_sum($t) - $alice - $t[$pos]) {
		$num = $pos + 1;
	} else {
		$num = $pos;
	}

	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = str_split(rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice < array_sum($t) - $alice - $t[$pos]) {
		$num = $pos + 1;
	} else {
		$num = $pos;
	}

	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = explode(" ",rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice < array_sum($t) - $alice - $t[$pos]) {
		$num = $pos + 1;
	} else {
		$num = $pos;
	}
	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = str_split(rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp > $half) {
			$num = $i + 1;
			break;
		}
	}

	print($num. " ". ($n - $num));
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	$n = rtrim(fgets(STDIN));
	for ($i = 0; $i < $n; $i++)
	{
		$t[] = rtrim(fgets(STDIN));
	}

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = intval(array_sum($t) / 2);
	else $half = intval(array_sum($t) / 2) + 1;

	for ($i = 0; $i < $n; $i++)
	{
		$temp += $t[$i];
		if ($temp > $half) {
			$num = $i + 1;
			break;
		}
	}

	printf($num. " ". $n - $num);
}
?>

<?php

error_reporting(0);

solve();

function solve(){

	//$handle = @fopen("input.txt", "r");
	$n = rtrim(fgets(STDIN));
	//$n = (int)rtrim(fgets($handle));
	$t = explode(rtrim(fgets(STDIN)));
	//$t = explode(" ", rtrim(fgets($handle)));

	$sum = array_sum($t);

	if ($sum % 2 === 0) $half = (int)(array_sum($t) / 2);
	else $half = (int)(array_sum($t) / 2) + 1;

	$temp = 0;
	for ($i = 0; $i < $n; $i++)
	{
		$temp += (int)$t[$i];
		if ($temp >= $half) {
			$pos = $i;
			break;
		}
	}

	for ($i = 0; $i < $pos; $i++) {
		$alice += (int)$t[$i];
	}
	if ($alice < array_sum($t) - $alice - $t[$pos]) {
		$num = $pos + 1;
	} else {
		$num = $pos;
	}
	print($num. " ". ($n - $num));
}
?>


There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where:  <hostname> — server name (consists of words and maybe some dots separating them),  /<path> — optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where:   <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20.  <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20.  Addresses are not guaranteed to be distinct.

First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.

10
http://abacaba.ru/test
http://abacaba.ru/
http://abacaba.com
http://abacaba.com/test
http://abacaba.de/
http://abacaba.ru/test
http://abacaba.de/test
http://abacaba.com/
http://abacaba.com/t
http://abacaba.com/test

14
http://c
http://ccc.bbbb/aba..b
http://cba.com
http://a.c/aba..b/a
http://abc/
http://a.c/
http://ccc.bbbb
http://ab.ac.bc.aa/
http://a.a.a/
http://ccc.bbbb/
http://cba.com/
http://cba.com/aba..b
http://a.a.a/aba..b/a
http://abc/aba..b/a

2
http://cba.com http://ccc.bbbb
http://a.a.a http://a.c http://abc

<?php
  $data = file_get_contents("php://stdin");

  $data = preg_split('#\s+#', trim($data));
  $n = intval($data[0]);
  $server = array();
  for($i=0;$i<$n;$i++)
  {
    preg_match('#(http://[^/]+)([^\s]*)#', $data[$i+1], $match);
    $server[$match[1]][] = $match[2];
  }
  $groups = array();
  foreach($server as $a=>$b)
  {
    $x = array_unique($b); sort($x);
    $groups[md5(implode("|", $x), true)][] = $a;
  }
  $n = 0;
  foreach($groups as $a)
  {
    if (count($a) > 1) $n ++;
  }
  echo $n."\n";
  foreach($groups as $a)
  {
    if (count($a) > 1) echo implode(" ", $a)."\n";
  }

?>

<?php

$n = trim(fgets(STDIN));
$map = array();
for ($i = 0; $i < $n; $i++) {
	$str = substr(trim(fgets(STDIN)), 7);
	$slashPost = strpos($str, '/');
	if ($slashPost !== false) {
		$host = substr($str, 0, $slashPost);
		$path = substr($str, $slashPost);
	} else {
		$host = $str;
		$path = '';
	}
	if (empty($map[$host])) {
		$map[$host] = array();
	}
	$map[$host][$path] = true;
}
$hostsMap = array();
foreach ($map as $host => $urls) {
	$urls = array_keys($urls);
	sort($urls);
	$urlKey = implode('#', $urls);
	if (empty($hostsMap[$urlKey])) {
		$hostsMap[$urlKey] = array();
	}
	$hostsMap[$urlKey][] = $host;
}
unset($map);

foreach ($hostsMap as $k => $hosts) {
	if (count($hosts) < 2) {
		unset($hostsMap[$k]);
	}
}
echo count($hostsMap) . "\n";
foreach ($hostsMap as $hosts) {
	foreach ($hosts as $host) {
		echo 'http://' . $host . ' ';
	}
	echo "\n";
}

<?php

$n = fgets(STDIN);

$separated = [];
$joined = [];
$ans = [];

for ($i = 0; $i < $n; $i++) {
	$line = trim(fgets(STDIN));
	preg_match('/http:\/\/[a-z.]+/', $line, $domain);
	$path = str_replace($domain[0], '', $line);
	$separated[$domain[0]][] = $path;
}

foreach ($separated as $domain => $paths) {
	$separated[$domain] = array_unique($paths);
	sort($separated[$domain]);
}

foreach ($separated as $domain => $paths) {
	$paths = implode('#', $paths);
	$joined[$paths][] = $domain;
}

foreach ($joined as $paths => $domains) {
	if (count($domains) > 1) {
		$ans[] = $domains;
	}
}

echo count($ans) . "\n";

foreach ($ans as $domains) {
	echo implode(' ', $domains) . "\n";
}

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

function get_int() {
	global $stdin;
	return (int) fgets($stdin);
}

function get_line() {
	global $stdin;
	return (string) rtrim(fgets($stdin));
}

$format = "/(http:\/\/)([^\/]+)(\/(.*))?/";
//          ^1         ^2      ^3 ^4

$n = 0; $m = 0; $paths = array(); $groups = array();

// Main code

$n = get_int(); $m = 0;

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

	$matches = null;

	if (!preg_match($format, $line, $matches))
		die("Wrong format");

	$domain = $matches[2];
	$path = $matches[3];

	if (!isset($path))
		$path = '';

	if (!isset($paths[$domain]))
		$paths[$domain] = array();
	array_push($paths[$domain], $path);
}

foreach ($paths as $key => $value) {
	sort($value);

	$vlen = count($value);
	$array = array($value[0]); $size = 1;

	for ($i = 1; $i < $vlen; $i++) {
		if ($array[$size - 1] != $value[$i])
			$array[$size++] = $value[$i];
	}

	$fullpath = implode('#', $array) . '#';

	if (!isset($groups[$fullpath]))
		$groups[$fullpath] = array();

	array_push($groups[$fullpath], $key);
}

foreach ($groups as $value) {
	if (count($value) > 1)
		$m++;
}

print($m . "\n");

foreach ($groups as $key => $value) {
	$len = count($value);
	if ($len > 1) {
		for ($i = 0; $i < $len; $i++) {
			print('http://' . $value[$i] . ' ');
		}
		print("\n");
	}
}
?>

<?php
  $data = file_get_contents("php://input");

  $data = preg_split('#\s+#', trim($data));
  $n = intval($data[0]);
  $server = array();
  for($i=0;$i<$n;$i++)
  {
    preg_match('#(http://[^/]+)([^\s]*)#', $data[$i+1], $match);
    $server[$match[1]][] = $match[2];
  }
  $groups = array();
  foreach($server as $a=>$b)
  {
    $x = array_unique($b); sort($x);
    $groups[md5(implode("|", $x), true)][] = $a;
  }
  $n = 0;
  foreach($groups as $a)
  {
    if (count($a) > 1) $n ++;
  }
  echo $n."\n";
  foreach($groups as $a)
  {
    if (count($a) > 1) echo implode(" ", $a)."\n";
  }

?>

<?php

$n = fgets(STDIN);

$separated = [];
$joined = [];
$ans = [];

for ($i = 0; $i < $n; $i++) {
	$line = trim(fgets(STDIN));
	preg_match('/http:\/\/[a-z.]+/', $line, $domain);
	$path = str_replace($domain[0], '', $line);
	$separated[$domain[0]][] = $path;
}

foreach ($separated as $domain => $paths) {
	$separated[$domain] = array_unique($paths);
	sort($separated[$domain]);
}

foreach ($separated as $domain => $paths) {
	$paths = implode('', $paths);
	$joined[$paths][] = $domain;
}

foreach ($joined as $paths => $domains) {
	if (count($domains) > 1) {
		$ans[] = $domains;
	}
}

echo count($ans) . "\n";

foreach ($ans as $domains) {
	echo implode(' ', $domains) . "\n";
}


Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.Let's enumerate students from 1 to n·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.

The only line contains two integers n and m (1 ≤ n, m ≤ 105; n·m ≤ 105) — the number of rows and the number of columns in the required matrix.

If there is no such matrix, output "NO" (without quotes).  Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.

NoteIn the first test case the matrix initially looks like this:1 2 3 45 6 7 8It's easy to see that there are no two students that are adjacent in both matrices.In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors.

<?php
    //init
    $a=[];
    $stime=microtime(true);
    fscanf(STDIN, "%d%d", $n, $m);

    function swap(&$a,&$b){
        $temp = $a;
        $a = $b;
        $b = $temp;
    }

    function check($i){
        global $m,$a;
        if ($i%$m!=0) if (abs($a[$i]-$a[$i-1])==1||abs($a[$i]-$a[$i-1])==$m) return true;
        if ($i>=$m) if (abs($a[$i]-$a[$i-$m])==1||abs($a[$i]-$a[$i-$m])==$m) return true;
        return 0;
    }

    foreach(range(1, $n*$m) as $temp) $a[]=$temp;
    $ok=0;
    while (microtime(true)-$stime < 1) {
        shuffle($a);
        $f=0;
        foreach(range(0, $n*$m-1) as $i){
            $cnt=0;
            while (check($i)&&$cnt<=100) {
                if ($i < $n*$m-1) swap($a[$i], $a[rand()%($n*$m-$i-1)+$i+1]);
                else $cnt=1e9;
                $cnt++;
            }
            if ($cnt>100) {
                $f=1;
                break;
            }
        }
        if($f) continue;
        $ok=1;
        echo "YES\n";
        foreach(range(1, $n) as $i){
            foreach (range(0, $m-1) as $j) {
                echo $a[($i-1)*$m+$j];
                echo " ";
            }
            echo "\n";
        }
        break;
    }
    if (!$ok) echo "NO\n";
    return 0;

<?php
    //init
    $a=[];
    $stime=getMillisecond();
    fscanf(STDIN, "%d%d", $n, $m);
    // $n=2;
    // $m=1;

    function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
    }

    function swap(&$a,&$b){
        $temp = $a;
        $a = $b;
        $b = $temp;
    }

    function check($i){
        global $m,$a;
        if ($i%$m!=0) if (abs($a[$i]-$a[$i-1])==1||abs($a[$i]-$a[$i-1])==$m) return true;
        if ($i>=$m) if (abs($a[$i]-$a[$i-$m])==1||abs($a[$i]-$a[$i-$m])==$m) return true;
        return 0;
    }

    foreach(range(1, $n*$m) as $temp) $a[]=$temp;
    $ok=0;
    while (getMillisecond()-$stime < 1000) {
        shuffle($a);
        $f=0;
        foreach(range(0, $n*$m-1) as $i){
            $cnt=0;
            while (check($i) && $cnt<=100) {
                if ($i < $n*$m-1) swap($a[$i], $a[rand()%($n*$m-$i-1)+$i+1]);
                else $cnt=1e9;
                $cnt++;
            }
            if ($cnt>100) {
                $f=1;
                break;
            }
        }
        if($f) continue;
        $ok=1;
        echo "YES\n";
        foreach(range(1, $n) as $i){
            foreach (range(0, $m-1) as $j) {
                echo $a[($i-1)*$m+$j];
                echo " ";
            }
            echo "\n";
        }
        break;
    }
    if (!$ok) echo "NO\n";
    return 0;


Let $$$LCM(x, y)$$$ be the minimum positive integer that is divisible by both $$$x$$$ and $$$y$$$. For example, $$$LCM(13, 37) = 481$$$, $$$LCM(9, 6) = 18$$$.You are given two integers $$$l$$$ and $$$r$$$. Find two integers $$$x$$$ and $$$y$$$ such that $$$l \le x < y \le r$$$ and $$$l \le LCM(x, y) \le r$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases. Each test case is represented by one line containing two integers $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le 10^9$$$).

For each test case, print two integers:   if it is impossible to find integers $$$x$$$ and $$$y$$$ meeting the constraints in the statement, print two integers equal to $$$-1$$$;  otherwise, print the values of $$$x$$$ and $$$y$$$ (if there are multiple valid answers, you may print any of them).

<?php
function gcd($x, $y) {
    if($y > $x) {
        $temp1 = $y;
        $y = $x;
        $x = $temp1;
    }

    if($x == 0 && $y == 0) return 1;
    if ($x == 0) return $y;
    if ($y == 0) return $x;
    if ($x < 0) $x = -$x;
    if ($y < 0) $y = -$y;
    if ($x == $y) return $x;
    while($y > 0) {
        $temp2 = $y;
        $y = $x % $y;
        $x = $temp2;
    }
    return $x;
}

function lcm($x, $y) {
    return ($x * $y)/gcd($x, $y);
}

function primeCheck($number){
    if ($number == 1)
    return 0;
    for ($i = 2; $i <= $number/2; $i++){
        if ($number % $i == 0)
            return 0;
    }
    return 1;
}

$t = (int)readline();
$input = array();
for($k = 0; $k < $t; $k++) {
    $input[] = explode(' ',readline());
}
foreach($input as $n) {
    $out = array(-1,-1);

    if ($n[0] * 2 <= $n[1]) $out = array($n[0], $n[0]*2);
    echo $out[0] . ' ' . $out[1] . "\n";
}

<?php
function gcd($x, $y) {
    if($y > $x) {
        $temp1 = $y;
        $y = $x;
        $x = $temp1;
    }

    if($x == 0 && $y == 0) return 1;
    if ($x == 0) return $y;
    if ($y == 0) return $x;
    if ($x < 0) $x = -$x;
    if ($y < 0) $y = -$y;
    if ($x == $y) return $x;
    while($y > 0) {
        $temp2 = $y;
        $y = $x % $y;
        $x = $temp2;
    }
    return $x;
}

function lcm($x, $y) {
    return ($x * $y)/gcd($x, $y);
}

function primeCheck($number){
    if ($number == 1)
    return 0;
    for ($i = 2; $i <= $number/2; $i++){
        if ($number % $i == 0)
            return 0;
    }
    return 1;
}

$t = (int)readline();
$input = array();
for($k = 0; $k < $t; $k++) {
    $input[] = explode(' ',readline());
}
foreach($input as $n) {
    $out = array(-1,-1);
    $break = false;
    for($i = $n[0]; $i < $n[1]; $i++) {
        if(($i % 2) != 0 && $i+1 != $n[1] && $i != 1) $i++;
        for($j = $i+1; $j <= $n[1]; $j++) {
            if(lcm($i, $j) >= $n[0] && lcm($i, $j) <= $n[1]) {
                $out = array($i, $j);
                $break = true;
                break;
            }
        }
        if($break) break;
    }
    echo $out[0] . ' ' . $out[1] . "\n";
}

<?php
function gcd($x, $y) {
    if($y > $x) {
        $temp1 = $y;
        $y = $x;
        $x = $temp1;
    }

    if($x == 0 && $y == 0) return 1;
    if ($x == 0) return $y;
    if ($y == 0) return $x;
    if ($x < 0) $x = -$x;
    if ($y < 0) $y = -$y;
    if ($x == $y) return $x;
    while($y > 0) {
        $temp2 = $y;
        $y = $x % $y;
        $x = $temp2;
    }
    return $x;
}

function lcm($x, $y) {
    return ($x * $y)/gcd($x, $y);
}

function primeCheck($number){
    if ($number == 1)
    return 0;
    for ($i = 2; $i <= $number/2; $i++){
        if ($number % $i == 0)
            return 0;
    }
    return 1;
}

$t = (int)readline();
$input = array();
for($k = 0; $k < $t; $k++) {
    $input[] = explode(' ',readline());
}
foreach($input as $n) {
    $out = array(-1,-1);
    $break = false;
    for($i = $n[0]; $i < $n[1]; $i++) {
        if(($i % 2) != 0 && $i+1 != $n[1]) $i++;
        for($j = $i+1; $j <= $n[1]; $j++) {
            if(lcm($i, $j) >= $n[0] && lcm($i, $j) <= $n[1]) {
                $out = array($i, $j);
                $break = true;
                break;
            }
        }
        if($break) break;
    }
    echo $out[0] . ' ' . $out[1] . "\n";
}

<?php
function gcd($x, $y) {
    if($y > $x) {
        $temp1 = $y;
        $y = $x;
        $x = $temp1;
    }

    if($x == 0 && $y == 0) return 1;
    if ($x == 0) return $y;
    if ($y == 0) return $x;
    if ($x < 0) $x = -$x;
    if ($y < 0) $y = -$y;
    if ($x == $y) return $x;
    while($y > 0) {
        $temp2 = $y;
        $y = $x % $y;
        $x = $temp2;
    }
    return $x;
}

function lcm($x, $y) {
    return ($x * $y)/gcd($x, $y);
}

function primeCheck($number){
    if ($number == 1)
    return 0;
    for ($i = 2; $i <= $number/2; $i++){
        if ($number % $i == 0)
            return 0;
    }
    return 1;
}

$t = (int)readline();
$input = array();
for($k = 0; $k < $t; $k++) {
    $input[] = explode(' ',readline());
}
foreach($input as $n) {
    $out = array(-1,-1);
    $break = false;
    for($i = $n[0]; $i < $n[1]; $i++) {
        if(($i % 2) != 0) $i++;
        for($j = $i+1; $j <= $n[1]; $j++) {
            if(lcm($i, $j) >= $n[0] && lcm($i, $j) <= $n[1]) {
                $out = array($i, $j);
                $break = true;
                break;
            }
        }
        if($break) break;
    }
    echo $out[0] . ' ' . $out[1] . "\n";
}

<?php
function gcd($x, $y) {
    if($y > $x) {
        $temp1 = $y;
        $y = $x;
        $x = $temp1;
    }

    if($x == 0 && $y == 0) return 1;
    if ($x == 0) return $y;
    if ($y == 0) return $x;
    if ($x < 0) $x = -$x;
    if ($y < 0) $y = -$y;
    if ($x == $y) return $x;
    while($y > 0) {
        $temp2 = $y;
        $y = $x % $y;
        $x = $temp2;
    }
    return $x;
}

function lcm($x, $y) {
    return ($x * $y)/gcd($x, $y);
}

$t = (int)readline();
$input = array();
for($k = 0; $k < $t; $k++) {
    $input[] = explode(' ',readline());
}
print_r($input);
foreach($input as $n) {
    $out = array(-1,-1);
    $break = false;
    for($i = (int)$n[0]; $i < (int)$n[1]; $i++) {
        for($j = $i+1; $j <= (int)$n[1]; $j++) {
            if(lcm($i, $j) >= (int)$n[0] && lcm($i, $j) <= (int)$n[1]) {
                $out = array($i, $j);
                $break = true;
                break;
            }
        }
        if($break) break;
    }
    echo $out[0] . ' ' . $out[1] . "\n";
}


Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.

First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies. Second line contains sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 109) — amounts of candies in each pile.

Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.

NoteIn first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).In second example you should add two candies to any three piles.


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.  The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.

For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size $$$m \times m$$$ which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).

NoteThe first test case of the input has three types of tiles, they are shown on the picture below.  Masha can construct, for example, the following square of size $$$4 \times 4$$$ which is a symmetric matrix:

<?php
    $j = trim(fgets(STDIN));
    for($i = 0; $i < $j; $i++){
        $bool = false;
        $a = explode(" ", trim(fgets(STDIN)));
        for($k = 0; $k < $a[0]; $k++){
            $d = explode(" ", trim(fgets(STDIN)));
            $f = explode(" ", trim(fgets(STDIN)));
            if($d[1] == $f[0]){
                $bool = true;
                //break;
            }
        }
        if($a[1] % 2 == 0 && $bool){
            echo "YES\n";
        } else {
            echo "NO\n";
        }
    }

?>


You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in circles muttering about how useless her sweetheart is. During that time Dima has time to peacefully complete k - 1 tasks. Then Inna returns and tells Dima off for the next task he does in her presence and goes to another room again. It continues until Dima is through with his tasks.Overall, Dima has n tasks to do, each task has a unique number from 1 to n. Dima loves order, so he does tasks consecutively, starting from some task. For example, if Dima has 6 tasks to do in total, then, if he starts from the 5-th task, the order is like that: first Dima does the 5-th task, then the 6-th one, then the 1-st one, then the 2-nd one, then the 3-rd one, then the 4-th one.Inna tells Dima off (only lovingly and appropriately!) so often and systematically that he's very well learned the power with which she tells him off for each task. Help Dima choose the first task so that in total he gets told off with as little power as possible.

The first line of the input contains two integers n, k (1 ≤ k ≤ n ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 103), where ai is the power Inna tells Dima off with if she is present in the room while he is doing the i-th task. It is guaranteed that n is divisible by k.

In a single line print the number of the task Dima should start with to get told off with as little power as possible. If there are multiple solutions, print the one with the minimum number of the first task to do.

NoteExplanation of the first example.If Dima starts from the first task, Inna tells him off with power 3, then Dima can do one more task (as k = 2), then Inna tells him off for the third task with power 1, then she tells him off for the fifth task with power 5. Thus, Dima gets told off with total power 3 + 1 + 5 = 9. If Dima started from the second task, for example, then Inna would tell him off for tasks 2, 4 and 6 with power 2 + 6 + 4 = 12. Explanation of the second example.In the second example k = 5, thus, Dima manages to complete 4 tasks in-between the telling off sessions. Thus, Inna tells Dima off for tasks number 1 and 6 (if he starts from 1 or 6), 2 and 7 (if he starts from 2 or 7) and so on. The optimal answer is to start from task 3 or 8, 3 has a smaller number, so the answer is 3.