Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.

If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.

NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating:  Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7.  With rating 1894 Limak is in the division 2. His rating increases by 5.  Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.

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

    fscanf(STDIN, "%d", $n);

    $pos = 0;
    $arr = array();
    $arrDiv = array('1' => 0, '2' => 0);
    $divMax = 0;
    $div1MinRate = PHP_INT_MAX;
    $div2MaxRate = -PHP_INT_MAX;

    for ($i = 0; $i < $n; $i++) {
        fscanf(STDIN, "%d %d", $chg, $div);

        if (isset($arr[$pos])) {
            if ($arr[$pos] != $div) {
                echo "Impossible";
                exit;
            }
        } else {
            $arr[$pos] = $div;
        }

        $pos += $chg;

        $arrDiv[$div]++;
    }

    if ($arrDiv[2] == 0) {
        echo "Infinity";
        exit;
    }

    krsort($arr);
    if (DEBUG) var_dump($arr);

    foreach ($arr as $k => $div) {
        if ($div == "1") {
            $div1MinRate = min($div1MinRate, $k);
        }
        if ($div == "2") {
            $div2MaxRate = max($div2MaxRate, $k);
        }

    }

    if ($div1MinRate <= $div2MaxRate) {
        echo "Impossible";
        exit;
    }

    if (DEBUG) echo $div2MaxRate . PHP_EOL;
    $baseRate = 1899 - $div2MaxRate;
    if (DEBUG) echo $baseRate . PHP_EOL;

    echo $baseRate + $pos;

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

    fscanf(STDIN, "%d", $n);

    $pos = 0;
    $arr = array();
    $arrDiv = array('1' => 0, '2' => 0);
    $divMax = 0;
    $div2MaxRate = -PHP_INT_MAX;

    for ($i = 0; $i < $n; $i++) {
        fscanf(STDIN, "%d %d", $chg, $div);

        $arr[$pos] = $div;

        $pos += $chg;

        $arrDiv[$div]++;
    }

    if ($arrDiv[2] == 0) {
        echo "Infinity";
        exit;
    }

    krsort($arr);
    if (DEBUG) var_dump($arr);

    foreach ($arr as $k => $div) {
        $divMax = max($div, $divMax);
        if ($divMax > $div) {
            echo "Impossible";
            exit;
        }
        if ($div == "2") {
            $div2MaxRate = max($div2MaxRate, $k);
        }

    }

    if (DEBUG) echo $div2MaxRate . PHP_EOL;
    $baseRate = 1899 - $div2MaxRate;
    if (DEBUG) echo $baseRate . PHP_EOL;

    echo $baseRate + $pos;

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

    fscanf(STDIN, "%d", $n);

    $pos = 0;
    $arr = array();
    $arrDiv = array('1' => 0, '2' => 0);
    $divMax = 0;
    $div1MinRate = PHP_INT_MAX;
    $div2MaxRate = -PHP_INT_MAX;

    for ($i = 0; $i < $n; $i++) {
        fscanf(STDIN, "%d %d", $chg, $div);

        $arr[$pos] = $div;

        $pos += $chg;

        $arrDiv[$div]++;
    }

    if ($arrDiv[2] == 0) {
        echo "Infinity";
        exit;
    }

    krsort($arr);
    if (DEBUG) var_dump($arr);

    foreach ($arr as $k => $div) {
        if ($div == "1") {
            $div1MinRate = min($div1MinRate, $k);
        }
        if ($div == "2") {
            $div2MaxRate = max($div2MaxRate, $k);
        }

    }

    if ($div1MinRate <= $div2MaxRate) {
        echo "Impossible";
        exit;
    }

    if (DEBUG) echo $div2MaxRate . PHP_EOL;
    $baseRate = 1899 - $div2MaxRate;
    if (DEBUG) echo $baseRate . PHP_EOL;

    echo $baseRate + $pos;

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

    fscanf(STDIN, "%d", $n);

    $pos = 0;
    $arr = array();
    $arrDiv = array('1' => 0, '2' => 0);
    $divMax = 0;
    $div1MinRate = PHP_INT_MAX;
    $div2MaxRate = -PHP_INT_MAX;

    for ($i = 0; $i < $n; $i++) {
        fscanf(STDIN, "%d %d", $chg, $div);

        $arr[$pos] = $div;

        $pos += $chg;

        $arrDiv[$div]++;
    }

    if ($arrDiv[2] == 0) {
        echo "Infinity";
        exit;
    }

    krsort($arr);
    if (DEBUG) var_dump($arr);

    foreach ($arr as $k => $div) {
        $divMax = max($div, $divMax);
        if ($divMax > $div) {
            echo "Impossible";
            exit;
        }
        if ($div == "1") {
            $div1MinRate = min($div1MinRate, $k);
        }
        if ($div == "2") {
            $div2MaxRate = max($div2MaxRate, $k);
        }

    }

    if ($div1MinRate <= $div2MaxRate) {
        echo "Impossible";
        exit;
    }

    if (DEBUG) echo $div2MaxRate . PHP_EOL;
    $baseRate = 1899 - $div2MaxRate;
    if (DEBUG) echo $baseRate . PHP_EOL;

    echo $baseRate + $pos;


Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).You are given an $$$n \times m$$$ grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.

The first line contains $$$t$$$ ($$$1 \le t \le 100$$$), the number of test cases. In each test case, the first line will contain $$$n$$$ ($$$1 \le n \le 50$$$) and $$$m$$$ ($$$1 \le m \le 50$$$), the height and width of the grid respectively. The next $$$n$$$ lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'.

For each test case, output "YES" if there is a valid grid or "NO" if there is not. If there is, output the grid on the next $$$n$$$ lines. If there are multiple answers, print any. In the output, the "YES"s and "NO"s are case-insensitive, meaning that outputs such as "yEs" and "nO" are valid. However, the grid is case-sensitive.

YES
WRWRWR
RWRWRW
WRWRWR
RWRWRW
NO
YES
R
W
R
W
R

NoteThe answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid.


Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.

The first line of the input contains a string s (1 ≤ |s| ≤ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.

If there is no way of replacing '#' characters which leads to a beautiful string print  - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.

Note|s| denotes the length of the string s.

<?php
	$str = trim(fgets(STDIN));
	$open_all=0;
	$close_all=0;
	$sharp=0;
	for($i=0;$i<strlen($str);$i++){
		if ($str[$i]=='(') $open_all++;
		if ($str[$i]==')') $close_all++;
		if ($str[$i]=='#') $sharp++;
	}
	$need = $open_all-$close_all;
	if ($close_all>=$open_all || $need < $sharp){echo "-1";exit;}
	$ustr = explode('#',$str);
	$open=0;
	$close=0;
	$pos = 0;
	for($i=0;$i<count($ustr)-1;$i++){
		for($j=$pos;$j<strlen($ustr[$i]);$j++){
			if ($ustr[$i][$j]=='(') $open++;
			if ($ustr[$i][$j]==')') $close++;
		}
		$pos = 0;
		$stri = $ustr[$i+1];
		$len = strlen($stri)-1;
		while($stri[$pos]==')' && $pos<=$len) {$close++;$pos++;}
		//printf("%d %d\n",$open,$close);
		$result = $open-$close;
		if ($result > $open) $result = $open;
		while($need-$result<$sharp) $result--;
		$close += $result;
		printf("%d\n",$result);
		$sharp--;
	}
?>

<?php
	$str = trim(fgets(STDIN));
	$open_all=0;
	$close_all=0;
	$sharp=0;
	for($i=0;$i<strlen($str);$i++){
		if ($str[$i]=='(') $open_all++;
		if ($str[$i]==')') $close_all++;
		if ($str[$i]=='#') $sharp++;
	}
	$need = $open_all-$close_all;
	if ($close_all>=$open_all || $need < $sharp){echo "-1";exit;}
	if ($sharp>1){
		$ustr = explode('#',$str);
		$open=0;
		$close=0;
		$pos = 0;
		for($i=0;$i<count($ustr)-1;$i++){
			for($j=$pos;$j<strlen($ustr[$i]);$j++){
				if ($ustr[$i][$j]=='(') $open++;
				if ($ustr[$i][$j]==')') $close++;
			}
			$pos = 0;
			$stri = $ustr[$i+1];
			$len = strlen($stri)-1;
			while($stri[$pos]==')' && $pos<=$len) {$close++;$pos++;}
			//printf("%d %d\n",$open,$close);
			$result = $open-$close;
			if ($result > $open) $result = $open;
			while($need-$result<$sharp) $result--;
			$close += $result;
			printf("%d\n",$result);
			$sharp--;
		}
	}else{
		printf("%d\n",$open_all-$close_all);
	}
?>

<?php
	$str = trim(fgets(STDIN));
	$open_all=0;
	$close_all=0;
	for($i=0;$i<strlen($str);$i++){
		if ($str[$i]=='(') $open_all++;
		if ($str[$i]==')') $close_all++;
	}
	if ($close_all>=$open_all){echo "-1";exit;}
	$ustr = explode('#',$str);
	$open=0;
	$close=0;
	$pos = 0;
	for($i=0;$i<count($ustr)-1;$i++){
		for($j=$pos;$j<strlen($ustr[$i]);$j++){
			if ($ustr[$i][$j]=='(') $open++;
			if ($ustr[$i][$j]==')') $close++;
		}
		$pos = 0;
		$stri = $ustr[$i+1];
		$len = strlen($stri)-1;
		while($stri[$pos]==')' && $pos<=$len) {$close++;$pos++;}
		//printf("%d %d\n",$open,$close);
		$result = $open-$close;
		if ($result > $open) $result = $open;
		if ($result < 1) $result = 1;
		$close += $result;
		printf("%d\n",$result);
	}
?>

<?php
	$str = trim(fgets(STDIN));
	$open_all=0;
	$close_all=0;
	$sharp=0;
	for($i=0;$i<strlen($str);$i++){
		if ($str[$i]=='(') $open_all++;
		if ($str[$i]==')') $close_all++;
		if ($str[$i]=='#') $sharp++;
	}
	$need = $open_all-$close_all;
	if ($close_all>=$open_all || $need < $sharp){echo "-1";exit;}
	if ($sharp>1){
		$ustr = explode('#',$str);
		$open=0;
		$close=0;
		$pos = 0;
		for($i=0;$i<count($ustr)-1;$i++){
			for($j=$pos;$j<strlen($ustr[$i]);$j++){
				if ($ustr[$i][$j]=='(') $open++;
				if ($ustr[$i][$j]==')') $close++;
			}
			$pos = 0;
			$stri = $ustr[$i+1];
			$len = strlen($stri)-1;
			while($stri[$pos]==')' && $pos<=$len) {$close++;$pos++;}
			//printf("%d %d\n",$open,$close);
			$result = $open-$close;
			if ($result > $open) $result = $open;
			while($need-$result<$sharp) $result--;
			if ($result < 1) $result=1;
			$close += $result;
			printf("%d\n",$result);
			$sharp--;
		}
	}else{
		printf("%d\n",$open_all-$close_all);
	}
?>

<?php
	$str = trim(fgets(STDIN));
	$open_all=0;
	$close_all=0;
	$sharp=0;
	for($i=0;$i<strlen($str);$i++){
		if ($str[$i]=='(') $open_all++;
		if ($str[$i]==')') $close_all++;
		if ($str[$i]=='#') $sharp++;
	}
	$need = $open_all-$close_all;
	if ($close_all>=$open_all || $need < $sharp){echo "-1";exit;}
	if ($sharp>1){
		$ustr = explode('#',$str);
		$open=0;
		$close=0;
		$pos = 0;
		for($i=0;$i<count($ustr)-1;$i++){
			for($j=$pos;$j<strlen($ustr[$i]);$j++){
				if ($ustr[$i][$j]=='(') $open++;
				if ($ustr[$i][$j]==')') $close++;
			}
			$pos = 0;
			$stri = $ustr[$i+1];
			$len = strlen($stri)-1;
			while($stri[$pos]==')' && $pos<=$len) {$close++;$pos++;}
			//printf("%d %d\n",$open,$close);
			$result = $open-$close;
			if ($result > $open) $result = $open;
			while($need-$result<$sharp) $result--;
			if ($result > 1) $result=1;
			$close += $result;
			printf("%d\n",$result);
			$sharp--;
		}
	}else{
		printf("%d\n",$open_all-$close_all);
	}
?>


Polycarp had an array $$$a$$$ of $$$3$$$ positive integers. He wrote out the sums of all non-empty subsequences of this array, sorted them in non-decreasing order, and got an array $$$b$$$ of $$$7$$$ integers.For example, if $$$a = \{1, 4, 3\}$$$, then Polycarp wrote out $$$1$$$, $$$4$$$, $$$3$$$, $$$1 + 4 = 5$$$, $$$1 + 3 = 4$$$, $$$4 + 3 = 7$$$, $$$1 + 4 + 3 = 8$$$. After sorting, he got an array $$$b = \{1, 3, 4, 4, 5, 7, 8\}.$$$Unfortunately, Polycarp lost the array $$$a$$$. He only has the array $$$b$$$ left. Help him to restore the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Each test case consists of one line which contains $$$7$$$ integers $$$b_1, b_2, \dots, b_7$$$ ($$$1 \le b_i \le 10^9$$$; $$$b_i \le b_{i+1}$$$).  Additional constraint on the input: there exists at least one array $$$a$$$ which yields this array $$$b$$$ as described in the statement.

For each test case, print $$$3$$$ integers — $$$a_1$$$, $$$a_2$$$ and $$$a_3$$$. If there can be several answers, print any of them.

NoteThe subsequence of the array $$$a$$$ is a sequence that can be obtained from $$$a$$$ by removing zero or more of its elements.Two subsequences are considered different if index sets of elements included in them are different. That is, the values of the elements don't matter in the comparison of subsequences. In particular, any array of length $$$3$$$ has exactly $$$7$$$ different non-empty subsequences.

<?php
// $stdin = fopen('input.txt', 'r');

function solve($a) {

	return [$a[0], $a[1], $a[6] - $a[0] - $a[1]];

};

$t = intval(fgets(STDIN));

while ($t) {

	$a = array_map('intval', explode(' ', fgets(STDIN)));

            $ans = solve($a);

            foreach ($ans as $i) {
                        echo $i.' ';
            }

	echo "\n";

	$t--;

}

<?php
// $stdin = fopen('input.txt', 'r');

$solve = function ($a) {

	return [$a[0], $a[1], $a[6] - $a[0] - $a[1]];

};

$t = intval(fgets(STDIN));

for (; $t > 0; $t--) {

	$a = array_map('intval', explode(' ', fgets(STDIN)));

	echo implode(' ', $solve($a));
	echo "\n";

}


Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming an n × n grid, surrounded entirely by walls. At the end of the room lies a door locked with evil magical forces. The following inscriptions are written on the door: The sound of clashing rocks will awaken the door! Being a very senior adventurer, you immediately realize what this means. In the room next door lies an infinite number of magical rocks. There are four types of rocks:   '^': this rock moves upwards;  '<': this rock moves leftwards;  '>': this rock moves rightwards;  'v': this rock moves downwards. To open the door, you first need to place the rocks on some of the tiles (one tile can be occupied by at most one rock). Then, you select a single rock that you have placed and activate it. The activated rock will then move in its direction until it hits another rock or hits the walls of the room (the rock will not move if something already blocks it in its chosen direction). The rock then deactivates. If it hits the walls, or if there have been already 107 events of rock becoming activated, the movements end. Otherwise, the rock that was hit becomes activated and this procedure is repeated.If a rock moves at least one cell before hitting either the wall or another rock, the hit produces a sound. The door will open once the number of produced sounds is at least x. It is okay for the rocks to continue moving after producing x sounds.The following picture illustrates the four possible scenarios of moving rocks. Moves at least one cell, then hits another rock. A sound is produced, the hit rock becomes activated.   Moves at least one cell, then hits the wall (i.e., the side of the room). A sound is produced, the movements end.   Does not move because a rock is already standing in the path. The blocking rock becomes activated, but no sounds are produced.   Does not move because the wall is in the way. No sounds are produced and the movements end.  Assume there's an infinite number of rocks of each type in the neighboring room. You know what to do: place the rocks and open the door!

The first line will consists of two integers n and x, denoting the size of the room and the number of sounds required to open the door. There will be exactly three test cases for this problem:   n = 5, x = 5;  n = 3, x = 2;  n = 100, x = 105.  All of these testcases are in pretest.

Output n lines. Each line consists of n characters — the j-th character of the i-th line represents the content of the tile at the i-th row and the j-th column, and should be one of these:   '^', '<', '>', or 'v': a rock as described in the problem statement.  '.': an empty tile.  Then, output two integers r and c (1 ≤ r, c ≤ n) on the next line — this means that the rock you activate first is located at the r-th row from above and c-th column from the left. There must be a rock in this cell. If there are multiple solutions, you may output any of them.

NoteHere's a simulation of the first example, accompanied with the number of sounds produced so far.  0 sound   1 sound   2 sounds   3 sounds   4 sounds   still 4 sounds In the picture above, the activated rock switches between the '^' rock and the '<' rock. However, no sound is produced since the '^' rock didn't move even a single tile. So, still 4 sound.  5 sounds At this point, 5 sound are already produced, so this solution is already correct. However, for the sake of example, we will continue simulating what happens.  6 sounds   7 sounds   still 7 sounds   8 sounds And the movement stops. In total, it produces 8 sounds. Notice that the last move produced sound.Here's a simulation of the second example:  0 sound   1 sound   2 sounds Now, the activated stone will switch continuously from one to another without producing a sound until it reaches the 107 limit, after which the movement will cease.  In total, it produced exactly 2 sounds, so the solution is correct.

<?php
/** SECTION 0: NOTES **/
/*
Problem:
Codeforces Contest 192 Div 1 Problem D

Author          : chaotic_iak (http://chaoticiak.comlu.com/)
Language        : PHP 5.4
Released under  : CC BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/)
Template version: 20130720 (http://chaoticiak.comlu.com/prog/assorted/templates.phps)
                           (http://ideone.com/AV2T2U)
*/

/** SECTION 1: SET UP INPUT HANDLER **/
// 0: Don't output format at all
// 1: Trim newline characters only
// 2: Assume \x00..\x20 (accaw) as delimiters and output as array

if (isset($inputstream)) {$stdin = $inputstream;} else {$stdin = fopen("php://stdin", "r");}
function g($format = 2) {
    global $stdin;
    $input = fgets($stdin);
    if ($format == 0) {return $input;}
    $input = trim($input, "\n\r");
    if ($format == 1) {return $input;}
    $input = trim($input, "\x00..\x20");
    $input = preg_replace("/[\\x00-\\x20]+/", " ", $input);
    return explode(" ", $input);
}

/** SECTION 2: IMPORTING FUNCTIONS FROM chaotic_iak'S LIBRARY **/
// none

/** SECTION 3: SOLVING THE PROBLEM **/
$n = g(1);

switch ($n) {
	case "5 5":
		echo ">...v
v.<..
..^..
>....
..^.<
1 1";
		break;
	case "3 2":
		echo "..v
...
^.<
1 3";
		break;
	case "100 100000":	// dolphinigle's solution according to tutorial, because when browsing through his submissions I don't find this one (only a 105k one)
		echo "v<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v>v^
v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.v.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^.^.^.^.^.^.^.^.^.^.^.^
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^
v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^v^
.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^.^
>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^>^
....................................................................................................
1 1";
}


Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.

The first line contains two integers n and f (1 ≤ n ≤ 105, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out. Each line of the following n subsequent lines contains two integers ki, li (0 ≤ ki, li ≤ 109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.

Print a single integer denoting the maximal number of products that shop can sell.

NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out.


In an ICPC contest, balloons are distributed as follows:   Whenever a team solves a problem, that team gets a balloon.  The first team to solve a problem gets an additional balloon.  A contest has 26 problems, labelled $$$\textsf{A}$$$, $$$\textsf{B}$$$, $$$\textsf{C}$$$, ..., $$$\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.

For each test case, output a single integer — the total number of balloons that the teams received.

6

3

ABA

1

A

3

ORZ

5

BAAAA

4

BKPT

10

CODEFORCES

NoteIn the first test case, $$$5$$$ balloons are given out:   Problem $$$\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.  Problem $$$\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{B}$$$.  Problem $$$\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\textsf{A}$$$.  The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.

<?php

$cnt = readline();
$res = array();
while ($cnt--) {
    $a = readline();
    $s = readline();
    $a = str_split($s);
    $bf = array();
    $i = 0;
    foreach ($a as $str) {
        if (isset($bf[$str])) {
            $i++;
        } else {
            $bf[$str] = 1;
            $i++;
            $i++;
        }
    }

    $res[] = $i;

}

foreach ($res as $i => $ss) {
    $d = "\n";
    if ($i == count($res) - 1) {
        $d='';
    }
    echo $ss . $d;
}

<?php

function solve()
{
	$n = readline();
	$s = readline();
	$arr = [];
	$ans = 0;
	for($i = 0;$i < strlen($s);$i++)
	{
		if(isset($arr[$s[$i]]))
			$ans++;
		else
			$ans += 2;
		$arr[$s[$i]] = 1;
	}
	echo $ans . "\n";
}

$t = readline();
while($t--)
{
	solve();
}

<?php
$n = ReadLine();
while($n--) {
    $x = (int) ReadLine();
    $string = (string) ReadLine();
    $string = str_split($string);
    sort($string);
    $ans = 0;
    for ($i = 0; $i < count($string) - 1; $i++) {
        if ($string[$i] == $string[$i + 1]) {
            $ans++;
        }else {
            $ans += 2;
        }
    }
    echo $ans + 2 . "\n";
}

<?php

$t = intval(readline());

$i = 0;

$final_result = [];

while($i++ < $t) {
    $results = [];
    $len = intval(readline());

    $str = readline();

    foreach(str_split($str) as $char) {
        if(isset($results[$char])) {
            $results[$char]++;
        } else {
            $results[$char] = 1;
        }
    }

    array_push($final_result, $results);
}

foreach($final_result as $result) {

    $count = count($result) + array_reduce($result, function($c2, $i2) {
            return $c2 + $i2;
        }, 0);

    echo $count . PHP_EOL;
}

<?php
$test_case = readline();
for($i = 0; $i < $test_case; $i++) {
  $str_len = readline();
  $str_value = readline();
   $str_arr = array();
      $count = 0;
  $str_value = str_split($str_value, 1);
  for($j=0;$j<$str_len;$j++) {
  	if(in_array($str_value[$j], $str_arr)) {
  	    $count+=1;
  	    array_push($str_arr, $str_value[$j]);
  	} else {
       $count+=2;
  	   array_push($str_arr, $str_value[$j]);
  	}
  }
    echo $count;
  	echo "\n";
  	unset($str_arr);
  	unset($count);
}

<?php
fscanf(STDIN, "%d", $t);
while ($t--) {
    fscanf(STDIN, "%d", $n);
    fscanf(STDIN, "%s", $s);
    printf("%d\n", $n+count(array_unique(str_split($s))));
}

<?php

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

function readInt() {
	return (int) read() ;
}

function readStrs() {
	return explode(" ",read()) ;
}

function readIntArray() {
	return array_map('intval', readStrs());
}

function readAsArray() {
	return str_split(read()) ;
}

function printLine($arg) {

	print_r($arg) ;
	print_r("\n") ;

}

$t = readInt() ;

while($t--) {
	$n = readInt() ;
	$arr = readAsArray() ;
	$cnt = array_count_values($arr) ;
	$sum = array_sum($cnt) ;
	printLine($sum + count($cnt));
}

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

$loop = true;
$t = $loop ? IO::get() : 1;
while($t--) {
    solve();
}
//6
//3
//ABA
function solve()
{
    $n = IO::get();
    $s = IO::get();

    $ans = 0;
    $tt= [];
    for($i=0; $i<$n; $i++) {
        if(isset($tt[$s[$i]])) {
            $ans++;
        } else {
            $ans += 2;
            $tt[$s[$i]] = 1;
        }
    }
    IO::pr($ans);

}

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

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

<?php

$cnt = readline();
$res = array();
while ($cnt--) {
    echo $cnt . "\n";
    $a = readline();
    $s = readline();
    $a = str_split($s);
    $bf = array();
    $i = 0;
    foreach ($a as $str) {
        if (isset($bf[$str])) {
            $i++;
        } else {
            $bf[$str] = 1;
            $i++;
            $i++;
        }
    }

    $res[] = $i;

}

foreach ($res as $i => $ss) {
    $d = "\n";
    if ($i == count($res) - 1) {
        $d='';
    }
    echo $ss . $d;
}

<?php

$cnt = readline();
$res = array();
while ($cnt--) {
    echo $cnt . "\n";
    $a = readline();
    $s = readline();
    $a = str_split($s);
    $bf = array();
    $i = 0;
    foreach ($a as $str) {
        if (isset($bf[$str])) {
            $i++;
        } else {
            $bf[$str] = 1;
            $i++;
            $i++;
        }
    }

    $res[] = $i;

}

foreach ($res as $ss) {
    echo $ss . "\n";
}

<?php

$cnt = readline();
$res = array();
while ($cnt--) {
    $s = readline();
    $a = str_split($s);
    $bf = array();
    $i = 0;
    foreach ($a as $str) {
        if (isset($bf[$str])) {
            $i++;
        } else {
            $i++;
            $i++;
        }
    }

    $res[] = $i;

}

foreach ($res as $ss) {
    echo $ss . "\n";
}


And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

<?php
function equal($a,$b){
   $FPS=0.00000001;
   return $a-$FPS<$b&&$b<$a+$FPS;
}
list($n,$vb,$vs)=explode(" ",trim(fgets(STDIN)));
$x=explode(" ",trim(fgets(STDIN)));
list($px,$py)=explode(" ",trim(fgets(STDIN)));
$min=10000000;
$d=10000000;
for($i=1;$i<$n;$i++){
  $time=$x[$i]/$vb;
  $xx=$x[$i]-$px;
  $yy=$py;
  $time+=sqrt($xx*$xx+$yy*$yy)/$vs;
  if($min>$time){
     $min=$time;
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }else if(equal($min,$time)&&$d>sqrt($xx*$xx+$yy*$yy)){
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }
}
print(($tn+1));
?>

<?php

$EPS = 1e-6;

class Result {
	function __construct($a, $b, $i) {
		$this->a = $a;
		$this->b = $b;
		$this->i = $i;
	}
	function less($r) {
		global $EPS;
		return abs($this->a - $r->a) > $EPS ? $this->a < $r->a : $this->b < $r->b;
	}
}

function dist($x1, $y1, $x2, $y2) {
	return sqrt(($x1 - $x2)**2 + ($y1 - $y2)**2);
}

fscanf(STDIN, "%d %d %d", $n, $vb, $vs);
$line = fgets(STDIN);
$x = array_map("intval", explode(' ', $line));
//print_r($x);
fscanf(STDIN, "%d %d", $dx, $dy);

$answer = new Result(1e9, 0, -1);
for ($i = 1; $i < $n; $i++) {
	$d = dist($x[$i], 0, $dx, $dy);
	$t = $x[$i] / $vb + $d / $vs;
	$candidate = new Result($t, $d, $i);
	if ($candidate->less($answer))
		$answer = $candidate;
}
print $answer->i + 1;

?>

<?
$fp=fopen('php://stdin', 'r');
$lines=stream_get_contents($fp);
$lines = trim($lines);

$lines=explode("\n", $lines);

list ($n, $bus_speed, $student_speed)=explode(" ", trim($lines[0]));
$stops_x=explode(" ", trim($lines[1]));
list($un_x, $un_y)=explode(" ", trim($lines[2]));
for ($i=1; $i<count($stops_x); $i++)
{
    $n=$i+1;
    $stop[$n]['bus_time']=$stops_x[$i]/$bus_speed;
    $stop[$n]['run_time']=(sqrt(($un_x-$stops_x[$i])*($un_x-$stops_x[$i])+($un_y-0)*($un_y-0)))/$student_speed;
    $stop[$n]['all_time']=$stop[$n]['bus_time']+$stop[$n]['run_time'];
}

$min_time=$stop[2]['all_time'];
$min_run_time=$stop[2]['run_time'];
$num=2;

for ($n=3; $n<count($stop)+2; $n++)
{
    if ($stop[$n]['all_time']<$min_time or ($stop[$n]['all_time']==$min_time and $stop[$n]['run_time']<$min_run_time))
    {
        $min_time=$stop[$n]['all_time'];
        $min_run_time=$stop[$n]['run_time'];
        $num=$n;
    }
}

echo $num;
?>

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

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

list($n, $vb, $vs) = inputarray();
$x = inputarray();
list($xu, $yu) = inputarray();
$besttime = 1e18;
$ret = 1;
for ($i = 1; $i < $n; $i++)
{
    $time = (double)$x[$i] / $vb + hypot($x[$i] - $xu, $yu) / $vs;
    if ($time < $besttime + 1e-9)
    {
        $besttime = $time;
        $ret = $i + 1;
    }
}
echo "$ret\n";
?>

<?php
list($n,$vb,$vs)=explode(" ",trim(fgets(STDIN)));
$x=explode(" ",trim(fgets(STDIN)));
list($px,$py)=explode(" ",trim(fgets(STDIN)));
$min=10000000;
$d=10000000;
for($i=1;$i<$n;$i++){
  $time=$x[$i]/$vb;
  $xx=$x[$i]-$px;
  $yy=$y[$i];
  $time+=sqrt($xx*$xx+$yy*$yy)/$vs;
  if($min>$time){
     $min=$time;
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }else if($min==$time&&$d>sqrt($xx*$xx+$yy*$yy)){
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }
}
print(($tn+1));
?>

<?php
	$fr = fopen("php://stdin","r");
	$input = fgets($fr);
	list( $n, $b, $s ) = explode(' ', $input);
	$input = fgets($fr);
	$stops = explode(' ', $input);
	$input = fgets($fr);
	list( $x, $y ) = explode(' ', $input);
	fclose ($fr);

	if ( $n == 2 )
		die('2');

function dist($x1, $y1, $x2, $y2)
{
	$x = $x2 - $x1;
	$y = $y2 - $y1;
	return sqrt( $x*$x + $y*$y );
}

	$o = 1;
	$r = array();
	for ( $i = 0; $i < $n; $i+= 1 )
	{
		$r[$i] = dist(0,0,$stops[$i],0) * $b + dist($stops[$i],0,$x,$y) * $s;
		if ( isset($r[$o]) && ($r[$o] > $r[$i]) )
			$o = $i;
	}
	echo max($o, 2);
?>

<?php
	$fr = fopen("php://stdin","r");
	$input = fgets($fr);
	list( $n, $b, $s ) = explode(' ', $input);
	$input = fgets($fr);
	$stops = explode(' ', $input);
	$input = fgets($fr);
	list( $x, $y ) = explode(' ', $input);
	fclose ($fr);

	if ( $n == 2 )
		die('2');

function dist($x1, $y1, $x2, $y2)
{
	$x = $x2 - $x1;
	$y = $y2 - $y1;
	return sqrt( $x*$x + $y*$y );
}

	$b = (float)$b;
	$s = (float)$s;
	$o = 1;
	$r = array();
	for ( $i = 0; $i < $n; $i+= 1 )
	{
		$r[$i] = (float)$stops[$i] / $b + dist($stops[$i],0,$x,$y) / $s;
		if ( isset($r[$o]) && ($r[$o] > $r[$i]) )
			$o = $i;
	}
	echo max($o+1, 2);

?>

<?php

$EPS = 1e-6;

class Result {
	function __construct($a, $b, $i) {
		$this->a = $a;
		$this->b = $b;
		$this->i = $i;
	}
	function less($r) {
		global $EPS;
		return abs($this->a - $r->a) > $EPS ? $this->a < $r->a : $this->b < $r->b;
	}
}

function dist($x1, $y1, $x2, $y2) {
	return sqrt(($x1 - $x2)**2 + ($y1 - $y2)**2);
}

fscanf(STDIN, "%d %d %d", $n, $vb, $vs);
$line = fgets(STDIN);
$x = array_map("intval", explode(' ', $line));
//print_r($x);
fscanf(STDIN, "%d %d", $dx, $dy);

$answer = new Result(1e9, 0, -1);
for ($i = 1; $i < $n; $i++) {
	$d = dist($x[$i], 0, $dx, $dy);
	$t = $x[$i] / $vb + $d / $vs;
	$candidate = new Result($t, $d, $i);
	if ($candidate->less($answer))
		$answer = $candidate;
}
print($answer->i + 1);
?>

<?php
list($n,$vb,$vs)=explode(" ",trim(fgets(STDIN)));
$x=explode(" ",trim(fgets(STDIN)));
list($px,$py)=explode(" ",trim(fgets(STDIN)));
$min=10000000;
for($i=1;$i<$n;$i++){
  $time=$x[$i]/$vb;
  $xx=$x[$i]-$px;
  $yy=$y[$i];
  $time+=sqrt($xx*$xx+$yy*$yy)/$vs;
  if($min>$time){
     $min=$time;
     $tn=$i;
  }
}
print(($tn+1));
?>

<?php
function equal($a,$b){
   $FPS=0.00000001;
   return $a-$FPS<$b&&$b<$a+$FPS;
}
list($n,$vb,$vs)=explode(" ",trim(fgets(STDIN)));
$x=explode(" ",trim(fgets(STDIN)));
list($px,$py)=explode(" ",trim(fgets(STDIN)));
$min=10000000;
$d=10000000;
for($i=1;$i<$n;$i++){
  $time=$x[$i]/$vb;
  $xx=$x[$i]-$px;
  $yy=$y[$i];
  $time+=sqrt($xx*$xx+$yy*$yy)/$vs;
  if($min>$time){
     $min=$time;
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }else if(equal($min,$time)&&$d>sqrt($xx*$xx+$yy*$yy)){
     $tn=$i;
     $d=sqrt($xx*$xx+$yy*$yy);
  }
}
print(($tn+1));
?>


A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.


Little Leon lives in the forest. He has recently noticed that some trees near his favourite path are withering, while the other ones are overhydrated so he decided to learn how to control the level of the soil moisture to save the trees.There are $$$n$$$ trees growing near the path, the current levels of moisture of each tree are denoted by the array $$$a_1, a_2, \dots, a_n$$$. Leon has learned three abilities which will help him to dry and water the soil.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$1, 2, \dots, i$$$ by $$$1$$$.  Choose a position $$$i$$$ and decrease the level of moisture of the trees $$$i, i + 1, \dots, n$$$ by $$$1$$$.  Increase the level of moisture of all trees by $$$1$$$. Leon wants to know the minimum number of actions he needs to perform to make the moisture of each tree equal to $$$0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$)  — the number of test cases. The description of $$$t$$$ test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 200\,000$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) — the initial levels of trees moisture.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$200\,000$$$.

For each test case output a single integer — the minimum number of actions. It can be shown that the answer exists.

NoteIn the first test case it's enough to apply the operation of adding $$$1$$$ to the whole array $$$2$$$ times. In the second test case you can apply the operation of decreasing $$$4$$$ times on the prefix of length $$$3$$$ and get an array $$$6, 0, 3$$$. After that apply the operation of decreasing $$$6$$$ times on the prefix of length $$$1$$$ and $$$3$$$ times on the suffix of length $$$1$$$. In total, the number of actions will be $$$4 + 6 + 3 = 13$$$. It can be shown that it's impossible to perform less actions to get the required array, so the answer is $$$13$$$.

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

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

function solve()
{
     $n = IO::get();
     $a = IO::getArray();
    $ans = 0;
     $p = $a[0];
    for ($i = 0; $i < $n - 1; $i++){
      if ($a[$i] < $a[$i + 1]){
        $ans = bcadd($ans, bcsub($a[$i + 1], $a[$i]));
      } else {
        $ans = bcadd($ans, bcsub($a[$i],  $a[$i + 1]));
        $p = bcsub($p, bcsub($a[$i],  $a[$i + 1]));
      }
    }
    $p = bccomp($p, '0') == 1 ? $p : bcmul($p, '-1');
    $ans =  bcadd($ans, $p);

       IO::pr($ans);

}

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

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

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

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

function solve()
{
     $n = IO::get();
     $a = IO::getArray();
    $ans = 0;
     $p = $a[0];
    for ($i = 0; $i < $n - 1; $i++){
      if ($a[$i] < $a[$i + 1]){
        $ans = bcadd($ans, bcsub($a[$i + 1], $a[$i]));
      } else {
        $ans = bcadd($ans, bcsub($a[$i],  $a[$i + 1]));
        $p -= bcsub($a[$i],  $a[$i + 1]);
      }
    }
    $p = bccomp($p, '0') == 1 ? $p : bcmul($p, '-1');
    $ans =  bcadd($ans, $p);

       IO::pr($ans);

}

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

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

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

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

function solve()
{
     $n = IO::get();
     $a = IO::getArray();
    $ans = 0;
     $p = $a[0];
    for ($i = 0; $i < $n - 1; $i++){
      if ($a[$i] < $a[$i + 1]){
        $ans = bcadd($ans, bcsub($a[$i + 1], $a[$i]));
      } else {
        $ans = bcadd($ans, bcsub($a[$i],  $a[$i + 1]));
        $p -= bcsub($a[$i],  $a[$i + 1]);
      }
    }
    $ans =  bcadd($ans, abs($p));

       IO::pr($ans);

}

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

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

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

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

function solve()
{
     $n = IO::get();
     $a = IO::getArray();
    $ans = 0;
     $p = $a[0];
    for ($i = 0; $i < $n - 1; $i++){
      if ($a[$i] < $a[$i + 1]){
        $ans = bcadd($ans, $a[$i + 1] - $a[$i]);
      } else {
        $ans = bcadd($ans,$a[$i] - $a[$i + 1]);
        $p -= $a[$i] - $a[$i + 1];
      }
    }
    $ans =  bcadd($ans, abs($p));

       IO::pr($ans);

}

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

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

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

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

function solve()
{
     $n = IO::get();
     $a = IO::getArray();
    $ans = 0;
     $p = $a[0];
    for ($i = 0; $i < $n - 1; $i++){
      if ($a[$i] < $a[$i + 1]){
        $ans += $a[$i + 1] - $a[$i];
      } else {
        $ans += $a[$i] - $a[$i + 1];
        $p -= $a[$i] - $a[$i + 1];
      }
    }
    $ans += abs($p);

       IO::pr($ans);

}

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

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


The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

<?php

    list($n, $k) = explode(" ", trim(fgets(STDIN)));
    $a = explode(" ", trim(fgets(STDIN)));
    $map = array();

    $left = 0; $right = 0; $max = -1; $l = 0; $r = 0;
    while (1) {
        if ($right == $n) break;
        $map[$a[$right]] = isset($map[$a[$right]]) ? $map[$a[$right]] + 1 : 1;
        while (count($map) > $k) {
            if (isset($map[$a[$left]])) {
                $s = $map[$a[$left]];
                if ($s == 1) unset($map[$a[$left]]); else $map[$a[$left]] = $s - 1;
            }
            $left++;
        }

        if ($right - $left > $max) {
            $l = $left + 1;
            $r = $right + 1;
            $max = $right - $left;
        }
        $right++;
    }

    echo $l . " " . $r;


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

<?
fscanf(STDIN, "%d", $n);
$c = 1;
foreach (explode(" ", fgets(STDIN)) as $t) {
    $s += ($t - $c + $n) % $n;
    $c = $t;
}
echo $s;
?>

<?php
list($n, $m) = explode(' ', trim(fgets(STDIN)));
$a = explode(' ', trim(fgets(STDIN)));
$i = 1;
$r = 0;
foreach($a as $s) {
 if($s < $i) {
  $r += $s + $n - $i;
  $i = $s;
 } elseif($s > $i) {
  $r += $s - $i;
  $i = $s;
 }
}
echo $r;
?>

<?php
$length=0;
list ($nDomov,$nDel) = explode(" ",trim(fgets(STDIN)));
$poryadok = explode(" ",trim(fgets(STDIN)));
array_unshift($poryadok,"1");
$currentHome = 1;
for ($i=1;$i<count($poryadok);$i++)
{
    if ($poryadok[$i]>$poryadok[$i-1])
    {
        $length+=($poryadok[$i]-$poryadok[$i-1]);
    }
    elseif ($poryadok[$i]<$poryadok[$i-1])
    {
        $length+=($nDomov-$poryadok[$i-1]+$poryadok[$i]);
    }
}
echo $length;

<?php
// 339B     Ксюша и кольцевая дорога
$in = fopen("php://stdin", 'r');

$input_line = fgets($in);
list($n, $m) = preg_split('/ /', substr($input_line, 0, strlen($input_line)-2), -1, PREG_SPLIT_NO_EMPTY);
$n = (int) $n;
$m = (int) $m;

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

$min = 0;
$house = 1;

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

    $pos = (int) $arr[$i];

    if ($house <= $pos) {
        $min += $pos - $house;
    } else {
        $min += $n - $house + $pos;
    }

    $house = $pos;

//    echo "i=$i house=$house min=$min pos=$pos \n";
}

echo $min;

?>

<?php

$line = trim(fgets(STDIN));
$argv = explode(' ', $line);

//var_dump($argv);

$n = intval($argv[0]);
$m = intval($argv[1]);

$answer = 0;
$from = 1;

$line = trim(fgets(STDIN));
$array = explode(' ', $line);

for ($i = 0; $i < $m; $i ++) {
  $to = $array[$i];
  $answer += ($to - $from + $n) % $n;
  $from = $to;
}

print $answer;

?>

<?php
/*
Ксюша живет в городе, в котором на главной кольцевой дороге находятся n домов. Дома кольцевой пронумерованы от 1 до n по часовой стрелке, по счастливой случайности движение на кольцевой одностороннее и организовано также по часовой стрелке.

Недавно Ксюша переехала на кольцевую в дом с номером 1. В связи с переездом у нее появилось m дел, чтобы сделать i-ое дело, нужно находиться в доме с номером ai, а также сделать все дела с номерами меньше i. Изначально, Ксюша находится в доме с номером 1, найдите какое минимальное количество времени ей нужно потратить, чтобы выполнить все дела, если на переезд между двумя соседними домами на кольцевой требуется одна единица времени.
*/

fscanf(STDIN, "%d%d", $n, $m);	// количество домов и количество дел

$tasks = fgets(STDIN);
$tasks = trim($tasks);
$tasks = explode(' ', $tasks);
array_unshift($tasks, 1);

$result = 0;
$i = 0;
while ($i < $m) {
	if($tasks[$i + 1] >= $tasks[$i]) {
		$result += $tasks[$i + 1] - $tasks[$i];
	} else {
		// что делать, если нужно ехать вспять, а нельзя и придется делать весь круг?
		$result += $n - ($tasks[$i] - $tasks[$i + 1]);
	}
	$i++;
}

echo $result;

<?php
error_reporting("off");
//339B: Xenia and Ringroad
//Lesson of the day: Functions like global variables.
list($n, $m) = explode(" ", trim(fgets(STDIN))); //$n = 4; $m = 3;
$a = explode(" ", trim(fgets(STDIN))); //$a = explode(" ", "3 2 3");
$currenthouse = 1;
$time = 0;

function travel($from, $to) { //returns the time from house $from to house $to
    global $n;
    if ($to >= $from) {
        return $to - $from;
    } elseif ($to < $from) {
        $dif = $from - $to;
        return $n - $dif;
    }
}

for ($i = 0; $i < $m; $i++) {
    $time += travel($currenthouse, $a[$i]);
    $currenthouse = $a[$i];
}

echo $time;
?>

<?php

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

	$arr = array();
	$arr[0] = 1;
	$time = 0;
	$tmp = 0;

	for($i = 1; $i <= $m; $i++)
	{
		$tmp = 0;
		$tmp = trim(fgets(STDIN));
		$arr[$i] = $tmp;

		if($tmp >= $arr[$i-1])
		{
			$time += ($tmp - $arr[$i-1]);
		}
		else
		{
			$time += ($n - $arr[$i-1] + $tmp);
		}
	}

	fwrite(STDOUT, "$time");

?>

<?php
$length=0;
list ($nDomov,$nDel) = explode(" ",trim(fgets(STDIN)));
$poryadok = explode(" ",trim(fgets(STDIN)));
array_unshift($poryadok,"1");
$currentHome = 1;
for ($i=1;$i<$nDomov;$i++)
{
    if ($poryadok[$i]>$poryadok[$i-1])
    {
        $length+=($poryadok[$i]-$poryadok[$i-1]);
    }
    elseif ($poryadok[$i]<$poryadok[$i-1])
    {
        $length+=($nDomov-$poryadok[$i-1]+$poryadok[$i]);
    }
}
echo $length;

<?php
$length=0;
list ($nDomov,$nDel) = explode(" ",trim(fgets(STDIN)));
$poryadok = explode(" ",trim(fgets(STDIN)));
array_unshift($poryadok,"1");
$currentHome = 1;
var_dump($poryadok);
for ($i=1;$i<count($poryadok);$i++)
{
    if ($poryadok[$i]>$poryadok[$i-1])
    {
        $length+=($poryadok[$i]-$poryadok[$i-1]);
    }
    elseif ($poryadok[$i]<$poryadok[$i-1])
    {
        $length+=($nDomov-$poryadok[$i-1]+$poryadok[$i]);
    }
}
echo $length;


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain.

For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.

<?php

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

function readInt() {
  return (int) read() ;
}

function readStrs() {
  return explode(" ",read()) ;
}

function readIntArray() {
  return array_map('intval', readStrs());
}

function readAsArray() {
  return str_split(read()) ;
}

function puts($arg) {
  if($arg === true) print_r("true");
  elseif($arg === false) print_r("false");
  else {
    print_r($arg) ;
  }
  print_r("\n") ;
}
//-----------------------------------//

$t = readInt() ;
while($t--){
  $a = readInt() ;
  $arr = [] ;
  for($i=1;$i<=$a;$i++) {

    $arr[] = $i ;
  }
  // puts($arr);
  puts($a) ;
  puts(implode(' ',$arr)) ;
  for($i=0;$i<$a-1;$i++) {
    $tem = $arr[$i+1] ;
    $arr[$i+1] = $arr[$i] ;
    $arr[$i] = $tem ;
    puts(implode(' ',$arr)) ;
  }
}


In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.A string is a bHTML table, if it satisfies the grammar: TABLE ::=
ROWS
ROWS ::= ROW | ROW ROWSROW ::=
CELLS
CELLS ::= CELL | CELL CELLSCELL ::= 	 | TABLE	Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.

For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.

Print the sizes of all the tables in the non-decreasing order.


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$  — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$

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

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

function solve()
{
     $n = IO::getInt();
    $a = IO::getArray();

     $nw = 0;
    $ch = true;
    $pos = $n-1;
    for ($i = 0; $i < $n-1; $i++) {
        if ($nw > $a[$i]) {
            $ch = false;
            break;
        } else if ($nw == $a[$i]) {
            $pos = $i;
            $nw = 0;
            break;
        }
        $nw = -($a[$i] - $nw);
    }
    for ($j = $pos + 1; $j < $n; $j++) {
        if ($a[$j] != 0) {
            $ch = false;
            break;
        }
    }
    if (!$ch || $nw != $a[$n - 1]) {
       IO::pr("No");
    } else {
       IO::pr("YES");
    }
}

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

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

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

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

function solve()
{
     $n = IO::getInt();
    $a = IO::getArray();

     $nw = 0;
    $ch = true;
    $pos = $n;
    for ($i = 0; $i < $n; $i++) {
        if ($nw > $a[$i]) {
            $ch = false;
            break;
        } else if ($nw == $a[$i]) {
            $pos = $i;
            $nw = 0;
            break;
        }
        $nw = -($a[$i] - $nw);
    }
    for ($j = $pos + 1; $j < $n; $j++) {
        if ($a[$j] != 0) {
            $ch = false;
            break;
        }
    }
    if (!$ch || $nw != $a[$n - 1]) {
       IO::pr("No");
    } else {
       IO::pr("YES");
    }
}

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

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


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).


Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out the name of the company on a piece of paper in a line (horizontally, from left to right) with large English letters, then put this piece of paper in front of the mirror, then the reflection of the name in the mirror should perfectly match the line written on the piece of paper.There are many suggestions for the company name, so coming up to the mirror with a piece of paper for each name wouldn't be sensible. The founders of the company decided to automatize this process. They asked you to write a program that can, given a word, determine whether the word is a 'mirror' word or not.

The first line contains a non-empty name that needs to be checked. The name contains at most 105 large English letters. The name will be written with the next sans serif font:

Print 'YES' (without the quotes), if the given name matches its mirror reflection. Otherwise, print 'NO' (without the quotes).

<?php

function FindMirrorWord($string){

    $mirror_reflection_words = 'AHIMOTUVWXY';
    $reverse_string          = strrev($string);
    $matches                 = 1;

    if($reverse_string==$string){
        for($i=0;$i<strlen($string);$i++){
            if (strpos($mirror_reflection_words, $reverse_string[$i]) === false){
                $matches = 0;
                break;
            }
        }
    }
    else{
        $matches = 0;
    }

    if($matches==0)
        return 'NO';
    else
        return 'YES';
}

$string      = trim(fgets(STDIN));
echo FindMirrorWord($string);

<?php

$forward = str_split(trim(fgets(STDIN)));

$reflectable = array('A'=>1, 'H'=>1, 'I'=>1, 'M'=>1, 'O'=>1, 'T'=>1, 'U'=>1, 'V'=>1, 'W'=>1, 'X'=>1, 'Y'=>1);

$n = sizeof($forward);
for($i = 0; $i < $n; $i++)
{
	if($forward[$i] != $forward[($n - $i - 1)] || !@isset($reflectable[$forward[$i]]))
	{
		echo "NO" . PHP_EOL;
		exit;
	}
}

echo "YES" . PHP_EOL;

<?php
	$s = trim(fgets(STDIN));
	echo (substr_count($s,'A')+substr_count($s,'H')+substr_count($s,'I')+substr_count($s,'M')+substr_count($s,'O')+substr_count($s,'T')+substr_count($s,'U')+substr_count($s,'V')+substr_count($s,'W')+substr_count($s,'X')+substr_count($s,'Y') == strlen($s) && $s == strrev($s)) ? 'YES' : 'NO';
?>

<?php

function FindMirrorWord($string){

    $mirror_reflection_words = 'AHIMOTUVWXY';
    $reverse_string          = strrev($string);
    $matches                 = 1;

    if($reverse_string==$string){
        for($i=0;$i<count($string);$i++){
            if (strpos($mirror_reflection_words, $reverse_string[$i]) === false){
                $matches = 0;
                break;
            }
        }
    }
    else{
        $matches = 0;
    }

    if($matches==0)
        return 'NO';
    else
        return 'YES';
}

$string      = trim(fgets(STDIN));
echo FindMirrorWord($string);

<?php

$front = str_split(trim(fgets(STDIN)));
$rev = array_reverse($front);

$front = implode($front);
$rev = implode($rev);

echo ($front == $rev && strlen($front) > 1) ? "YES" : "NO";


The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Print a single integer, the number of crimes which will go untreated.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

<?php

# https://codeforces.com/contest/427/problem/A
# A. Police Recruits
# sample input =>
#3
#-1 -1 1
# sample output => 2
# scihesham

/* code forces */
$num = trim(fgets(STDIN));
$arr = explode(" ", trim(fgets(STDIN)));
/**/

$police_num = 0;
$crime_num = 0;

foreach($arr as $val){
    if($val > 0){
        $police_num += $val;
    }
    else{
        if($val + $police_num < 0){
            $crime_num++;
        }
        else{
            $police_num--;
        }
    }

}

echo $crime_num;

?>

<?php
fscanf(STDIN, "%d", $n);
$str = "";
for ($j=0; $j<$n; $j++) {
    $str .= "%s ";
}
$i = fscanf(STDIN, $str);

$toSolve = 0;
$unSolved = 0;
for ($k=0; $k<$n; $k++) {
	if ($i[$k] == -1) {
		if ($toSolve > 0) {
			$toSolve--;
		}
		else $unSolved++;
	}
	else {
		$toSolve += $i[$k];
	}
}
echo $unSolved;

?>

<?php

//=====================================
// link: https://codeforces.com/contest/427/problem/A
//=====================================

// get inputs
$events_count = trim(fgets(STDIN));
$events       = explode(' ', trim(fgets(STDIN)));

// solution
$officers         = 0;
$untreated_crimes = 0;

for ($i = 0; $i < $events_count; $i++) {
    if ($events[$i] == -1) {
        if ($officers == 0) {
            $untreated_crimes++;
            continue;
        }

        $officers--;
        continue;
    }

    $officers += $events[$i];
}

echo "$untreated_crimes\n";

<?php
$n=trim(fgets(STDIN));
$input=trim(fgets(STDIN));
$input=explode(' ',$input);
// var_dump($input);
$e=0;
$j=0;
foreach ($input as $key => $value) {
      if($value == -1){
          if($e != 0){
            $e--;
          }else{
                $j++;
          }
      }else{
            $e+=$value;
      }
}
echo $j;

<?php
fscanf(STDIN,"%d",$n);
$line=trim(fgets(STDIN));
$singleValue=explode(' ', $line);
$sum=0;
$count=0;
for($i=0;$i<$n;$i++)
{
	if($singleValue[$i]>0)
		$sum+=$singleValue[$i];
	elseif ($sum>0) {
		$sum--;
	}
	else
		$count++;

}

echo "$count";

<?php

$vsego = readline();
$stroka = readline();
$stroka = explode(' ', $stroka);
$zapas = 0;
$prestup = 0;
foreach ($stroka as $v) {

    if ($v>0){
        $zapas = $zapas+$v;
     }

    if ($v<0){
        $prestup = $prestup +1;
        if ($zapas != 0) {
            $zapas = $zapas -1;
            $prestup = $prestup -1;
        }
    }

}
echo $prestup;

<?php

$stdout = fopen(getenv("OUTPUT_PATH"), "w");
$stdin = fopen("php://stdin", "r");

fscanf($stdin, "%d", $n);
fscanf($stdin, "%[^\n]", $str);
$arr = array_map( 'intval' , preg_split('/ /' , $str , -1 , PREG_SPLIT_NO_EMPTY ) );

$crimes = 0 ;
$police = 0 ;

for( $i=0 ; $i<$n ; $i++)
{
     if( $arr[$i] > 0 )
     {
          $police += $arr[$i] ;
     }
     else
     {
          if( $police == 0)
          {
               $crimes++ ;
          }
          else
          {
               $police-- ;
          }
     }
}
echo $crimes ;
fwrite($stdout);

fclose($stdin);
fclose($stdout);

?>

<?php
$text = str_replace("\r", "", file_get_contents("php://stdin"));
list($n, $str) = explode("\n", $text);
$numbers = explode(" ", $str);

$p = 0;
$result = 0;
foreach ($numbers as $val) {
	if ($val > 0) {
		$p += $val;
	} else {
		if ($p == 0) {
			$result++;
		} else {
			$p--;
		}
	}
}

echo $result;

<?php
$fi=@fopen('test.inp',"r");
$n=trim(fgets(STDIN));
$a=explode(" ",trim(fgets(STDIN)));
$s=0;
$res=0;
for ($i=0;$i<$n;$i++){
	if ($s==0 && $a[$i]==-1) $res++;
	else $s+=$a[$i];
}
echo $res;
?>

<?php
$fp = fopen("php://stdin", "r");
$numEvents = trim(fgets($fp));
$events = explode(" ", trim(fgets($fp)));
fclose($fp);
$police = 0;
$crime = 0;
for ($i = 0; $i < $numEvents; $i++) {
	$x = $events[$i];
	if ($x > 0) {
		$police += $x;
	} else if ($police > 0 && $x == -1) {
		$police--;
	} else if ($police == 0 && $x == -1) {
		$crime++;
	}
}
echo $crime."\n";
?>

<?php
// 427A     Полицейские-рекруты
$in = fopen("php://stdin", 'r');

$input_line = fgets($in);

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

$col = 0;
$polic = 0;

foreach ($arr as $key => $value) {
    if ($value == '-1') {
        if ($polic > 0) {
            $polic --;
        } else {
            $col ++;
        }
    } else {
        $polic += (int) $value;
    }
}

echo $col;

?>

<?php
	$in = 'php://stdin';
//	$in = 'input.txt';

	$input = fopen($in, "r");

	$n = fgets($input);

	$a = explode(" ", fgets($input));

	$crimes = 0;
	$anticrimes = 0;

	for($i=0;$i<$n;$i++) {
		$anticrimes += $a[$i];

		if ($anticrimes<0) {$crimes++; $anticrimes=0;}
	}

	echo $crimes;
?>

<?php

$n = (int)fgets(STDIN);
$a = explode(' ', fgets(STDIN));

$output = 0;
$police = 0;

for ($i = 0; $i < $n; $i ++) {
	if ($a[$i] > 0) {
		$police += $a[$i];
	} elseif ($a[$i] == -1) {
		if ($police > 0) {
			$police --;
		} else {
			$output ++;
		}
	}
}

print $output;

<?php
$n = (int)fgets(STDIN);
$a = explode(" ", trim(fgets(STDIN)));
$ans = 0;
$cur = 0;
for ($i = 0; $i < count($a); ++$i)
{
    if ($a[$i] > 0)
        $cur += $a[$i];
    else
    {
        $cur -= 1;
        if ($cur < 0)
        {
            $cur = 0;
            ++$ans;
        }
    }
}
print $ans;
?>

<?php
fscanf(STDIN,"%d",$n);
$line=trim(fgets(STDIN));
$single=explode(' ', $line);

$count=0;
$j=0;
$l=0;
$sum=0;

for($i=$n-1;$i>=0;$i--) {
 	if($single[$i]=="-1")
 	{
       break;
 	}
 	$j++;

 }

 for($k=0;$k<$n-$j;$k++)

 {
 	if($single[$k]>0)
 	{
     break;
 	}
 	else $l++;
 }
 for($m=$l;$m<$n-$j;$m++)
 {
  $sum+=$single[$m];
 }

 if($sum>0)
 	echo "$l";
 else
 {
 	$count=$l-$sum;
 	echo "$count";
 }

 //print_r($single);

<?php
fscanf(STDIN,"%d",$n);
$line=trim(fgets(STDIN));
$single=explode(' ', $line);

$count=0;

for($i=0;$i<$n;$i++)
 {
 	if($single[$i]>0)
 	{
 		$i+=$single[$i];
 	}
 	else $count++;

 }
 echo $count;

 //print_r($single);

<?php
fscanf(STDIN,"%d",$n);
$line=trim(fgets(STDIN));
$single=explode(' ', $line);

$count=0;
$j=0;

for($i=$n-1;$i>=0;$i--) {
 	if($single[$i]=="-1")
 	{
       break;
 	}
 	$j++;

 }

 for($k=0;$k<$n-$j;$k++)
 	$count+=$single[$k];
 echo ltrim($count,'-');

 //print_r($single);


There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x.

Only one line containing two positive integers a and b (1 ≤ a, b ≤ 109).

Output the only line containing the answer. Your answer will be considered correct if its relative or absolute error doesn't exceed 10 - 9. If there is no such x then output  - 1 as the answer.

NoteYou can see following graphs for sample 1 and sample 3.

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
list($x, $y) = explode(" ", trim(fgets($file)));
$result = 0;
if ($y > $x) {
    $result = -1;
} else {
    $k = floor($x / $y);
    $k = $k%2 ? $k : $k-1;
    $x -= $k * $y;
    $result = $x / ($k+1);
    $result += $y;
}
echo $result;


Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = $$$2$$$, b = $$$3$$$ changes the value of a to $$$5$$$ (the value of b does not change).In a prototype program Leo has two integer variables a and b, initialized with some positive values. He can perform any number of operations "a += b" or "b += a". Leo wants to test handling large integers, so he wants to make the value of either a or b strictly greater than a given value $$$n$$$. What is the smallest number of operations he has to perform?

The first line contains a single integer $$$T$$$ ($$$1 \leq T \leq 100$$$) — the number of test cases. Each of the following $$$T$$$ lines describes a single test case, and contains three integers $$$a, b, n$$$ ($$$1 \leq a, b \leq n \leq 10^9$$$) — initial values of a and b, and the value one of the variables has to exceed, respectively.

For each test case print a single integer — the smallest number of operations needed. Separate answers with line breaks.

NoteIn the first case we cannot make a variable exceed $$$3$$$ in one operation. One way of achieving this in two operations is to perform "b += a" twice.

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

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

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

        $a = intval($in_str[0]) ;
        $b = intval($in_str[1]) ;
        $n = intval($in_str[2]) ;

        if($a < $b) list($a, $b) = array($b, $a) ;

        $ans = 0 ;
        while($a <= $n)
        {
            $b += $a ;
            if($a < $b) list($a, $b) = array($b, $a) ;

            $ans ++ ;
        }
        echo $ans . "\n" ;
    }
?>


You have an array $$$a$$$ of size $$$n$$$ consisting only of zeroes and ones. You can do the following operation:  choose two indices $$$1 \le i , j \le n$$$, $$$i \ne j$$$,  add $$$a_{i}$$$ to $$$a_{j}$$$,  remove $$$a_{i}$$$ from $$$a$$$. Note that elements of $$$a$$$ can become bigger than $$$1$$$ after performing some operations. Also note that $$$n$$$ becomes $$$1$$$ less after the operation.What is the minimum number of operations needed to make $$$a$$$ non-decreasing, i. e. that each element is not less than the previous element?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$), the size of array $$$a$$$. Next line contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots a_{n}$$$ ($$$a_i$$$ is $$$0$$$ or $$$1$$$), elements of array $$$a$$$. It's guaranteed that sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print a single integer, minimum number of operations needed to make $$$a$$$ non-decreasing.

NoteIn the first test case, $$$a$$$ is already non-decreasing, so you don't need to do any operations and the answer is $$$0$$$.In the second test case, you can perform an operation for $$$i = 1$$$ and $$$j = 5$$$, so $$$a$$$ will be equal to $$$[0, 0, 1, 2]$$$ and it becomes non-decreasing.In the third test case, you can perform an operation for $$$i = 2$$$ and $$$j = 1$$$, so $$$a$$$ will be equal to $$$[1]$$$ and it becomes non-decreasing.

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

echo implode(PHP_EOL,$ans);


Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

<?php

$t = (int)fgets(STDIN);

for($i=0; $i<$t; $i++){
    $n = (int)fgets(STDIN);
    $line1 = fgets(STDIN);
    $line2 = fgets(STDIN);

    $isBlocked = false;
    for($j=0; $j<$n; $j++){
        if($line1[$j] === '1' && $line2[$j] === '1'){
            $isBlocked = true;
            break;
        }
    }

    if($isBlocked){
        echo "NO\n";
    }else{
        echo "YES\n";
    }
}


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = 0;
for($x = 0; $x < $a; $x++)
{
     $e = ceil($c[$x] / $b);
     $d += $e;
}
$f = ceil($d / 2);
print $f;
?>

<?php
list($n, $k) = explode(' ',fgets(STDIN));
$cnt=0;
$a = explode(' ',fgets(STDIN));
for($i = 0; $i < $n; $i++){
    $x=$a[$i];
    $cnt+=(int)floor(($x+$k-1)/$k);
}
echo (int)floor(($cnt+1)/2) . "\n";

<?php
list($n, $k) = explode(' ',fgets(STDIN));
$cnt=0;
$a = explode(' ',fgets(STDIN));
for($i = 0; $i < $n; $i++){
    $x=$a[$i];
    echo $x . "\n";
    $cnt+=(int)floor(($x+$k-1)/$k);
}
echo (int)floor(($cnt+1)/2) . "\n";