Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times:  Choose one of her cards X. This card mustn't be chosen before.  If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then:   If Y's position is Attack, then (X's strength)  ≥  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength).  If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.  Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have. Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense. Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.

Output an integer: the maximal damage Jiro can get.

NoteIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.

<?php
/** chaotic_iak's solution in PHP 5.4 to the problem 321B (Round 190 Div 2 Problem D) in Codeforces **/

/** Module for retrieving input **/

// If this is a local test (a variable declared in a specialized page to open this script), open from localtest.txt instead of php://stdin (because I'm too lazy to supply the arguments by stdin)
if (isset($localtest)) {$stdin = fopen("localtest.txt", "r");} else {$stdin = fopen("php://stdin", "r");}

// A function to retrieve the next line. Takes one optional argument $single, which should be true if the next line (based on problem's specification) has only one number/string/whatever, so I don't have to do silly things like $raw = g(); $num = $raw[0];
function g($single = false) {

	// Take the global $stdin variable aka the file handler so we can access it from this function
	global $stdin;

	// Take the input from the handler, trim it, and explode it based on space (" 1 2 3 " becomes array("1", "2", "3")); trim is usually to remove trailing \r
	$input = explode(" ", trim(fgets($stdin)));

	// If the line is not a single number, return the whole array, otherwise simply return the single string that we exploded for nothing
	if (!$single) {return $input;} else {return $input[0];}
}

/** Imported functions from chaotic_iak's library **/
// none

/** chaotic_iak's solution **/
// This is a competitive programming solution. The code is not remarked (because I want speed).

$raw = g();
$n = $raw[0];
$m = $raw[1];
$atk = array();
$def = array();

for ($i = 0; $i < $n; $i++) {
	$raw = g();
	if ($raw[0] == "ATK") {$atk[] = $raw[1];} else {$def[] = $raw[1];}
}

for ($i = 0; $i < $m; $i++) {
	$own[$i] = g(true);
}

// sort
sort($own, SORT_NUMERIC);
sort($atk, SORT_NUMERIC);
sort($def, SORT_NUMERIC);

// strategy 1
// match all def, beat all atk, do direct damage
$atk1 = $atk;
$def1 = $def;
$own1 = $own;
$dmg = 0;

$i = 0;

$n = count($own1);

for ($j = 0; $j < $n; $j++) {
	if ($i >= count($def1)) {break;}
	if ($own1[$j] > $def1[$i]) {$i++; unset($own1[$j]);}
}

if ($i >= count($def1)) {

$own1 = array_values($own1);
sort($own1, SORT_NUMERIC);
$i = count($atk1)-1;

for ($j = count($own1)-1; $j >= 0; $j--) {
	if ($i < 0) {$dmg += $own1[$j];} else {
		if ($own1[$j] < $atk1[$i]) {break;} else {$dmg += $own1[$j] - $atk1[$i]; $i--;}
	}
}

}

$res = $dmg;

// strategy 2
// beat least atk with most power
$atk2 = $atk;
$own2 = $own;
$dmg = 0;

$i = 0;

for ($j = count($own2)-1; $j >= 0; $j--) {
	if ($i >= count($atk2)) {break;}
	if ($own2[$j] < $atk2[$i]) {break;} else {$dmg += $own2[$j] - $atk2[$i]; $i++;}
}

$res = ($res < $dmg) ? $dmg : $res;

echo $res;

<?php
/** chaotic_iak's solution in PHP 5.4 to the problem 321B (Round 190 Div 2 Problem D) in Codeforces **/

/** Module for retrieving input **/

// If this is a local test (a variable declared in a specialized page to open this script), open from localtest.txt instead of php://stdin (because I'm too lazy to supply the arguments by stdin)
if (isset($localtest)) {$stdin = fopen("localtest.txt", "r");} else {$stdin = fopen("php://stdin", "r");}

// A function to retrieve the next line. Takes one optional argument $single, which should be true if the next line (based on problem's specification) has only one number/string/whatever, so I don't have to do silly things like $raw = g(); $num = $raw[0];
function g($single = false) {

	// Take the global $stdin variable aka the file handler so we can access it from this function
	global $stdin;

	// Take the input from the handler, trim it, and explode it based on space (" 1 2 3 " becomes array("1", "2", "3")); trim is usually to remove trailing \r
	$input = explode(" ", trim(fgets($stdin)));

	// If the line is not a single number, return the whole array, otherwise simply return the single string that we exploded for nothing
	if (!$single) {return $input;} else {return $input[0];}
}

/** Imported functions from chaotic_iak's library **/
// none

/** chaotic_iak's solution **/
// This is a competitive programming solution. The code is not remarked (because I want speed).

$raw = g();
$n = $raw[0];
$m = $raw[1];
$atk = array();
$def = array();

for ($i = 0; $i < $n; $i++) {
	$raw = g();
	if ($raw[0] == "ATK") {$atk[] = $raw[1];} else {$def[] = $raw[1];}
}

for ($i = 0; $i < $m; $i++) {
	$own[$i] = g(true);
}

// sort
sort($own, SORT_NUMERIC);
sort($atk, SORT_NUMERIC);
sort($def, SORT_NUMERIC);

// strategy 1
// match all def, beat all atk, do direct damage
$atk1 = $atk;
$def1 = $def;
$own1 = $own;
$dmg = 0;

$i = 0;

for ($j = 0; $j < count($own1); $j++) {
	if ($i >= count($def1)) {break;}
	if ($own1[$j] > $def1[$i]) {$i++; unset($own1[$j]);}
}

if ($i >= count($def1)) {

$own1 = array_values($own1);
sort($own1);
$i = count($atk1)-1;

for ($j = count($own1)-1; $j >= 0; $j--) {
	if ($i < 0) {$dmg += $own1[$j];} else {
		if ($own1[$j] < $atk1[$i]) {$dmg = 0; break;} else {$dmg += $own1[$j] - $atk1[$i]; $i--;}
	}
}

}

$res = $dmg;

// strategy 2
// beat least atk with most power
$atk2 = $atk;
$own2 = $own;
$dmg = 0;

$i = 0;

for ($j = count($own2)-1; $j >= 0; $j--) {
	if ($i >= count($atk2)) {break;}
	if ($own2[$j] < $atk2[$i]) {break;} else {$dmg += $own2[$j] - $atk2[$i]; $i++;}
}

$res = ($res < $dmg) ? $dmg : $res;

echo $res;


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

<?php
$IN = STDIN;
fscanf($IN, "%d", $n);
$items = explode(" ",trim(fgets($IN)));

$curr = 0;
for ($i=0;$i<(count($items));$i++){
    if ($items[$i]!=$items[$i-1]){
        $normalized[$curr] = $items[$i];
        $curr++;
    } else {
        $cellweight[$curr-1] += 1;
    }
}

if (count($normalized)>1) {
    $locmin[] = 0;
    for ($i=1;$i<(count($normalized)-1);$i++)
        if (($normalized[$i]<$normalized[$i+1])&&($normalized[$i]<$normalized[$i-1]))
            $locmin[] = $i;
    $locmin[] = count($normalized)-1;
} else {
    $locmin = Array(0,0);
}

for ($i=1;$i<count($locmin);$i++){
    $len = 0;
    for ($j=$locmin[$i-1];$j<=$locmin[$i];$j++)
        $len = $len + 1 + (int)$cellweight[$j];
        $lenarr[] = $len;
}

echo (count($lenarr)>1)?max($lenarr):$lenarr[0];

?>


There are $$$n$$$ Christmas trees on an infinite number line. The $$$i$$$-th tree grows at the position $$$x_i$$$. All $$$x_i$$$ are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are $$$m$$$ people who want to celebrate Christmas. Let $$$y_1, y_2, \dots, y_m$$$ be the positions of people (note that all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct and all $$$y_j$$$ should be integer). You want to find such an arrangement of people that the value $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let $$$d_j$$$ be the distance from the $$$j$$$-th human to the nearest Christmas tree ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Then you need to choose such positions $$$y_1, y_2, \dots, y_m$$$ that $$$\sum\limits_{j=1}^{m} d_j$$$ is the minimum possible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of Christmas trees and the number of people. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), where $$$x_i$$$ is the position of the $$$i$$$-th Christmas tree. It is guaranteed that all $$$x_i$$$ are distinct.

In the first line print one integer $$$res$$$ — the minimum possible value of $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (in other words, the sum of distances to the nearest Christmas tree for all people). In the second line print $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), where $$$y_j$$$ is the position of the $$$j$$$-th human. All $$$y_j$$$ should be distinct and all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct. If there are multiple answers, print any of them.

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

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

$trees = explode(' ', trim(fgets(STDIN)));
$places = [];

for ($i = 0; $i < $n; $i++){
	$trees[$i] = intval($trees[$i]);
}

sort($trees);
$min = $trees[0] - 1;
$pos2 = $min;
for ($i = 1; $i < $n; $i++){
	$pos1 = $pos2 + 2;
	$pos2 = $trees[$i]-1;
	if($pos1 <= $pos2){
		$places[] = [$pos1, $pos2];
	}
}
$max = $pos2 + 2;
$peoples = [];
$sum = 0;
$d = 0;

$check = function($pos, $d) use (&$m, &$peoples, &$sum){
	$m--;
	$peoples[] = $pos;
	$sum += $d;
	if($m == 0){
		echo $sum . "\n";
		echo implode(' ', $peoples);
		die;
	}
};

$iterate = function($d) use(&$places, &$min, &$max, &$check){
	$c = count($places);
	$places2 = [];
	$check($min--, $d);
	for ($i = 0; $i < $c; $i++){
		list($p1,$p2) = $places[$i];
		$check($p1++, $d);
		if($p1 <= $p2){
			$check($p2--, $d);
			if($p1 <= $p2){
				$places2[] = [$p1, $p2];
			}
		}
	}
	$check($max++, $d);
	return $places2;
};

while($m > 0){
	$d++;
	$places = $iterate($d);
}

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

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

$trees = explode(' ', trim(fgets(STDIN)));
$occupied = [];
$places = [];

for ($i = 0; $i < $n; $i++){
	$trees[$i] = intval($trees[$i]);
	$occupied[$trees[$i]] = 1;
}

sort($trees);

for ($i = 0; $i < $n; $i++){
	if(!array_key_exists($i-1, $occupied)){
		$places[] = [$trees[$i], -1];
	}
	if(!array_key_exists($i+1, $occupied)){
		$places[] = [$trees[$i], +1];
	}
}

$peoples = [];
$sum = 0;
$d = 0;

$iterate = function($d) use(&$places, &$occupied, &$peoples, &$m, &$sum){
	$c = count($places);
	$places2 = [];
	for ($i = 0; $i < $c; $i++){
		$pos = $places[$i][0] + $places[$i][1] * $d;
		if(!array_key_exists($pos, $occupied)){
			$m--;
			$peoples[] = $pos;
			$occupied[$pos] = 1;
 			$places2[] = $places[$i];
			$sum +=$d;
			if($m == 0){
				return null;
			}
		}
	}
	return $places2;
};

while($m > 0){
	$d++;
	$places = $iterate($d);
}

echo $sum . "\n";
echo implode(' ', $peoples);

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

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

$trees = explode(' ', trim(fgets($stdin)));

$peoples = [];
$sum = 0;
$d = 1;

while($m > 0){
	for($tIndex = 0; $tIndex < $n; $tIndex++ ){
		$pos = $trees[$tIndex] - $d;
		if(array_search($pos, $trees) === false && array_search($pos, $peoples) === false){
			$sum += $d;
			$peoples[] = $pos;
			$m--;
			if($m == 0){
				break;
			}
		}

		$pos = $trees[$tIndex] + $d;
		if(array_search($pos, $trees) === false && array_search($pos, $peoples) === false){
			$sum += $d;
			$peoples[] = $pos;
			$m--;
			if($m == 0){
				break;
			}
		}
	}
	$d++;
}

echo $sum . "\n";
echo implode(' ', $peoples);


The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250.Heidi recently got her hands on a multiverse observation tool. She was able to see all $$$n$$$ universes lined up in a row, with non-existent links between them. She also noticed that the Doctor was in the $$$k$$$-th universe.The tool also points out that due to restrictions originating from the space-time discontinuum, the number of universes will never exceed $$$m$$$.Obviously, the multiverse is unstable because of free will. Each time a decision is made, one of two events will randomly happen: a new parallel universe is created, or a non-existent link is broken.More specifically,    When a universe is created, it will manifest itself between any two adjacent universes or at one of the ends.   When a link is broken, it could be cut between any two adjacent universes. After separating the multiverse into two segments, the segment NOT containing the Doctor will cease to exist. Heidi wants to perform a simulation of $$$t$$$ decisions. Each time a decision is made, Heidi wants to know the length of the multiverse (i.e. the number of universes), and the position of the Doctor.

The first line contains four integers $$$n$$$, $$$k$$$, $$$m$$$ and $$$t$$$ ($$$2 \le k \le n \le m \le 250$$$, $$$1 \le t \le 1000$$$). Each of the following $$$t$$$ lines is in one of the following formats:    "$$$1$$$ $$$i$$$" — meaning that a universe is inserted at the position $$$i$$$ ($$$1 \le i \le l + 1$$$), where $$$l$$$ denotes the current length of the multiverse.  "$$$0$$$ $$$i$$$" — meaning that the $$$i$$$-th link is broken ($$$1 \le i \le l - 1$$$), where $$$l$$$ denotes the current length of the multiverse.

Output $$$t$$$ lines. Each line should contain $$$l$$$, the current length of the multiverse and $$$k$$$, the current position of the Doctor. It is guaranteed that the sequence of the steps will be valid, i.e. the multiverse will have length at most $$$m$$$ and when the link breaking is performed, there will be at least one universe in the multiverse.

NoteThe multiverse initially consisted of 5 universes, with the Doctor being in the second.First, link 1 was broken, leaving the multiverse with 4 universes, and the Doctor in the first.Then, a universe was added to the leftmost end of the multiverse, increasing the multiverse length to 5, and the Doctor was then in the second universe.Then, the rightmost link was broken.Finally, a universe was added between the first and the second universe.


Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \times 1 \times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

The first line contains three positive space-separated integers $$$n, m, h$$$ ($$$1\leq n, m, h \leq 100$$$) — the length, width and height. The second line contains $$$m$$$ non-negative space-separated integers $$$a_1,a_2,\dots,a_m$$$, where $$$a_i$$$ is the height in the $$$i$$$-th column from left to right of the front view ($$$0\leq a_i \leq h$$$). The third line contains $$$n$$$ non-negative space-separated integers $$$b_1,b_2,\dots,b_n$$$ ($$$0\leq b_j \leq h$$$), where $$$b_j$$$ is the height in the $$$j$$$-th column from left to right of the left view. Each of the following $$$n$$$ lines contains $$$m$$$ numbers, each is $$$0$$$ or $$$1$$$, representing the top view, where $$$j$$$-th number of $$$i$$$-th row is $$$1$$$ if $$$h_{i, j}>0$$$, and $$$0$$$ otherwise. It is guaranteed that there is at least one structure satisfying the input.

Output $$$n$$$ lines, each of them contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.

Note  The graph above illustrates the object in the first example.    The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
$e = explode(" ", trim(fgets(STDIN)));
$f = 0;
for($x = 0; $x < $a; $x++)
{
     $g = explode(" ", trim(fgets(STDIN)));
     for($y = 0; $y < $b; $y++)
     {
          if($g[$y] == 1)
          {
               $g[$y] = min($d[$y], $e[$f]);
          }
     }
     $f++;
     print implode(" ", $g) . "\n";
}
?>

<?php

$ser = explode(' ', trim(fgets(STDIN)));

$n = $ser[0];
$m = $ser[1];
$h = $ser[2];

$front = explode(' ', trim(fgets(STDIN)));
$left = explode(' ', trim(fgets(STDIN)));

$top = [];

for($i = 0; $i<$n; $i++){
	$top[] = explode(' ', trim(fgets(STDIN)));
}

for($i = 0; $i<$n; $i++){
	for($j = 0; $j<$m; $j++){
		if($top[$i][$j] == 1){
			$top[$i][$j] = min($front[$j], $left[$i]);
		}
	}
}

for($i = 0; $i<$n; $i++){
	fwrite(STDOUT, implode(' ', $top[$i])."\n");
}


The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen chose.Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?

The first line contains two space-separated integers: n, k (1 ≤ n, k ≤ 1000). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the heights of the trees in the row.

In the first line print a single integer p — the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.  If the gardener needs to increase the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, print on the corresponding line "- j x". If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.


Alice has a birthday today, so she invited home her best friend Bob. Now Bob needs to find a way to commute to the Alice's home.In the city in which Alice and Bob live, the first metro line is being built. This metro line contains $$$n$$$ stations numbered from $$$1$$$ to $$$n$$$. Bob lives near the station with number $$$1$$$, while Alice lives near the station with number $$$s$$$. The metro line has two tracks. Trains on the first track go from the station $$$1$$$ to the station $$$n$$$ and trains on the second track go in reverse direction. Just after the train arrives to the end of its track, it goes to the depot immediately, so it is impossible to travel on it after that.Some stations are not yet open at all and some are only partially open — for each station and for each track it is known whether the station is closed for that track or not. If a station is closed for some track, all trains going in this track's direction pass the station without stopping on it.When the Bob got the information on opened and closed stations, he found that traveling by metro may be unexpectedly complicated. Help Bob determine whether he can travel to the Alice's home by metro or he should search for some other transport.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$2 \le s \le n \le 1000$$$) — the number of stations in the metro and the number of the station where Alice's home is located. Bob lives at station $$$1$$$. Next lines describe information about closed and open stations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$a_i = 0$$$ or $$$a_i = 1$$$). If $$$a_i = 1$$$, then the $$$i$$$-th station is open on the first track (that is, in the direction of increasing station numbers). Otherwise the station is closed on the first track. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$b_i = 0$$$ or $$$b_i = 1$$$). If $$$b_i = 1$$$, then the $$$i$$$-th station is open on the second track (that is, in the direction of decreasing station numbers). Otherwise the station is closed on the second track.

Print "YES" (quotes for clarity) if Bob will be able to commute to the Alice's home by metro and "NO" (quotes for clarity) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first example, all stations are opened, so Bob can simply travel to the station with number $$$3$$$.In the second example, Bob should travel to the station $$$5$$$ first, switch to the second track and travel to the station $$$4$$$ then.In the third example, Bob simply can't enter the train going in the direction of Alice's home.

<?php

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

$n = (int)$n;
$s = (int)$s;

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

if (intval($a[0]) == 0) {
	echo 'NO';
} else {
	if (intval($a[$s-1])==1) {
		echo 'YES';
	} else {
		if (intval($b[$s-1]) == 1) {
			$l = 0;
			for($i=$s; $i<=$n-1; $i++) {
				if (intval($a[$i])==1 && intval($b[$i])==1) {
					$l = $i;
					break;
				}
			}

			if ($l>0) {
				echo 'YES';
			} else {
				echo 'NO';
			}
		} else {
			echo 'NO';
		}
	}
}


Polycarp likes to play with numbers. He takes some integer number $$$x$$$, writes it down on the board, and then performs with it $$$n - 1$$$ operations of the two kinds:   divide the number $$$x$$$ by $$$3$$$ ($$$x$$$ must be divisible by $$$3$$$);  multiply the number $$$x$$$ by $$$2$$$. After each operation, Polycarp writes down the result on the board and replaces $$$x$$$ by the result. So there will be $$$n$$$ numbers on the board after all.You are given a sequence of length $$$n$$$ — the numbers that Polycarp wrote down. This sequence is given in arbitrary order, i.e. the order of the sequence can mismatch the order of the numbers written on the board.Your problem is to rearrange (reorder) elements of this sequence in such a way that it can match possible Polycarp's game in the order of the numbers written on the board. I.e. each next number will be exactly two times of the previous number or exactly one third of previous number.It is guaranteed that the answer exists.

The first line of the input contatins an integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the number of the elements in the sequence. The second line of the input contains $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 3 \cdot 10^{18}$$$) — rearranged (reordered) sequence that Polycarp can wrote down on the board.

Print $$$n$$$ integer numbers — rearranged (reordered) input sequence that can be the sequence that Polycarp could write down on the board. It is guaranteed that the answer exists.

NoteIn the first example the given sequence can be rearranged in the following way: $$$[9, 3, 6, 12, 4, 8]$$$. It can match possible Polycarp's game which started with $$$x = 9$$$.


You are given $$$n$$$ words, each of which consists of lowercase alphabet letters. Each word contains at least one vowel. You are going to choose some of the given words and make as many beautiful lyrics as possible.Each lyric consists of two lines. Each line consists of two words separated by whitespace. A lyric is beautiful if and only if it satisfies all conditions below.   The number of vowels in the first word of the first line is the same as the number of vowels in the first word of the second line.  The number of vowels in the second word of the first line is the same as the number of vowels in the second word of the second line.  The last vowel of the first line is the same as the last vowel of the second line. Note that there may be consonants after the vowel. Also, letters "a", "e", "o", "i", and "u" are vowels. Note that "y" is never vowel.For example of a beautiful lyric,  "hello hellooowww" "whatsup yowowowow"  is a beautiful lyric because there are two vowels each in "hello" and "whatsup", four vowels each in "hellooowww" and "yowowowow" (keep in mind that "y" is not a vowel), and the last vowel of each line is "o".For example of a not beautiful lyric,  "hey man""iam mcdic"  is not a beautiful lyric because "hey" and "iam" don't have same number of vowels and the last vowels of two lines are different ("a" in the first and "i" in the second).How many beautiful lyrics can you write from given words? Note that you cannot use a word more times than it is given to you. For example, if a word is given three times, you can use it at most three times.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the number of words. The $$$i$$$-th of the next $$$n$$$ lines contains string $$$s_{i}$$$ consisting lowercase alphabet letters — the $$$i$$$-th word. It is guaranteed that the sum of the total word length is equal or less than $$$10^{6}$$$. Each word contains at least one vowel.

In the first line, print $$$m$$$ — the number of maximum possible beautiful lyrics. In next $$$2m$$$ lines, print $$$m$$$ beautiful lyrics (two lines per lyric). If there are multiple answers, print any.

14
wow
this
is
the
first
mcdics
codeforces
round
hooray
i
am
proud
about
that

7
arsijo
suggested
the
idea
for
this
problem

3
about proud
hooray round
wow first
this is
i that
mcdics am

NoteIn the first example, those beautiful lyrics are one of the possible answers. Let's look at the first lyric on the sample output of the first example. "about proud hooray round" forms a beautiful lyric because "about" and "hooray" have same number of vowels, "proud" and "round" have same number of vowels, and both lines have same last vowel. On the other hand, you cannot form any beautiful lyric with the word "codeforces".In the second example, you cannot form any beautiful lyric from given words.In the third example, you can use the word "same" up to three times.


Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that.

The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces.

If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them.

<?php

$f = fopen('input.txt', 'r');
fscanf($f, '%d', $n);
$row = rtrim(fgets($f));
$cards = explode(' ', $row);

$hash = array();
$ans = '';
for ($i = 0; $i < 2 * $n; $i++) {
    $card = $cards[$i];
    if (isset($hash[$card])) {
        $ans .= sprintf('%d %d', $hash[$card] + 1, $i + 1) . PHP_EOL;
        unset($hash[$card]);
    } else {
        $hash[$card] = $i;
    }
}

if (count($hash)) {
    file_put_contents('output.txt', "-1" . PHP_EOL);
    exit;
}

file_put_contents('output.txt', $ans);

<?php

$f = fopen('input.txt', 'r');
fscanf($f, '%d', $n);
$row = rtrim(fgets($f));
$cards = explode(' ', $row);

$hash = array();
$ans = '';
for ($i = 0; $i < 2 * $n; $i++) {
    $card = $cards[$i];
    if (isset($hash[$card])) {
        $ans .= sprintf('%d %d', $hash[$card] + 1, $i + 1) . PHP_EOL;
        unset($hash[$card]);
    } else {
        $hash[$card] = $i;
    }
}

if (isset($hash)) {
    file_put_contents('output.txt', "-1" . PHP_EOL);
    exit;
}

file_put_contents('output.txt', $ans);

<?php

$f = fopen('input.txt', 'r');
fscanf($f, '%d', $n);
$row = rtrim(fgets($f));
$cards = explode(' ', $row);

$hash = array();
$ans = '';
for ($i = 0; $i < 2 * $n; $i++) {
    $card = $cards[$i];
    if (isset($hash[$card])) {
        $ans .= sprintf('%d %d', $hash[$card] + 1, $i + 1) . PHP_EOL;
        unset($hash[$card]);
    } else {
        $hash[$card] = $i;
    }
}

file_put_contents('output.txt', $ans);


You are given n points with integer coordinates on the plane. Points are given in a way such that there is no triangle, formed by any three of these n points, which area exceeds S.Alyona tried to construct a triangle with integer coordinates, which contains all n points and which area doesn't exceed 4S, but, by obvious reason, had no success in that. Please help Alyona construct such triangle. Please note that vertices of resulting triangle are not necessarily chosen from n given points.

In the first line of the input two integers n and S (3 ≤ n ≤ 5000, 1 ≤ S ≤ 1018) are given — the number of points given and the upper bound value of any triangle's area, formed by any three of given n points. The next n lines describes given points: ith of them consists of two integers xi and yi ( - 108 ≤ xi, yi ≤ 108) — coordinates of ith point. It is guaranteed that there is at least one triple of points not lying on the same line.

Print the coordinates of three points — vertices of a triangle which contains all n points and which area doesn't exceed 4S. Coordinates of every triangle's vertex should be printed on a separate line, every coordinate pair should be separated by a single space. Coordinates should be an integers not exceeding 109 by absolute value. It is guaranteed that there is at least one desired triangle. If there is more than one answer, print any of them.


Monocarp had a tree which consisted of $$$n$$$ vertices and was rooted at vertex $$$1$$$. He decided to study BFS (Breadth-first search), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:a = [] # the order in which vertices were processedq = Queue()q.put(1) # place the root at the end of the queuewhile not q.empty():    k = q.pop() # retrieve the first vertex from the queue    a.append(k) # append k to the end of the sequence in which vertices were visited    for y in g[k]: # g[k] is the list of all children of vertex k, sorted in ascending order        q.put(y)Monocarp was fascinated by BFS so much that, in the end, he lost his tree. Fortunately, he still has a sequence of vertices, in which order vertices were visited by the BFS algorithm (the array a from the pseudocode). Monocarp knows that each vertex was visited exactly once (since they were put and taken from the queue exactly once). Also, he knows that all children of each vertex were viewed in ascending order.Monocarp knows that there are many trees (in the general case) with the same visiting order $$$a$$$, so he doesn't hope to restore his tree. Monocarp is okay with any tree that has minimum height.The height of a tree is the maximum depth of the tree's vertices, and the depth of a vertex is the number of edges in the path from the root to it. For example, the depth of vertex $$$1$$$ is $$$0$$$, since it's the root, and the depth of all root's children are $$$1$$$.Help Monocarp to find any tree with given visiting order $$$a$$$ and minimum height.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$; $$$a_i \neq a_j$$$; $$$a_1 = 1$$$) — the order in which the vertices were visited by the BFS algorithm. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case print the minimum possible height of a tree with the given visiting order $$$a$$$.

NoteIn the first test case, there is only one tree with the given visiting order:   In the second test case, there is only one tree with the given visiting order as well:   In the third test case, an optimal tree with the given visiting order is shown below:

<?php

ob_start(null, 65536);

$__ln = explode("\n", file_get_contents("php://stdin"));
$__lc = 0;

function nl() {
    global $__ln, $__lc;
    return $__ln[$__lc++];
}

function nla() {
    global $__ln, $__lc;
    return explode(" ", $__ln[$__lc++]);
}

function asInt($x) {
    return (int)$x;
}

function asDouble($x) {
    return (double)$x;
}

$tc = asInt(nl());
for($cc=0; $cc<$tc; $cc++) {
    $n = asInt(nl());
    $buf = array_map(asInt::class, nla());
    $a = new SplFixedArray($n+2);
    $x = 0;
    foreach($buf as $v) {
        $a[$x++] = $v;
    }
    $q = new SplFixedArray($n+2);
    $s = 0; $e = 0;
    $q[$e++] = [1, 0];
    for($i=1; $i<$n; $i++) {
        if($a[$i-1] < $a[$i]) {
            $q[$e++] = [$a[$i], $q[$s][1]+1];
        } else {
            $s++;
            $q[$e++] = [$a[$i], $q[$s][1]+1];
        }
    }
    echo $q[$n-1][1] . "\n";
}

<?php

ob_start(null, 65536);

$__ln = explode("\n", file_get_contents("php://stdin"));
$__lc = 0;

function nl() {
    global $__ln, $__lc;
    return $__ln[$__lc++];
}

function nla() {
    global $__ln, $__lc;
    return explode(" ", $__ln[$__lc++]);
}

function asInt($x) {
    return (int)$x;
}

function asDouble($x) {
    return (double)$x;
}

$tc = asInt(nl());
for($cc=0; $cc<$tc; $cc++) {
    $n = asInt(nl());
    $buf = array_map(asInt::class, nla());
    $a = new SplFixedArray($n+2);
    $x = 0;
    foreach($buf as $v) {
        $a[$x++] = $v;
    }
    $q = new SplFixedArray($n+2);
    $s = 0; $e = 0;
    $q[$e++] = 0;
    for($i=1; $i<$n; $i++) {
        if($a[$i-1] < $a[$i]) {
            $q[$e++] = $q[$s]+1;
        } else {
            $s++;
            $q[$e++] = $q[$s]+1;
        }
    }
    echo $q[$n-1] . "\n";
}


The Bitlandians are quite weird people. They do everything differently. They have a different alphabet so they have a different definition for a string.A Bitlandish string is a string made only of characters "0" and "1".BitHaval (the mayor of Bitland) loves to play with Bitlandish strings. He takes some Bitlandish string a, and applies several (possibly zero) operations to it. In one operation the mayor may take any two adjacent characters of a string, define one of them as x and the other one as y. Then he calculates two values p and q: p = x xor y, q = x or y. Then he replaces one of the two taken characters by p and the other one by q.The xor operation means the bitwise excluding OR operation. The or operation is the bitwise OR operation.So for example one operation can transform string 11 to string 10 or to string 01. String 1 cannot be transformed into any other string.You've got two Bitlandish strings a and b. Your task is to check if it is possible for BitHaval to transform string a to string b in several (possibly zero) described operations.

The first line contains Bitlandish string a, the second line contains Bitlandish string b. The strings can have different lengths. It is guaranteed that the given strings only consist of characters "0" and "1". The strings are not empty, their length doesn't exceed 106.

Print "YES" if a can be transformed into b, otherwise print "NO". Please do not print the quotes.

<?php
    $s1 = trim(fgets(STDIN));
    $s2 = trim(fgets(STDIN));

    $ret = "NO";
    if (strlen($s1) != strlen($s2))
    {

    }
    else
    {
        $k1 = strpos($s1, "1");
        $k2 = strpos($s2, "1");
        if (($k1 === false && $k2 !== false)||
            ($k1 !== false && $k2 === false)
            )
        {

        }
        else
        {
            $ret = "YES";
        }

    }

    echo $ret;
?>

<?php
	$str1 = trim(fgets(STDIN), "\r\n");
	$str2 = trim(fgets(STDIN), "\r\n");
	$str = $str1 . $str2;
	$ans1 = false;
	$ans2 = false;
	if(strlen($str1) == 1 && strlen($str2) == 1)
		echo $str1 == $str2 ? "YES" : "NO";
	elseif(strlen($str1) != strlen($str2))
		echo "NO";
	else
	{
		for($i = 0; $i < strlen($str1); ++$i)
		{
			$ans1 |= $str1[$i];
			$ans2 |= $str2[$i];
		}
		echo !($ans1 ^ $ans2) ? "YES" : "NO";
	}


Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?

The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.

Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.

<?php
list($n, $k, $m) = explode(" ", trim(fgets(STDIN)));
$v = explode(" ", trim(fgets(STDIN)));
sort($v);
$total=$ans=0;
for($i=0;$i<$n;$i++)
$total+=$v[$i];
//print $total."\n";
for($i=0;$i<=min($m,$n-1);$i++)
    {
        $baki=$n-$i;
        $temp=$total+min($m-$i,$baki*$k);
        $ans=max($ans,$temp/$baki);
        $total-=$v[$i];
       // print $total."\n";
    }
print number_format($ans, 15, ".", "") . "\n";
?>

<?php
list($n, $k, $m) = explode(" ", trim(fgets(STDIN)));
$v = explode(" ", trim(fgets(STDIN)));
sort($v);
$total=$ans=0;
for($i=0;$i<$n;$i++)
$total+=$v[$i];
//print $total."\n";
for($i=0;$i<=min($m,$n-1);$i++)
    {
        $baki=$n-$i;
        $temp=$total+min($m-$i,$baki*$k);
        $ans=max($ans,$temp/$baki);
        $total-=$v[$i];
       // print $total."\n";
    }
print number_format($ans, 6, ".", "") . "\n";
?>

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
rsort($d);
$e = 0;
for($x = 0; $x < $a; $x++)
{
     $f = $d[$x] + $b;
     if($f < $e)
     {
          break;
     }
     else
     {
          $e = $f;
     }
}
print number_format($e, 6, ".", "");
?>

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
rsort($d);
if($c < $a)
{
    $e = array_slice($d, 0, $a - $c);
    $g = array_sum($e) / count($e);
    $d[0]++;
    $h = array_sum($d) / $a;
    $f = max($g, $h);
}
elseif($c == $a)
{
     $f = $d[0] + 1;
}
elseif($c > $a)
{
     $c -= $a;
     $c++;
     $f = $d[0] + min($b, $c);
}
print number_format($f, 6, ".", "") . "\n";
?>

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
rsort($d);
if($c < $a)
{
    $e = array_slice($d, 0, $a - $c);
    $f = array_sum($e) / count($e);
}
elseif($c == $a)
{
     $f = $d[0] + 1;
}
elseif($c > $a)
{
     $c -= $a;
     $c++;
     $f = $d[0] + min($b, $c);
}
print number_format($f, 6, ".", "") . "\n";
?>

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
rsort($d);
if($c <= $a)
{
    $e = array_slice($d, 0, $a - $c);
    $f = array_sum($e) / count($e);
}
else
{
     $c -= $a;
     $f = $d[0] + min($b, $c);
}
print number_format($f, 6, ".", "") . "\n";
?>

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = explode(" ", trim(fgets(STDIN)));
rsort($d);
if($c < $a)
{
    $e = array_slice($d, 0, $a - $c);
    $f = array_sum($e) / count($e);
}
elseif($c == $a)
{
     $f = $d[0] + 1;
}
elseif($c > $a)
{
     $c -= $a;
     $f = $d[0] + min($b, $c);
}
print number_format($f, 6, ".", "") . "\n";
?>

<?php
	fscanf(STDIN, "%d %d %d", $n,$k,$m);
	$a = fscanf(STDIN, str_pad("",2*$n,"%d"));
	//print_r($a);
	rsort($a, SORT_NUMERIC);
	$m = $a[0]+min($k,$m);
	echo $m;
?>

<?php
	fscanf(STDIN, "%d %d %d", $n,$k,$m);
	$a = fscanf(STDIN, str_pad("",2*$n,"%d"));
	//print_r($a);
	rsort($a, SORT_NUMERIC);
	$m = $a[0]+$k;
	echo $m;
?>

<?php
list($n, $k, $m) = explode(" ", trim(fgets(STDIN)));
$v = explode(" ", trim(fgets(STDIN)));
sort($v);
$total=$ans=0;
for($i=0;$i<$n;$i++)
$total+=$v[$i];
//print $total."\n";
for($i=0;$i<=min($m,$n-1);$i++)
    {
        $baki=$n-$i;
        $temp=$total+min($m-$i,$baki*$k);
        $ans=max($ans,$temp/$baki);
        $total-=$v[$i];
       // print $total."\n";
    }
print number_format($ans, 5, ".", "") . "\n";
?>


Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase.Patrick believes that a message is fancy if any uppercase letter stands to the left of any lowercase one. In other words, this rule describes the strings where first go zero or more uppercase letters, and then — zero or more lowercase letters.To make the message fancy, Patrick can erase some letter and add the same letter in the same place in the opposite case (that is, he can replace an uppercase letter with the lowercase one and vice versa). Patrick got interested in the following question: what minimum number of actions do we need to make a message fancy? Changing a letter's case in the message counts as one action. Patrick cannot perform any other actions.

The only line of the input contains a non-empty string consisting of uppercase and lowercase letters. The string's length does not exceed 105.

Print a single number — the least number of actions needed to make the message fancy.

<?php

error_reporting(0);

solve();

function solve(){
	//$Input = new Input("input.txt");
	$Input = new Input();

	$S = $Input->in();
	$S_array = str_split($S);
	$len = count($S_array);

	$u_cnt = array_fill(-1, $len, 0);
	$min = 100000 + 1;
	for ($i = -1; $i < $len - 1; $i++) {
		if ($S_array[$i + 1] >= "A" && $S_array[$i + 1] <= "Z") {
			$u_cnt[$i + 1] = $u_cnt[$i] + 1;
		} else {
			$u_cnt[$i + 1] = $u_cnt[$i];
		}
	}
	for ($i = -1; $i < $len; $i++) {
		$min = min($min, $u_cnt[$len - 1] - $u_cnt[$i] + $i + 1 - $u_cnt[$i]);
	}

	print($min);
}

class Input{
	private $handle = "";
	private $values = array();
	private $index = 0;

	public function __construct($localfile){

		if (is_file($localfile)) {

			$this->handle = fopen($localfile, "r");
			$contents = stream_get_contents($this->handle);

		} else {

			$contents = stream_get_contents(STDIN);

		}

		$no_newlines = str_replace(array("\r\n", "\r", "\n"), " ", $contents);
		$this->values = explode(" ", $no_newlines);
	}

	public function in(){

		return $this->values[$this->index++];

	}

	public function close(){

		if (is_file($localfile) && feof($this->handle)) fclose($this->handle);

	}
}

?>

<?php

error_reporting(0);

solve();

function solve(){
	//$Input = new Input("input.txt");
	$Input = new Input();

	$S = $Input->in();
	$S_array = str_split($S);
	$len = count($S_array);

	$alp = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
	$l_pos = "";
	$u_pos = "";
	$l_count = array_fill(0,count($len), 0);
	$u_count = array_fill(0,count($len), 0);
	$min = 100000 + 1;
	$l_pre = 0;
	$u_pre = 0;
	for ($i = 0; $i < $len; $i++) {
		for ($j = 0; $j < count($alp); $j++) {
			$l_count[$i] = $l_pre;
			$u_count[$len - 1 - $i] = $u_pre;

			if ($S_array[$i] === $alp[$j]) {
				$l_count[$i] += 1;
			}
			if ($S_array[$len - 1 - $i] === strtoupper($alp[$j])) {
				$u_count[$len - 1 - $i] += 1;
			}

			$l_pre = $l_count[$i];
			$u_pre = $u_count[$len - 1 - $i];
		}
	}
	for ($i = 0; $i < $len; $i++) {

		$min = min($min, $l_count[$i] + $u_count[$i + 1]);
	}

	print($min);
}

class Input{
	private $handle = "";
	private $values = array();
	private $index = 0;

	public function __construct($localfile){

		if (is_file($localfile)) {

			$this->handle = fopen($localfile, "r");
			$contents = stream_get_contents($this->handle);

		} else {

			$contents = stream_get_contents(STDIN);

		}

		$no_newlines = str_replace(array("\r\n", "\r", "\n"), " ", $contents);
		$this->values = explode(" ", $no_newlines);
	}

	public function in(){

		return $this->values[$this->index++];

	}

	public function close(){

		if (is_file($localfile) && feof($this->handle)) fclose($this->handle);

	}
}

?>

<?php

error_reporting(0);

solve();

function solve(){
	//$Input = new Input("input.txt");
	$Input = new Input();

	$S = $Input->in();
	$S_array = str_split($S);
	$len = count($S_array);

	$alp = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
	$l_pos = "";
	$u_pos = "";
	$l_count = 0;
	$u_count = 0;

	for ($i = 0; $i < $len; $i++) {
		for ($j = 0; $j < count($alp); $j++) {
		if ($S_array[$i] === $alp[$j] && $l_pos === "") {
			$l_pos = $i;
			break;
		}
		if ($l_pos !== "" && $S_array[$i] === strtoupper($alp[$j])) {
				$u_count++;
				break;
			}
		}
	}

	for ($i = $len - 1; $i >= 0; $i--) {
		for ($j = 0; $j < count($alp); $j++) {
			if ($S_array[$i] === strtoupper($alp[$j]) && $u_pos === "") {
				$u_pos = $i;
				break;
			}
			if ($u_pos !== "" && $S_array[$i] === $alp[$j]) {
					$l_count++;
					break;
				}
			}
	}

	print(min($u_count, $l_count));
}

class Input{
	private $handle = "";
	private $values = array();
	private $index = 0;

	public function __construct($localfile){

		if (is_file($localfile)) {

			$this->handle = fopen($localfile, "r");
			$contents = stream_get_contents($this->handle);

		} else {

			$contents = stream_get_contents(STDIN);

		}

		$no_newlines = str_replace(array("\r\n", "\r", "\n"), " ", $contents);
		$this->values = explode(" ", $no_newlines);
	}

	public function in(){

		return $this->values[$this->index++];

	}

	public function close(){

		if (is_file($localfile) && feof($this->handle)) fclose($this->handle);

	}
}

?>


Kuznecov likes art, poetry, and music. And strings consisting of lowercase English letters.Recently, Kuznecov has found two strings, $$$a$$$ and $$$b$$$, of lengths $$$n$$$ and $$$m$$$ respectively. They consist of lowercase English letters and no character is contained in both strings. Let another string $$$c$$$ be initially empty. Kuznecov can do the following two types of operations:  Choose any character from the string $$$a$$$, remove it from $$$a$$$, and add it to the end of $$$c$$$.  Choose any character from the string $$$b$$$, remove it from $$$b$$$, and add it to the end of $$$c$$$. But, he can not do more than $$$k$$$ operations of the same type in a row. He must perform operations until either $$$a$$$ or $$$b$$$ becomes empty. What is the lexicographically smallest possible value of $$$c$$$ after he finishes?A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds: $$$x$$$ is a prefix of $$$y$$$, but $$$x \neq y$$$;  in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1\leq n,m,k \leq 100$$$) — parameters from the statement. The second line of each test case contains the string $$$a$$$ of length $$$n$$$. The third line of each test case contains the string $$$b$$$ of length $$$m$$$.  The strings contain only lowercase English letters. It is guaranteed that no symbol appears in $$$a$$$ and $$$b$$$ simultaneously.

In each test case, output a single string $$$c$$$ — the answer to the problem.

3

6 4 2

aaaaaa

bbbb

5 9 3

caaca

bedededeb

7 7 1

noskill

wxhtzdy

NoteIn the first test case, it is optimal to take two 'a's from the string $$$a$$$ and add them to the string $$$c$$$. Then it is forbidden to take more characters from $$$a$$$, hence one character 'b' from the string $$$b$$$ has to be taken. Following that logic, we end up with $$$c$$$ being 'aabaabaa' when string $$$a$$$ is emptied.In the second test case it is optimal to take as many 'a's from string $$$a$$$ as possible, then take as many 'b's as possible from string $$$b$$$. In the end, we take two 'c's from the string $$$a$$$ emptying it.


In a certain video game, the player controls a hero characterized by a single integer value: power. The hero will have to beat monsters that are also characterized by a single integer value: armor.On the current level, the hero is facing $$$n$$$ caves. To pass the level, the hero must enter all the caves in some order, each cave exactly once, and exit every cave safe and sound. When the hero enters cave $$$i$$$, he will have to fight $$$k_i$$$ monsters in a row: first a monster with armor $$$a_{i, 1}$$$, then a monster with armor $$$a_{i, 2}$$$ and so on, finally, a monster with armor $$$a_{i, k_i}$$$.The hero can beat a monster if and only if the hero's power is strictly greater than the monster's armor. If the hero can't beat the monster he's fighting, the game ends and the player loses. Note that once the hero enters a cave, he can't exit it before he fights all the monsters in it, strictly in the given order.Each time the hero beats a monster, the hero's power increases by $$$1$$$.Find the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of caves. The $$$i$$$-th of the next $$$n$$$ lines contains an integer $$$k_i$$$ ($$$1 \le k_i \le 10^5$$$) — the number of monsters in the $$$i$$$-th cave, followed by $$$k_i$$$ integers $$$a_{i, 1}, a_{i, 2}, \ldots, a_{i, k_i}$$$ ($$$1 \le a_{i, j} \le 10^9$$$) — armor levels of the monsters in cave $$$i$$$ in order the hero has to fight them. It is guaranteed that the sum of $$$k_i$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest possible power the hero must start the level with to be able to enter all the caves in some order and beat all the monsters.

NoteIn the first test case, the hero has to beat a single monster with armor $$$42$$$, it's enough to have power $$$43$$$ to achieve that.In the second test case, the hero can pass the level with initial power $$$13$$$ as follows:   enter cave $$$2$$$:   beat a monster with armor $$$12$$$, power increases to $$$14$$$;  beat a monster with armor $$$11$$$, power increases to $$$15$$$;   enter cave $$$1$$$:   beat a monster with armor $$$10$$$, power increases to $$$16$$$;  beat a monster with armor $$$15$$$, power increases to $$$17$$$;  beat a monster with armor $$$8$$$, power increases to $$$18$$$.

<?php
class IO {
    public static $aAlphabet = ['A','B','C','D', 'E', 'F', 'G', 'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    //Input/Output
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function asLine($mArr, $sep = ' ') { echo implode($sep, $mArr) . PHP_EOL; }

    //Z-function
    public static function z($sString) {
        $s = str_split($sString);
        $n = count($s);
        $z = array_fill(0, $n, 0);
        $r = $l = 0;
        for ($i = 1; $i < $n; $i++) {
            if ($r >= $i) {
                $z[$i] = min($z[$i - $l], $r - $i + 1);
            }
            while ($z[$i] + $i < $n && $s[$z[$i]] == $s[$z[$i] + $i]) {
                $z[$i]++;
            }
            if ($i + $z[$i] - 1 > $r) {
                $l = $i;
                $r = $i + $z[$i] - 1;
            }
        }
        return $z;
    }
    public static function getCountOfDiffSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $n = count($s);
        $count = 0;
        $t = '';
        for ($i = $n - 1; $i >= 0; $i--) {
            $t = $s[$i] . $t;
            $count += $i + 1 - max(self::z($t));
        }
        return $count;
    }
    public static function getMinPeriodOfSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $res = count($s);
        $z = self::z($sString);
        foreach ($z as $iI => $sV) {
            if ((int) $iI + $z[$iI] == $res && $res % (int) $iI == 0) {
                $res = $iI;
                break;
            }
        }
        return $res;
    }

    //Other functions
    public static function gcd($a, $b) {
        return ($a % $b) ? self::gcd($b,$a % $b) : $b;
    }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }

}

//$iQueryCount = 1;
$iQueryCount = IO::str();
$aAllResults = [];
while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $n = IO::str();
    $a = [];
    $b = [];
    $c = [];
    for ($i12 = 0; $i12 < $n; $i12++) {
        $x = IO::arr();
        $k = $x[0];
        $min = $x[1] + 1;
        for ($i = 1; $i <= $k; $i++) {
            if ($x[$i] >= $min + $i - 1) {
                $min = $x[$i] - $i + 2;
            }
        }
        $a[] = $x;
        $b[] = $min;
        if (isset($c[$min])) {
            $c[$min] += $k;
        } else {
            $c[$min] = $k;
        }
    }
    $res = [];
    ksort($c);
//    foreach ($c as $kk => $aV) {
//        IO::line($kk . ' - ' . implode(' ', $aV));
//    }
    $res = 0;
    $d = 0;
    foreach ($c as $minK => $aV) {
        if ($d < $minK) {
            $res += $minK - $d;
            $d += $minK - $d;
        }
        $d += $aV;
    }
    IO::line($res);

}

?>

<?php
class IO {
    public static $aAlphabet = ['A','B','C','D', 'E', 'F', 'G', 'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    //Input/Output
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function asLine($mArr, $sep = ' ') { echo implode($sep, $mArr) . PHP_EOL; }

    //Z-function
    public static function z($sString) {
        $s = str_split($sString);
        $n = count($s);
        $z = array_fill(0, $n, 0);
        $r = $l = 0;
        for ($i = 1; $i < $n; $i++) {
            if ($r >= $i) {
                $z[$i] = min($z[$i - $l], $r - $i + 1);
            }
            while ($z[$i] + $i < $n && $s[$z[$i]] == $s[$z[$i] + $i]) {
                $z[$i]++;
            }
            if ($i + $z[$i] - 1 > $r) {
                $l = $i;
                $r = $i + $z[$i] - 1;
            }
        }
        return $z;
    }
    public static function getCountOfDiffSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $n = count($s);
        $count = 0;
        $t = '';
        for ($i = $n - 1; $i >= 0; $i--) {
            $t = $s[$i] . $t;
            $count += $i + 1 - max(self::z($t));
        }
        return $count;
    }
    public static function getMinPeriodOfSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $res = count($s);
        $z = self::z($sString);
        foreach ($z as $iI => $sV) {
            if ((int) $iI + $z[$iI] == $res && $res % (int) $iI == 0) {
                $res = $iI;
                break;
            }
        }
        return $res;
    }

    //Other functions
    public static function gcd($a, $b) {
        return ($a % $b) ? self::gcd($b,$a % $b) : $b;
    }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }

}

//$iQueryCount = 1;
$iQueryCount = IO::str();
$aAllResults = [];
while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $n = IO::str();
    $a = [];
    $b = [];
    $c = [];
    for ($i12 = 0; $i12 < $n; $i12++) {
        $x = IO::arr();
        $k = $x[0];
        $min = $x[1] + 1;
        for ($i = 1; $i <= $k; $i++) {
            if ($x[$i] >= $min + $i - 1) {
                $min = $x[$i] - $i + 2;
            }
        }
        $a[] = $x;
        $b[] = $min;
        if (isset($c[$min])) {
            $c[$min] += $k;
        } else {
            $c[$min] = $k;
        }
    }
    $res = [];
    ksort($c);
//    foreach ($c as $kk => $aV) {
//        IO::line($kk . ' - ' . implode(' ', $aV));
//    }
    $res = 0;
    foreach ($c as $minK => $aV) {
        if ($res < $minK) {
            $res+= $minK - $res;
        }
    }
    IO::line($res);

}

?>

<?php
class IO {
    public static $aAlphabet = ['A','B','C','D', 'E', 'F', 'G', 'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    //Input/Output
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function asLine($mArr, $sep = ' ') { echo implode($sep, $mArr) . PHP_EOL; }

    //Z-function
    public static function z($sString) {
        $s = str_split($sString);
        $n = count($s);
        $z = array_fill(0, $n, 0);
        $r = $l = 0;
        for ($i = 1; $i < $n; $i++) {
            if ($r >= $i) {
                $z[$i] = min($z[$i - $l], $r - $i + 1);
            }
            while ($z[$i] + $i < $n && $s[$z[$i]] == $s[$z[$i] + $i]) {
                $z[$i]++;
            }
            if ($i + $z[$i] - 1 > $r) {
                $l = $i;
                $r = $i + $z[$i] - 1;
            }
        }
        return $z;
    }
    public static function getCountOfDiffSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $n = count($s);
        $count = 0;
        $t = '';
        for ($i = $n - 1; $i >= 0; $i--) {
            $t = $s[$i] . $t;
            $count += $i + 1 - max(self::z($t));
        }
        return $count;
    }
    public static function getMinPeriodOfSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $res = count($s);
        $z = self::z($sString);
        foreach ($z as $iI => $sV) {
            if ((int) $iI + $z[$iI] == $res && $res % (int) $iI == 0) {
                $res = $iI;
                break;
            }
        }
        return $res;
    }

    //Other functions
    public static function gcd($a, $b) {
        return ($a % $b) ? self::gcd($b,$a % $b) : $b;
    }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }

}

//$iQueryCount = 1;
$iQueryCount = IO::str();
$aAllResults = [];
while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $n = IO::str();
    $a = [];
    $b = [];
    $c = [];
    for ($i12 = 0; $i12 < $n; $i12++) {
        $x = IO::arr();
        $k = $x[0];
        $min = $x[1] + 1;
        for ($i = 1; $i <= $k; $i++) {
            if ($x[$i] >= $min + $i - 1) {
                $min += $x[$i] - $min;
            }
        }
        $a[] = $x;
        $b[] = $min;
        if (isset($c[$min])) {
            $c[$min][] = $k;
        } else {
            $c[$min] = [$k];
        }
    }
    $res = [];
    ksort($c);
//    foreach ($c as $kk => $aV) {
//        IO::line($kk . ' - ' . implode(' ', $aV));
//    }
    foreach ($c as $minK => $aV) {
        $d = $minK;
        $f = $minK;
        foreach ($c as $minK2 => $aV2) {
            if ($d <= $minK2) {
                $f += $minK2 - $d;
                $d += $minK2 - $d;
            }
            foreach ($aV2 as $sVal) {
                $d += $sVal;
            }
        }
        $res[] = $f;
    }
    IO::line(min($res));

}

?>

<?php
class IO {
    public static $aAlphabet = ['A','B','C','D', 'E', 'F', 'G', 'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    //Input/Output
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function asLine($mArr, $sep = ' ') { echo implode($sep, $mArr) . PHP_EOL; }

    //Z-function
    public static function z($sString) {
        $s = str_split($sString);
        $n = count($s);
        $z = array_fill(0, $n, 0);
        $r = $l = 0;
        for ($i = 1; $i < $n; $i++) {
            if ($r >= $i) {
                $z[$i] = min($z[$i - $l], $r - $i + 1);
            }
            while ($z[$i] + $i < $n && $s[$z[$i]] == $s[$z[$i] + $i]) {
                $z[$i]++;
            }
            if ($i + $z[$i] - 1 > $r) {
                $l = $i;
                $r = $i + $z[$i] - 1;
            }
        }
        return $z;
    }
    public static function getCountOfDiffSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $n = count($s);
        $count = 0;
        $t = '';
        for ($i = $n - 1; $i >= 0; $i--) {
            $t = $s[$i] . $t;
            $count += $i + 1 - max(self::z($t));
        }
        return $count;
    }
    public static function getMinPeriodOfSubstrWithZ($sString)
    {
        $s = str_split($sString);
        $res = count($s);
        $z = self::z($sString);
        foreach ($z as $iI => $sV) {
            if ((int) $iI + $z[$iI] == $res && $res % (int) $iI == 0) {
                $res = $iI;
                break;
            }
        }
        return $res;
    }

    //Other functions
    public static function gcd($a, $b) {
        return ($a % $b) ? self::gcd($b,$a % $b) : $b;
    }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }

}

//$iQueryCount = 1;
$iQueryCount = IO::str();
$aAllResults = [];
while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $n = IO::str();
    $a = [];
    $b = [];
    $c = [];
    for ($i12 = 0; $i12 < $n; $i12++) {
        $x = IO::arr();
        $k = $x[0];
        $min = $x[1] + 1;
        for ($i = 1; $i < $k; $i++) {
            if ($x[$i] >= $min + $i - 1) {
                $min += $x[$i] - $min;
            }
        }
        $a[] = $x;
        $b[] = $min;
        if (isset($c[$min])) {
            $c[$min][] = $k;
        } else {
            $c[$min] = [$k];
        }
    }
    $res = [];
    ksort($c);
//    foreach ($c as $kk => $aV) {
//        IO::line($kk . ' - ' . implode(' ', $aV));
//    }
    foreach ($c as $minK => $aV) {
        $d = $minK;
        $f = $minK;
        foreach ($c as $minK2 => $aV2) {
            if ($d <= $minK2) {
                $f += $minK2 - $d;
                $d += $minK2 - $d;
            }
            foreach ($aV2 as $sVal) {
                $d += $sVal;
            }
        }
        $res[] = $f;
    }
    IO::line(min($res));

}

?>


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0.You may choose at most one consecutive subarray of $$$a$$$ and multiply all values contained in this subarray by $$$x$$$. You want to maximize the beauty of array after applying at most one such operation.

The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 3 \cdot 10^5, -100 \le x \le 100$$$) — the length of array $$$a$$$ and the integer $$$x$$$ respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the array $$$a$$$.

Print one integer — the maximum possible beauty of array $$$a$$$ after multiplying all values belonging to some consecutive subarray $$$x$$$.

NoteIn the first test case we need to multiply the subarray [-2, 1, -6], and the array becomes [-3, 8, 4, -2, 12] with beauty 22 ([-3, 8, 4, -2, 12]).In the second test case we don't need to multiply any subarray at all.In the third test case no matter which subarray we multiply, the beauty of array will be equal to 0.

<?php
# 1155D
[$itemsCount, $x] = fscanf(STDIN, '%d %d');

$max = $max1 = $max2 = $max3 = 0;
$item = '';
do {
    $char = trim(fgetc(STDIN));
    $item .= $char;
    if ($char === '') {
        $item = (float) $item;
        $max1 = max($max1 + $item, 0);
        $max2 = max($max2 + $item * $x, $max1);
        $max3 = max($max3 + $item, $max2);
        $max = max($max3, $max);
        $item = '';
    }
} while (feof(STDIN) !== true);
printf('%.0f', $max);

<?php
# 1155D
[$itemsCount, $x] = fscanf(STDIN, '%d %d');

$items = explode(' ', fgets(STDIN));
$max = $max1 = $max2 = $max3 = 0;
foreach ($items as $item) {
    $item = (float) $item;
    $max1 = max($max1 + $item, 0);
    $max2 = max($max2 + $item * $x, $max1);
    $max3 = max($max3 + $item, $max2);
    $max = max($max3, $max);
}
printf('%.0f', $max);

<?php
echo PHP_INT_MAX . PHP_EOL;
echo PHP_FLOAT_MAX . PHP_EOL;

<?php
# 1155D
[$itemsCount, $x] = fscanf(STDIN, '%d %d');
$items = explode(' ', fgets(STDIN));
$max = $max1 = $max2 = $max3 = 0;
foreach ($items as $item) {
    $item = (int) $item;
    $max1 = max($max1 + $item, 0);
    $max2 = max($max2 + $item * $x, $max1);
    $max3 = max($max3 + $item, $max2);
    $max = max($max3, $max);
}
echo printf('%.0f', $max);

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

[$itemsCount, $x] = explode(' ', fgets($input));
$items = explode(' ', fgets($input));

$max = array_sum($items);
for($length = 1; $length <= $itemsCount; $length++) {
    for ($i = 0; $length + $i <= $itemsCount; $i++) {
        $limit = $length + $i;
        $arr = $items;
        for($j = $i; $j < $limit; $j++) {
            $arr[$j] = (int)$items[$j] * (int)$x;
        }

        $max = max($max, array_sum($arr));
    }
}
echo $max;

<?php
echo PHP_INT_MAX;
die();
//9223372036854775807
//13346856128091
//13526989544447800
$input = fopen('php://stdin', 'rb');

[$itemsCount, $x] = explode(' ', fgets($input));
$itemsCount = (int)$itemsCount;
$x = (int)$x;
$items = explode(' ', fgets($input));
$max = $max1 = $max2 = $max3 = 0;
foreach ($items as $item) {
    $max1 = max($max1 + $item, 0);
    $max2 = max($max2 + $item * $x, $max1);
    $max3 = max($max3 + $item, $max2);
    $max = max($max3, $max);
}
echo $max;

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

[$itemsCount, $x] = explode(' ', fgets($input));
$items = explode(' ', fgets($input));

$max = array_sum($items);
for($length = 1; $length <= $itemsCount; $length++) {
    for ($i = 0; $length + $i <= $itemsCount; $i++) {
        $limit = $length + $i;
        $arr = [];
        for($j = $i; $j < $limit; $j++) {
            $arr[$j] = (int)$items[$j] * (int)$x;
        }
        $summ = 0;
        $j = 0;
        while($j < $itemsCount && ($arr[$j] ?? $items[$j]) < 0) {
            $j++;
        }
        for (; $j < $itemsCount; $j++) {
            $summ += (int)($arr[$j] ?? $items[$j]);
        }
        $max = max($max, $summ);
    }
}
echo $max;

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

[$itemsCount, $x] = explode(' ', fgets($input));
$items = explode(' ', fgets($input));
$max = 0;
for($length = 1; $length <= $itemsCount; $length++) {
    for ($i = 0; $length + $i <= $itemsCount; $i++) {
        $limit = $length + $i;
        $arr = $items;
        for($j = $i; $j < $limit; $j++) {
            $arr[$j] = (int)$items[$j] * (int)$x;
        }
        while(isset($arr[0]) && $arr[0] < 0) {
            array_shift($arr);
        }

        $max = max($max, array_sum($arr));
    }
}
echo $max;

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

[$itemsCount, $x] = explode(' ', fgets($input));
$itemsCount = (int)$itemsCount;
$x = (int)$x;
$items = explode(' ', fgets($input));
$max = $max1 = $max2 = $max3 = 0;
foreach ($items as $item) {
    $max1 = max($max1 + $item, 0);
    $max2 = max($max2 + $item * $x, $max1);
    $max3 = max($max3 + $item, $max2);
    $max = max($max3, $max);
}
echo $max;

<?php
# 1155D
[$itemsCount, $x] = fscanf(STDIN, '%u %u');
$items = explode(' ', fgets(STDIN));
$max = $max1 = $max2 = $max3 = 0;
foreach ($items as $item) {
    $max1 = max($max1 + $item, 0);
    $max2 = max($max2 + $item * $x, $max1);
    $max3 = max($max3 + $item, $max2);
    $max = max($max3, $max);
}
echo printf('%.0f', $max);


You're given an array $$$a$$$. You should repeat the following operation $$$k$$$ times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0.

The first line contains integers $$$n$$$ and $$$k$$$ $$$(1 \le n,k \le 10^5)$$$, the length of the array and the number of operations you should perform. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, the elements of the array.

Print the minimum non-zero element before each operation in a new line.

NoteIn the first sample:In the first step: the array is $$$[1,2,3]$$$, so the minimum non-zero element is 1.In the second step: the array is $$$[0,1,2]$$$, so the minimum non-zero element is 1.In the third step: the array is $$$[0,0,1]$$$, so the minimum non-zero element is 1.In the fourth and fifth step: the array is $$$[0,0,0]$$$, so we printed 0.In the second sample:In the first step: the array is $$$[10,3,5,3]$$$, so the minimum non-zero element is 3.In the second step: the array is $$$[7,0,2,0]$$$, so the minimum non-zero element is 2.

<?php
list($n, $k) = explode(' ', trim(fgets(STDIN)));
$items = explode(' ', trim(fgets(STDIN)));
sort($items);
$i = 0;
$min = $items[$i++];
$sum = $min;
echo $min ."\n";

while ($k > 1) {
    if ($i >= $n) {
        echo "0\n";
        $k--;
        continue;
    }

    $min = $items[$i++] - $sum;

    if ($min <= 0) {
        continue;
    }

    $sum += $min;
    echo $min ."\n";

    $k--;
    while ($i < $n && $items[$i] == $sum) {
        $i++;
    }
}


Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial heights of the parts of the wall.

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise.

NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete.

<?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, $func = null) {$a = [];$ind = $indexFrom;foreach (explode(' ', fgets($this->_fh)) as $item) {$a[$ind++] = $func?$func((int)$item):(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();
$a = $ir->readArrayOfInt($n, 0, function($e){return $e&1;});

$stack = [];
foreach ($a as $k=>$v) {
	if ($v) {
		if ($stack && ($k - current($stack) - 1)%2==0) {
			array_pop($stack);
		} else {
			$stack[]=$k;
		}
	}
}

if (count($stack)==0) {
	$result = true;
} elseif(count($stack)>1) {
	$result = false;
} else {
	$e = array_pop($stack)&1;
	if ($e) {
		$result = false;
	} else {
		$result = ($n%2==1);
	}
}

echo $result ? 'YES' : 'NO';

<?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();
$a = $ir->readArrayOfInt($n);

$m = max($a);
$sd = $m*$n - array_sum($a);

$allOdds = true;
for ($i=1; $i<$n; $i++) {
	if (abs($a[$i] - $a[$i-1])%2==0) {
		$allOdds = false;
		break;
	}
}

if ($allOdds) {
	echo 'NO';
	exit();
}

if ($sd%2==0 || $n%2==1) {
	echo 'YES';
} else {
	echo 'NO';
}


Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis!The computers bought for the room were different. Some of them had only USB ports, some — only PS/2 ports, and some had both options.You have found a price list of a certain computer shop. In it, for m mouses it is specified the cost and the type of the port that is required to plug the mouse in (USB or PS/2). Each mouse from the list can be bought at most once.You want to buy some set of mouses from the given price list in such a way so that you maximize the number of computers equipped with mouses (it is not guaranteed that you will be able to equip all of the computers), and in case of equality of this value you want to minimize the total cost of mouses you will buy.

The first line contains three integers a, b and c (0 ≤ a, b, c ≤ 105)  — the number of computers that only have USB ports, the number of computers, that only have PS/2 ports, and the number of computers, that have both options, respectively. The next line contains one integer m (0 ≤ m ≤ 3·105)  — the number of mouses in the price list. The next m lines each describe another mouse. The i-th line contains first integer vali (1 ≤ vali ≤ 109)  — the cost of the i-th mouse, then the type of port (USB or PS/2) that is required to plug the mouse in.

Output two integers separated by space — the number of equipped computers and the total cost of the mouses you will buy.

NoteIn the first example you can buy the first three mouses. This way you will equip one of the computers that has only a USB port with a USB mouse, and the two PS/2 mouses you will plug into the computer with PS/2 port and the computer with both ports.

<?
  list($a, $b, $c) = explode(' ', trim(fgets(STDIN)));
  $n = trim(fgets(STDIN));
  for ($i = 0; $i < $n; $i++) {
    list($x, $s) = explode(' ', trim(fgets(STDIN)));
    if ($s == "USB") {
      $u[] = $x;
    } elseif ($s == "PS/2") {
      $p[] = $x;
    }
  }

  sort($u);

  $e = array();

  function arrSum($inArray) {
    $result = 0;
    foreach ($inArray as $value) {
      $result = bcadd($result, $value);
    }
    return $result;
  }

  if (count($u) <= $a) {
    $ans += count($u);
    $sum = bcadd($sum, arrSum($u));
  } else {
    $e = array_slice($u, $a, count($u) - $a);
    $ans += $a;
    $sum = bcadd($sum, arrSum(array_slice($u, 0, $a)));
  }

  sort($p);

  if (count($p) <= $b) {
    $ans += count($p);
    $sum = bcadd($sum, arrSum($p));
  } else {
    $e = array_merge($e, array_slice($p, $b, count($p) - $b));
    $ans += $b;
    $sum = bcadd($sum, arrSum(array_slice($p, 0, $b)));
  }

  sort($e);

  if (count($e) <= $c) {
    $ans += count($e);
    $sum = bcadd($sum, arrSum($e));
  } else {
    $ans += $c;
    $sum = bcadd($sum, arrSum(array_slice($e, 0, $c)));
  }

  printf("%d %s\n", $ans, $sum);

?>

<?
  list($a, $b, $c) = explode(' ', trim(fgets(STDIN)));
  $n = trim(fgets(STDIN));
  for ($i = 0; $i < $n; $i++) {
    list($x, $s) = explode(' ', trim(fgets(STDIN)));
    if ($s == "USB") {
      $u[] = $x;
    } elseif ($s == "PS/2") {
      $p[] = $x;
    }
  }

  sort($u);

  $e = array();

  if (count($u) <= $a) {
    $ans += count($u);
    $sum += array_sum($u);
  } else {
    $e = array_slice($u, $a, count($u) - $a);
    $ans += $a;
    $sum += array_sum(array_slice($u, 0, $a));
  }
  sort($p);

  if (count($p) <= $b) {
    $ans += count($p);
    $sum += array_sum($p);
  } else {
    $e = array_merge($e, array_slice($p, $b, count($p) - $b));
    $ans += $b;
    $sum += array_sum(array_slice($p, 0, $b));
  }

  sort($e);

  if (count($e) <= $c) {
    $ans += count($e);
    $sum += array_sum($e);
  } else {
    $ans += $c;
    $sum += array_sum(array_slice($e, 0, $c));
  }

  printf("%d %.0f\n", $ans, $sum);

?>

<?
  list($a, $b, $c) = explode(' ', trim(fgets(STDIN)));
  $n = trim(fgets(STDIN));
  for ($i = 0; $i < $n; $i++) {
    list($x, $s) = explode(' ', trim(fgets(STDIN)));
    if ($s == "USB") {
      $u[] = $x;
    } elseif ($s == "PS/2") {
      $p[] = $x;
    }
  }

  sort($u);

  $f = array();

  if (count($u) <= $a) {
    $ans += count($u);
    $sum += array_sum($u);
  } else {
    $f = array_slice($u, $a, count($u) - $a);
    $ans += $a;
    $sum += array_sum(array_slice($u, 0, $a));
  }
  sort($p);

  if (count($p) <= $b) {
    $ans += count($p);
    $sum += array_sum($p);
  } else {
    $s = array_merge($f, array_slice($p, $b, count($p) - $b));
    $ans += $b;
    $sum += array_sum(array_slice($p, 0, $b));
  }

  sort($s);

  if (count($s) <= $c) {
    $ans += count($s);
    $sum += array_sum($s);
  } else {
    $ans += $c;
    $sum += array_sum(array_slice($s, 0, $c));
  }

  printf("%d %d\n", $ans, $sum);

?>