The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:   the size he wanted, if he specified one size;  any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.

The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000. The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants. The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.

If it is not possible to present a t-shirt to each participant, print «NO» (without quotes). Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them.


Recently Monocarp got a job. His working day lasts exactly $$$m$$$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $$$n$$$ minutes $$$a_1, a_2, \dots, a_n$$$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $$$a_i$$$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $$$d$$$ minutes pass between any two coffee breaks. Monocarp also wants to take these $$$n$$$ coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $$$d$$$ minutes pass between the end of any working day and the start of the following working day.For each of the $$$n$$$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.

The first line contains three integers $$$n$$$, $$$m$$$, $$$d$$$ $$$(1 \le n \le 2\cdot10^{5}, n \le m \le 10^{9}, 1 \le d \le m)$$$ — the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le m)$$$, where $$$a_i$$$ is some minute when Monocarp wants to have a coffee break.

In the first line, write the minimum number of days required to make a coffee break in each of the $$$n$$$ given minutes.  In the second line, print $$$n$$$ space separated integers. The $$$i$$$-th of integers should be the index of the day during which Monocarp should have a coffee break at minute $$$a_i$$$. Days are numbered from $$$1$$$. If there are multiple optimal solutions, you may print any of them.

NoteIn the first example, Monocarp can take two coffee breaks during the first day (during minutes $$$1$$$ and $$$5$$$, $$$3$$$ minutes will pass between these breaks). One break during the second day (at minute $$$2$$$), and one break during the third day (at minute $$$3$$$).In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day.

<?php
class node
{
	public $id;
	public $time;
	public $value;
	public function __construct($id,$time){
          $this->id = $id;
          $this->time = $time;
          $this->value = null;
	}
}
function cmp($first,$second){
   if($first->time < $second->time){
   	    return -1;
   }
   else if($first->time > $second->time){
   	    return 1;
   }
   return 0;
}
fscanf(STDIN,"%d %d %d",$n,$m,$d);
$times = fgets(STDIN);
$times = explode(' ',trim($times));
$node_array = array();
$answer = array();
$days = 0;
for($i = 0;$i < $n;$i++){
    array_push($node_array,new node($i,(int)$times[$i]));
}
usort($node_array,'cmp');
$j = 1;
for($i = 0; $i < $n;$i++){
	//var_dump($node_array[$i]->time);
    if(empty($node_array[$i]->value)){
    	$node_array[$i]->value = ++$days;
    	$id = $node_array[$i]->id;
    	$answer[$id] = $node_array[$i]->value;
    }
    while($j < $n){
        if($node_array[$j]->time - $node_array[$i]->time > $d){
        	$node_array[$j]->value = $node_array[$i]->value;
        	$id = $node_array[$j]->id;
        	$answer[$id] = $node_array[$i]->value;
        	++$j;
        	break;
        }
        $j++;
    }
}
echo $days . "\n";
echo $answer[0];
for($i = 1;$i < $n;$i++)
	echo " ".$answer[$i];
echo "\n";

<?php
class node
{
	public $id;
	public $time;
	public $value;
	public function __construct($id,$time){
          $this->id = $id;
          $this->time = $time;
          $this->value = null;
	}
}
function cmp($first,$second){
   if($first->time < $second->time){
   	    return -1;
   }
   else if($first->time > $second->time){
   	    return 1;
   }
   return 0;
}
fscanf(STDIN,"%d %d %d",$n,$m,$d);
$times = fgets(STDIN);
$times = explode(' ',trim($times));
$node_array = array();
$answer = array();
$days = 0;
for($i = 0;$i < $n;$i++){
    array_push($node_array,new node($i,(int)$times[$i]));
}
usort($node_array,'cmp');
$j = 1;
for($i = 0; $i < $n;$i++){
    if(empty($node_array[$i]->value)){
    	$node_array[$i]->value = ++$days;
    	$id = $node_array[$i]->id;
    	$answer[$id] = $node_array[$i]->value;
    }
    while($j < $n){
        if($node_array[$j]->time - $node_array[$i]->time > $d){
        	$node_array[$j]->value = $node_array[$i]->value;
        	$id = $node_array[$j]->id;
        	$answer[$id] = $node_array[$i]->value;
        	break;
        }
        $j++;
    }
}
echo $days . "\n";
echo $answer[0];
for($i = 1;$i < $n;$i++)
	echo " ".$answer[$i];
echo "\n";


You are given a bracket sequence $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.You can change the type of some bracket $$$s_i$$$. It means that if $$$s_i = $$$ ')' then you can change it to '(' and vice versa.Your task is to calculate the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the bracket sequence. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.

Print one integer — the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.


You are given a long decimal number $$$a$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$. You also have a function $$$f$$$ that maps every digit from $$$1$$$ to $$$9$$$ to some (possibly the same) digit from $$$1$$$ to $$$9$$$.You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in $$$a$$$, and replace each digit $$$x$$$ from this segment with $$$f(x)$$$. For example, if $$$a = 1337$$$, $$$f(1) = 1$$$, $$$f(3) = 5$$$, $$$f(7) = 3$$$, and you choose the segment consisting of three rightmost digits, you get $$$1553$$$ as the result.What is the maximum possible number you can obtain applying this operation no more than once?

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of digits in $$$a$$$. The second line contains a string of $$$n$$$ characters, denoting the number $$$a$$$. Each character is a decimal digit from $$$1$$$ to $$$9$$$. The third line contains exactly $$$9$$$ integers $$$f(1)$$$, $$$f(2)$$$, ..., $$$f(9)$$$ ($$$1 \le f(i) \le 9$$$).

Print the maximum number you can get after applying the operation described in the statement no more than once.

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
list($a) = explode(' ', trim(fgets(STDIN)));
$aArray = explode(' ', trim(fgets(STDIN)));
$b = true;
$g = false;
$k = [];
foreach(str_split($a) as $sK => &$sV){

    if($sV == $aArray[$sV - 1]){
        $k[] = $sV;
    } elseif($sV < $aArray[$sV - 1] && $b){
        $k[] = $aArray[$sV - 1];
        $g = true;
    } else {
        if ($g){
            $b = false;
        }
        $k[] = $sV;
    }
}
echo implode('',$k);

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));
    $s = '';
    $b = true;
    $g = false;
    foreach ($a AS $k => $v) {
        if ($v == $f[$v-1]) {
            $s.= $v;
        } else if ($b && $f[$v-1] > $v) {
            $s.= $f[$v-1];
            $g = true;
        } else {
            if ($g) {
                $b = false;
            }
            $s.= $v;
        }
    }
    echo $s;
?>

<?php
$a = trim(fgets(STDIN));
$b = str_split(trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
for($x = 0; $x < $a; $x++)
{
     if($c[$b[$x] - 1] > $b[$x])
     {
          $b[$x] = $c[$b[$x] - 1];
     }
}
print implode($b);
?>

<?php
$a = trim(fgets(STDIN));
$b = str_split(trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = 0;
for($x = 0; $x < $a; $x++)
{
     if($c[$b[$x] - 1] >= $b[$x])
     {
          $b[$x] = $c[$b[$x] - 1];
          $d = 1;
     }
     elseif($d == 1)
     {
          break;
     }
}
print implode($b);
?>

<?php
$a = trim(fgets(STDIN));
$b = str_split(trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
for($x = 0; $x < $a; $x++)
{
     if($c[$b[$x] - 1] > $b[$x])
     {
          $b[$x] = $c[$b[$x] - 1];
          break;
     }
}
print implode($b);
?>

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
list($a) = explode(' ', trim(fgets(STDIN)));
$aArray = explode(' ', trim(fgets(STDIN)));
$bFlag = false;
$k = [];
foreach(str_split($a) as $sK => &$sV){

    if($sV == $aArray[$sV - 1] && !$bFlag){
        $k[] = $sV;
    } elseif($sV < $aArray[$sV - 1] && !$bFlag){
        $k[] = $aArray[$sV - 1];
    } else {
        $k[] = $sV;
        $bFlag = true;
    }
}
echo implode('',$k);

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
list($a) = explode(' ', trim(fgets(STDIN)));
$aArray = explode(' ', trim(fgets(STDIN)));
$k = [];
//foreach(str_split($a) as $sK => &$sV){
//    if($sV < $aArray[$sV - 1]){
//        $k[] = $aArray[$sV - 1];
//    } else {
//        $k[] = $sV;
//    }
//}

$iA = strlen($a) < 50 ? $a : 50;
for($i = 0; $i < $iA; $i++){
    if($a[$i] < $aArray[$a[$i]- 1]){
        $a[$i] = $aArray[$a[$i]- 1];
    }
}
echo $a;
//var_dump($k);

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
list($a) = explode(' ', trim(fgets(STDIN)));
$aArray = explode(' ', trim(fgets(STDIN)));
$k = [];
foreach(str_split($a) as $sK => &$sV){
    if($sV < $aArray[$sV - 1]){
        $k[] = $aArray[$sV - 1];
    } else {
        $k[] = $sV;
    }
}
echo implode('',$k);

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));
    $s = '';
    $b = true;
    foreach ($a AS $k => $v) {
        if ($b && $f[$v-1] > $v) {
            $s.= $f[$v-1];
        } else {
            if (!empty($s)) {
                $b = false;
            }
            $s.= $v;
        }
    }
    echo $s;
?>

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));
    $s = '';
    $b = true;
    foreach ($a AS $k => $v) {
        if ($b && $f[$v-1] >= $v) {
            $s.= $f[$v-1];
        } else {
            if (!empty($s)) {
                $b = false;
            }
            $s.= $v;
        }
    }
    echo $s;
?>

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));
    $s = '';
    $b = true;
    foreach ($a AS $v) {
        if ($b && $f[$v-1] > $v) {
            $s.= $f[$v-1];
        } else {
            if (!empty($s)) {
                $b = false;
            }
            $s.= $v;
        }
    }
    echo $s;
?>

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));$s = '';
    foreach ($a AS $v) {
        $s.= $f[$v-1];
    }
    echo $s;
?>

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));
    $s = '';
    $b = true;
    $g = false;
    foreach ($a AS $k => $v) {
        if ($b && $f[$v-1] > $v) {
            $s.= $f[$v-1];
            $g = true;
        } else {
            if ($g) {
                $b = false;
            }
            $s.= $v;
        }
    }
    echo $s;
?>

<?php
    $n = trim(fgets(STDIN));
    $a = str_split(trim(fgets(STDIN)));
    $f = explode(" ", trim(fgets(STDIN)));$s = '';
    foreach ($a AS $v) {
        if ($f[$v-1] > $v) {
            $s.= $f[$v-1];
        } else {
            $s.= $v;
        }
    }
    echo $s;
?>

<?php
$a = trim(fgets(STDIN));
$b = str_split(trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
for($x = 0; $x < 9; $x++)
{
     if($c[$b[$x] - 1] > $b[$x])
     {
          $b[$x] = $c[$b[$x] - 1];
     }
}
print implode($b);
?>

<?php
$a = trim(fgets(STDIN));
$b = str_split(trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = 0;
for($x = 0; $x < $a; $x++)
{
     if($c[$b[$x] - 1] > $b[$x])
     {
          $b[$x] = $c[$b[$x] - 1];
          $d = 1;
     }
     elseif($d == 1)
     {
          break;
     }
}
print implode($b);
?>


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

<?php
$num = (int) trim(fgets(STDIN));
$seq = array_map('intval', explode(' ', trim(fgets(STDIN))));

$slicePos = $prev = 0;
foreach ($seq as $pos => $cur) {
	if ($cur < $prev) {
		if ($slicePos) {
			echo -1;
			exit();
		} else {
			$slicePos = $pos;
		}
	}

	$prev = $cur;
}

if ($slicePos) {
	if ($seq[0] >= $seq[$num - 1]) {
		echo $num - $slicePos;
	} else {
		echo -1;
	}
} else {
	echo 0;
}

<?php
error_reporting("off");
//454B: Little Pony and Sort by Shift
$n = trim(fgets(STDIN)); //$n = 3;
$array = explode(" ", trim(fgets(STDIN))); //$array = explode(" ", "1 3 2");
$biggest = max($array);
$finding = array_keys($array, $biggest);
if ($finding == range(0, $n - 1)) {
  echo 0;
} else {
  $groups = array();

  for($i = 0; $i < count($finding); $i++) {
   if($i > 0 && ($finding[$i - 1] == $finding[$i] - 1)) {
       array_push($groups[count($groups) - 1], $finding[$i]);
    } else { // First value or no match, create a new group
      array_push($groups, array($finding[$i]));
    }
  }

  if (count($groups) > 2) {
    echo -1;
  } elseif (count($groups) == 2) {
    if (in_array(0, $groups[0]) && in_array($n - 1, $groups[1])) {
      $key = max($groups[0]) + 1;
      $go = TRUE;
    } else {
      echo -1;
    }
  } else {
    $lastone = end($finding);
    if ($lastone + 1 == $n) {
      $key = 0;
      $go = TRUE;
    } else {
      $key = $lastone + 1;
      $go = TRUE;
    }
  }
  if ($go == TRUE) {
    $next = $array[$key];
    if ($next !== min($array)) {
      echo -1;
    } else {
      $clone = $array;
      sort($clone);
      $splice = array_splice($clone, 0, $n - $key);
      $frankenstein = array_merge($clone, $splice);
      if ($array === $frankenstein) {
        if ($key == 0) {
          echo 0;
        } else {
          echo $n - $key;
        }
      } else {
        echo -1;
      }
    }
  }
}
?>

<?php
$num = (int) trim(fgets(STDIN));
$array = array_map('intval', explode(' ', trim(fgets(STDIN))));
$maxNumbers = 105;

function twilightSort($array)
{
    $item = array_pop($array);
    array_unshift($array, $item);

    return $array;
}

$result = $array;
$target = $array;
sort($target, SORT_ASC);

for ($i = 0; $i < $maxNumbers; $i++) {
    if ($result === $target) {
        echo "" . $i;
        break;
    }

    $result = twilightSort($result);
}

if ($result !== $target) {
    echo "-1";
}

echo "\n";

<?php
$num = fgets(STDIN);
$seq = explode(' ', fgets(STDIN));

$slicePos = $prev = 0;
foreach ($seq as $pos => $cur) {
	if ($cur < $prev) {
		if (!$slicePos) {
			$slicePos = $pos;
		} else {
			echo -1;
			exit();
		}
	}

	$prev = $cur;
}

if ($slicePos) {
	if ($seq[0] >= $seq[$num - 1]) {
		echo $num - $slicePos;
	} else {
		echo -1;
	}
} else {
	echo 0;
}

<?php
$num = (int) trim(fgets(STDIN));
$seq = array_map('intval', explode(' ', trim(fgets(STDIN))));

$input = [
    'count' => $num,
    'numbers' => $seq,
];

for ($prev = end($input['numbers']), $current = reset($input['numbers']), $spokes = 0, $position = -1; false !== $current; $prev = $current, $current = next($input['numbers'])) {
	if ($prev > $current) {
		$position = key($input['numbers']);
		++$spokes;
	}
}

if (1 != $spokes) {
	$iterations = -1;
} else {
	$iterations = 0 == $position ? 0 : $input['count'] - $position;
}

echo $iterations . "\n";

<?php

$handle = fopen("php://stdin", "r");
$num = fgets($handle);
$maxNumbers = 105;
$array = [];

for ($i = 0; $i < $num; $i++) {
    $array[] = rand(1, $maxNumbers);
}

function twilightSort($array)
{
    $item = array_pop($array);
    array_unshift($array, $item);

    return $array;
}

$result = $array;
$target = $array;
sort($target, SORT_ASC);

for ($i = 0; $i < $maxNumbers; $i++) {
    if ($result === $target) {
        echo "" . $i;
        break;
    }

    $result = twilightSort($result);
}

if ($result !== $target) {
    echo "-1";
}

echo "\n";

<?php
$num = (int) trim(fgets(STDIN));
$seq = array_map('intval', explode(' ', trim(fgets(STDIN))));

$input = [
    'numbers' => $seq,
];

for ($prev = end($input['numbers']), $current = reset($input['numbers']), $spokes = 0, $position = -1; false !== $current; $prev = $current, $current = next($input['numbers'])) {
	if ($prev > $current) {
		$position = key($input['numbers']);
		++$spokes;
	}
}

if (1 != $spokes) {
	$iterations = -1;
} else {
	$iterations = 0 == $position ? 0 : $input['count'] - $position;
}

echo $iterations . "\n";

<?php

$num = fgets(STDIN);
$seq = explode(' ', fgets(STDIN));

$slicePos = $prev = 0;
foreach ($seq as $pos => $cur) {
	if ($cur < $prev) {
		if (!$slicePos) {
			$slicePos = $pos;
		} else {
			echo -1;
			exit();
		}
	}

	$prev = $cur;
}

if ($slicePos) {
	if ($seq[0] > $seq[$num - 1]) {
		echo $num - $slicePos;
	} else {
		echo -1;
	}
} else {
	echo 0;
}

<?php
$num = fgets(STDIN);
$seq = explode(' ', fgets(STDIN));

$isDebug = $seq[0] == 99997;

$slicePos = $prev = 0;
foreach ($seq as $pos => $cur) {
	if ($cur < $prev) {
		if ($slicePos) {
			if ($isDebug) {
				echo $slicePos . ' | ';
			}
			echo -1;
			exit();
		} else {
			$slicePos = $pos;
		}
	}

	$prev = $cur;
}

if ($slicePos) {
	if ($seq[0] >= $seq[$num - 1]) {
		echo $num - $slicePos;
	} else {
		if ($isDebug) {
			echo $slicePos . ' | ' . $seq[0] . ' | ' . $seq[$num - 1] . ' | ';
		}
		echo -1;
	}
} else {
	echo 0;
}

<?php
error_reporting("off");
//454B: Little Pony and Sort by Shift
$n = trim(fgets(STDIN)); //$n = 6;
$array = explode(" ", trim(fgets(STDIN))); //$array = explode(" ", "1 1 1 1 1 1");
$biggest = max($array);
$finding = array_keys($array, $biggest);
$lastone = end($finding);
if ($lastone + 1 == $n) {
  $key = 0;
} else {
  $key = $lastone + 1;
}
$next = $array[$key];
if ($next !== min($array)) {
  echo -1;
} else {
  $clone = $array;
  sort($clone);
  $splice = array_splice($clone, 0, $n - $key);
  $frankenstein = array_merge($clone, $splice);
  if ($array === $frankenstein) {
    if ($key == 0) {
      echo 0;
    } else {
      echo $n - $key;
    }
  } else {
    echo -1;
  }
}
?>

<?php
error_reporting("off");
//454B: Little Pony and Sort by Shift
$n = trim(fgets(STDIN)); //$n = 10;
$array = explode(" ", trim(fgets(STDIN))); //$array = explode(" ", "6 7 8 9 10 1 2 3 4 55");
$biggest = max($array);
$finding = array_keys($array, $biggest);
$lastone = end($finding);
if ($lastone + 1 == $n) {
  $key = 0;
} else {
  $key = $lastone + 1;
}
$next = $array[$key];
$clone = $array;
sort($clone);
$splice = array_splice($clone, 0, $n - $key);
$frankenstein = array_merge($clone, $splice);
if ($array === $frankenstein) {
  echo $key;
} else {
  echo -1;
}
?>

<?php
error_reporting("off");
//454B: Little Pony and Sort by Shift
$n = trim(fgets(STDIN)); //$n = 4;
$array = explode(" ", trim(fgets(STDIN))); //$array = explode(" ", "4 1 2 3");
$biggest = max($array);
$finding = array_keys($array, $biggest);
$lastone = end($finding);
if ($lastone + 1 == $n) {
  $key = 0;
} else {
  $key = $lastone + 1;
}
$next = $array[$key];
if ($next !== min($array)) {
  echo -1;
} else {
  $clone = $array;
  sort($clone);
  $splice = array_splice($clone, 0, $n - $key);
  $frankenstein = array_merge($clone, $splice);
  if ($array === $frankenstein) {
    echo $n - $key;
  } else {
    echo -1;
  }
}
?>


You have a stripe of checkered paper of length $$$n$$$. Each cell is either white or black.What is the minimum number of cells that must be recolored from white to black in order to have a segment of $$$k$$$ consecutive black cells on the stripe?If the input data is such that a segment of $$$k$$$ consecutive black cells already exists, then print 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Next, descriptions of $$$t$$$ test cases follow. The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2\cdot10^5$$$). The second line consists of the letters 'W' (white) and 'B' (black). The line length is $$$n$$$. It is guaranteed that the sum of values $$$n$$$ does not exceed $$$2\cdot10^5$$$.

For each of $$$t$$$ test cases print an integer — the minimum number of cells that need to be repainted from white to black in order to have a segment of $$$k$$$ consecutive black cells.

4

5 3

BBWBW

5 5

BBWBW

5 1

BBWBW

1 1

W

NoteIn the first test case, $$$s$$$="BBWBW" and $$$k=3$$$. It is enough to recolor $$$s_3$$$ and get $$$s$$$="BBBBW". This string contains a segment of length $$$k=3$$$ consisting of the letters 'B'.In the second test case of the example $$$s$$$="BBWBW" and $$$k=5$$$. It is enough to recolor $$$s_3$$$ and $$$s_5$$$ and get $$$s$$$="BBBBB". This string contains a segment of length $$$k=5$$$ consisting of the letters 'B'.In the third test case of the example $$$s$$$="BBWBW" and $$$k=1$$$. The string $$$s$$$ already contains a segment of length $$$k=1$$$ consisting of the letters 'B'.

<?php

$testCases = (int) fgets(STDIN);

$answers = [];

for ($i=0; $i < $testCases; $i++) {
    $fistLine = explode(' ', fgets(STDIN));

    $length = (int) $fistLine[0];
    $target = (int) $fistLine[1];

    $string = fgets(STDIN);
    $cells = str_split($string);

    $firstArrayValue = array_count_values(str_split(substr($string, 0, $target)));
    $current = !empty($firstArrayValue['W']) ? $firstArrayValue['W'] : 0;
    $min = $current;

    for ($j=$target; $j < $length; $j++) {
        // Remove First
        if ($cells[$j - $target] === 'W') {
            $current--;
        }
        // Add to the End
        if ($cells[$j] === 'W') {
            $current++;
        }
        // Check Min Value
        if ($min > $current) {
            $min = $current;
        }
    }

    $answers[] = $min;
}

foreach ($answers as $item) {
    echo $item . PHP_EOL;
}

<?php
$no = 'NO';
$yes = 'YES';
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647
$alph = 'abcdefghijklmnopqrstuvwxyz';
$inter = "\n";
define("INTMAXVALUE",     2147483646);

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

 function solve()
 {
     list($n, $k) = IO::getArray();
     $s = IO::getInt();
     $ans = 0;
    $a[] = 0;
    for ($j = 0; $j < $n; $j++){
      $a[$j + 1] = $a[$j];
      if ($s[$j] == 'W'){
        $a[$j + 1]++;
      }
    }
    $ans = $n;
    for ($i = 0; $i <= $n - $k; $i++){
      $ans = IO::getMinValue($ans, $a[$i + $k] - $a[$i]);
    }
    IO::pr($ans);

 }

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

 class Algor {
     public static function efclidLcm($a, $b) {
         return ($a  / self::efclidGcd($a, $b)) * $b;
     }
     public static function efclidGcd($a, $b) {
             return $b > 0 ? self::efclidGcd($b, $a % $b) : $a;
     }
    public static function isPrime($n) {
         $d = 2;
         while ($n % $d != 0) {
         $d += 1;
         }

        return $d == $n;
    }

     public static function fabicon($n, $a) {
         if($n <= 1) {
             return $a[$n];
         }
         for($i=2; $i<=$n; $i++) {
             $a[$i] = $a[$i-1] + $a[$i-2];
         }

         return $a[$n];
     }

     function getRotate($a, $s, $e, $ind) {
         $ar = [];
         for ($i= $s; $i<=$e; $i++) {
             $ar[$i] = $a[$i];
             $j = $i + $ind > $e ? $i + $ind - $e - 1 : $i + $ind;
             // echo $i, ' ', $j, ' ', $j < $i ? $ar[$j] : $a[$j] , "\n";
             $a[$i] = $j < $i ? $ar[$j] : $a[$j];
         }
         return $a;
     }

}

class bigOperation {
     public static function efclidLcm($a, $b) {
         return bcmul(bcdiv($a,  self::efclidGcd($a, $b)), $b);
     }
     public static function efclidGcd($a, $b) {
             return bccomp($b, 0) == 1 ? self::efclidGcd($b, bcmod($a, $b)) : $a;
     }
    public static function  isBigNumber($n)
    {
        return bccomp($n, INTMAXVALUE) == 1;
    }
    // bcadd — Сложить 2 числа произвольной точности
    public static function  bcAdd($x, $y)
    {
        return bcadd($x, $y);
    }
// bccomp — Сравнение двух чисел произвольной точности
//return 1 if x>y, 0= x==y, -1 x < y
    public static function  bcComp($x, $y)
    {
        return bccomp($x, $y);
    }
// bcdiv — Операция деления для чисел произвольной точности
    public static function  bcDiv($x, $y)
    {
        return bcdiv($x, $y);
    }
// bcmod — Получает остаток от деления чисел с произвольной точностью
    public static function  bcMod($x, $y)
    {
        return bcmod($x, $y);
    }
// bcmul — Умножение двух чисел с произвольной точностью
    public static function  bcMul($x, $y)
    {
        return bcmul($x, $y);
    }
// bcpow — Возведение в степень чисел с произвольной точностью
    public static function  bcPow($x, $y)
    {
        return bcpow($x, $y);
    }
// bcpowmod — Возводит одно число в степень другого и возвращает остаток от деления результата на третье число
// bcscale — Задает количество чисел после десятичной точки по умолчанию для всех bc math функций.
// bcsqrt — Извлекает квадратный корень из числа с произвольной точностью
    public static function  bcSqrt($x, $y)
    {
        return bcsqrt($x, $y);
    }
// bcsub — Вычитает одно число с произвольной точностью из другого
    public static function  bcSub($x, $y)
    {
        return bcsub($x, $y);
    }
    public static function getMaxValue($x, $y) {
        return bccomp($x, $y) == 1 ? $x : $y;
    }
    public static function getMinValue($x, $y) {
        return bccomp($x, $y) == 1 ? $y : $x;
    }

    public static function getDareje($n, $k) {
        if($k == 0) {
            return 1;
        }
        return bcmul($n, self::getDareje($n, $k-1));
    }
}

class Sorting
{
    public static function mergeSort($aArray) {
        if(count($aArray) <= 1) {
            return $aArray;
        }
        $aLeft = [];
        $aRight = [];
        $n =floor(count($aArray) / 2);
        for($i = 0; $i <$n; $i++) {
            $aLeft[] = $aArray[$i];
        }
        for($i = $n; $i <count($aArray); $i++) {
            $aRight[] = $aArray[$i];
        }

        return self::merge(self::mergeSort($aLeft), self::mergeSort($aRight));
    }

    public static function merge($aLeft, $aRight) {
        $aResult = [];
        $iL = 0;
        $iR = 0;

        while($iL < count($aLeft) && $iR < count($aRight)) {
            if($aLeft[$iL] <= $aRight[$iR]) {
                $aResult[] = $aLeft[$iL];
                $iL++;
            } else {
                $aResult[] = $aRight[$iR];
                $iR++;
            }
        }

        while($iL < count($aLeft)) {
            $aResult[] = $aLeft[$iL];
            $iL++;
        }
        while($iR < count($aRight)) {
            $aResult[] = $aRight[$iR];
            $iR++;
        }

        return $aResult;

    }
}

class SolveArchive
{

}

<?php
$testCases = (int) fgets(STDIN);

$answers = [];

for ($i=0; $i < $testCases; $i++) {
    $fistLine = explode(' ', fgets(STDIN));

    $length = (int) $fistLine[0];
    $target = (int) $fistLine[1];

    $string = fgets(STDIN);
    $cells = str_split($string);

    $current = array_count_values(str_split(substr($string, 0, $target)))['W'] ?? 0;
    $min = $current;

    for ($j=$target; $j < $length - $target + 1; $j++) {
        // Remove First
        if ($cells[$j - $target] === 'W') {
            $current--;
        }
        // Add to the End
        if ($cells[$j] === 'W') {
            $current++;
        }
        // Check Min Value
        if ($min > $current) {
            $min = $current;
        }
    }

    $answers[] = $min;
}

foreach ($answers as $item) {
    echo $item . PHP_EOL;
}

<?php

$testCases = (int) fgets(STDIN);

$answers = [];

for ($i=0; $i < $testCases; $i++) {
    $fistLine = explode(' ', fgets(STDIN));

    $length = (int) $fistLine[0];
    $target = (int) $fistLine[1];

    $cells = fgets(STDIN);

    $length = 9;
    $target = 1;
    $cells = 'WWWWWBWWW';

    $cases = [];

    for ($j=0; $j < $length - $target + 1; $j++) {
        $cases[] = str_split(substr($cells, $j, $target));
    }

    $answers[] = min(array_map('getWhite', array_map('array_count_values', $cases)));
}

function getWhite($value)
{
    return !empty($value['W']) ? $value['W'] : 0;
}

foreach ($answers as $item) {
    echo $item . PHP_EOL;
}

<?php

$testCases = (int) fgets(STDIN);

$answers = [];

for ($i=0; $i < $testCases; $i++) {
    $fistLine = explode(' ', fgets(STDIN));

    $length = (int) $fistLine[0];
    $target = (int) $fistLine[1];

    $cells = fgets(STDIN);

    $cases = [];

    for ($j=0; $j < $length - $target + 1; $j++) {
        $add = $j === 0 ? 0 : -1;
        $cases[] = str_split(substr($cells, $j, $j+$target + $add));
    }

    $answers[] = min(array_map('getWhite', array_map('array_count_values', $cases)));
}

function getWhite($value)
{
    return !empty($value['W']) ? $value['W'] : 0;
}

foreach ($answers as $item) {
    echo $item . PHP_EOL;
}

<?php
$no = 'NO';
$yes = 'YES';
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647
$alph = 'abcdefghijklmnopqrstuvwxyz';
$inter = "\n";
define("INTMAXVALUE",     2147483646);

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

 function solve()
 {
     list($n, $k) = IO::getArray();
     $s = IO::getInt();
     $ans = 0;
     $bMax = 0;
     $temp = 0;
     $count = 0;
          for($i=0; $i<$n; $i++) {
             if($s[$i] == 'B')  {
                 $temp ++;
                 $count++;
             } else {
                 $bMax = IO::getMaxValue($bMax, $temp);
                 $temp = 0;

             }
          }

     //   $ans = $bMax > $k ? 0 : $bMax

          if($bMax > $k) {
               $ans = 0;
          } else {
               $ans = $k - $bMax;
               if($ans > $n - $count) {
                  $ans =  $n - $count;
               }
          }

      IO::pr($ans);

 }

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

 class Algor {
     public static function efclidLcm($a, $b) {
         return ($a  / self::efclidGcd($a, $b)) * $b;
     }
     public static function efclidGcd($a, $b) {
             return $b > 0 ? self::efclidGcd($b, $a % $b) : $a;
     }
    public static function isPrime($n) {
         $d = 2;
         while ($n % $d != 0) {
         $d += 1;
         }

        return $d == $n;
    }

     public static function fabicon($n, $a) {
         if($n <= 1) {
             return $a[$n];
         }
         for($i=2; $i<=$n; $i++) {
             $a[$i] = $a[$i-1] + $a[$i-2];
         }

         return $a[$n];
     }

     function getRotate($a, $s, $e, $ind) {
         $ar = [];
         for ($i= $s; $i<=$e; $i++) {
             $ar[$i] = $a[$i];
             $j = $i + $ind > $e ? $i + $ind - $e - 1 : $i + $ind;
             // echo $i, ' ', $j, ' ', $j < $i ? $ar[$j] : $a[$j] , "\n";
             $a[$i] = $j < $i ? $ar[$j] : $a[$j];
         }
         return $a;
     }

}

class bigOperation {
     public static function efclidLcm($a, $b) {
         return bcmul(bcdiv($a,  self::efclidGcd($a, $b)), $b);
     }
     public static function efclidGcd($a, $b) {
             return bccomp($b, 0) == 1 ? self::efclidGcd($b, bcmod($a, $b)) : $a;
     }
    public static function  isBigNumber($n)
    {
        return bccomp($n, INTMAXVALUE) == 1;
    }
    // bcadd — Сложить 2 числа произвольной точности
    public static function  bcAdd($x, $y)
    {
        return bcadd($x, $y);
    }
// bccomp — Сравнение двух чисел произвольной точности
//return 1 if x>y, 0= x==y, -1 x < y
    public static function  bcComp($x, $y)
    {
        return bccomp($x, $y);
    }
// bcdiv — Операция деления для чисел произвольной точности
    public static function  bcDiv($x, $y)
    {
        return bcdiv($x, $y);
    }
// bcmod — Получает остаток от деления чисел с произвольной точностью
    public static function  bcMod($x, $y)
    {
        return bcmod($x, $y);
    }
// bcmul — Умножение двух чисел с произвольной точностью
    public static function  bcMul($x, $y)
    {
        return bcmul($x, $y);
    }
// bcpow — Возведение в степень чисел с произвольной точностью
    public static function  bcPow($x, $y)
    {
        return bcpow($x, $y);
    }
// bcpowmod — Возводит одно число в степень другого и возвращает остаток от деления результата на третье число
// bcscale — Задает количество чисел после десятичной точки по умолчанию для всех bc math функций.
// bcsqrt — Извлекает квадратный корень из числа с произвольной точностью
    public static function  bcSqrt($x, $y)
    {
        return bcsqrt($x, $y);
    }
// bcsub — Вычитает одно число с произвольной точностью из другого
    public static function  bcSub($x, $y)
    {
        return bcsub($x, $y);
    }
    public static function getMaxValue($x, $y) {
        return bccomp($x, $y) == 1 ? $x : $y;
    }
    public static function getMinValue($x, $y) {
        return bccomp($x, $y) == 1 ? $y : $x;
    }

    public static function getDareje($n, $k) {
        if($k == 0) {
            return 1;
        }
        return bcmul($n, self::getDareje($n, $k-1));
    }
}

class Sorting
{
    public static function mergeSort($aArray) {
        if(count($aArray) <= 1) {
            return $aArray;
        }
        $aLeft = [];
        $aRight = [];
        $n =floor(count($aArray) / 2);
        for($i = 0; $i <$n; $i++) {
            $aLeft[] = $aArray[$i];
        }
        for($i = $n; $i <count($aArray); $i++) {
            $aRight[] = $aArray[$i];
        }

        return self::merge(self::mergeSort($aLeft), self::mergeSort($aRight));
    }

    public static function merge($aLeft, $aRight) {
        $aResult = [];
        $iL = 0;
        $iR = 0;

        while($iL < count($aLeft) && $iR < count($aRight)) {
            if($aLeft[$iL] <= $aRight[$iR]) {
                $aResult[] = $aLeft[$iL];
                $iL++;
            } else {
                $aResult[] = $aRight[$iR];
                $iR++;
            }
        }

        while($iL < count($aLeft)) {
            $aResult[] = $aLeft[$iL];
            $iL++;
        }
        while($iR < count($aRight)) {
            $aResult[] = $aRight[$iR];
            $iR++;
        }

        return $aResult;

    }
}

class SolveArchive
{

}

<?php
$no = 'NO';
$yes = 'YES';
$mod = 1000000007;
$intMaxValue = 2147483646; //2147483647
$alph = 'abcdefghijklmnopqrstuvwxyz';
$inter = "\n";
define("INTMAXVALUE",     2147483646);

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

 function solve()
 {
     list($n, $k) = IO::getArray();
     $s = IO::getInt();
     $ans = 0;

     $temp = 0;
     if($n == 1 && $s == 'W') {
          $ans = 1;
     } else {
          for($i=0; $i<$n; $i++) {
             if($s[$i] == 'B')  {
                  $temp++;
                  if($temp == $k) {
                       $temp = 0;
                       if($i > $n - 1 - $k) {
                            break;
                       }
                  }
             } else {
                  if($i <= $n-$k + $temp) {
                       if($temp > 0) {
                           $ans++;
                            $temp++;
                            if($temp == $k) {
                                 $temp = 0;
                            }
                       }
                  } else {
                       break;
                  }

             }
          }
     }

      IO::pr($ans);

 }

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

 class Algor {
     public static function efclidLcm($a, $b) {
         return ($a  / self::efclidGcd($a, $b)) * $b;
     }
     public static function efclidGcd($a, $b) {
             return $b > 0 ? self::efclidGcd($b, $a % $b) : $a;
     }
    public static function isPrime($n) {
         $d = 2;
         while ($n % $d != 0) {
         $d += 1;
         }

        return $d == $n;
    }

     public static function fabicon($n, $a) {
         if($n <= 1) {
             return $a[$n];
         }
         for($i=2; $i<=$n; $i++) {
             $a[$i] = $a[$i-1] + $a[$i-2];
         }

         return $a[$n];
     }

     function getRotate($a, $s, $e, $ind) {
         $ar = [];
         for ($i= $s; $i<=$e; $i++) {
             $ar[$i] = $a[$i];
             $j = $i + $ind > $e ? $i + $ind - $e - 1 : $i + $ind;
             // echo $i, ' ', $j, ' ', $j < $i ? $ar[$j] : $a[$j] , "\n";
             $a[$i] = $j < $i ? $ar[$j] : $a[$j];
         }
         return $a;
     }

}

class bigOperation {
     public static function efclidLcm($a, $b) {
         return bcmul(bcdiv($a,  self::efclidGcd($a, $b)), $b);
     }
     public static function efclidGcd($a, $b) {
             return bccomp($b, 0) == 1 ? self::efclidGcd($b, bcmod($a, $b)) : $a;
     }
    public static function  isBigNumber($n)
    {
        return bccomp($n, INTMAXVALUE) == 1;
    }
    // bcadd — Сложить 2 числа произвольной точности
    public static function  bcAdd($x, $y)
    {
        return bcadd($x, $y);
    }
// bccomp — Сравнение двух чисел произвольной точности
//return 1 if x>y, 0= x==y, -1 x < y
    public static function  bcComp($x, $y)
    {
        return bccomp($x, $y);
    }
// bcdiv — Операция деления для чисел произвольной точности
    public static function  bcDiv($x, $y)
    {
        return bcdiv($x, $y);
    }
// bcmod — Получает остаток от деления чисел с произвольной точностью
    public static function  bcMod($x, $y)
    {
        return bcmod($x, $y);
    }
// bcmul — Умножение двух чисел с произвольной точностью
    public static function  bcMul($x, $y)
    {
        return bcmul($x, $y);
    }
// bcpow — Возведение в степень чисел с произвольной точностью
    public static function  bcPow($x, $y)
    {
        return bcpow($x, $y);
    }
// bcpowmod — Возводит одно число в степень другого и возвращает остаток от деления результата на третье число
// bcscale — Задает количество чисел после десятичной точки по умолчанию для всех bc math функций.
// bcsqrt — Извлекает квадратный корень из числа с произвольной точностью
    public static function  bcSqrt($x, $y)
    {
        return bcsqrt($x, $y);
    }
// bcsub — Вычитает одно число с произвольной точностью из другого
    public static function  bcSub($x, $y)
    {
        return bcsub($x, $y);
    }
    public static function getMaxValue($x, $y) {
        return bccomp($x, $y) == 1 ? $x : $y;
    }
    public static function getMinValue($x, $y) {
        return bccomp($x, $y) == 1 ? $y : $x;
    }

    public static function getDareje($n, $k) {
        if($k == 0) {
            return 1;
        }
        return bcmul($n, self::getDareje($n, $k-1));
    }
}

class Sorting
{
    public static function mergeSort($aArray) {
        if(count($aArray) <= 1) {
            return $aArray;
        }
        $aLeft = [];
        $aRight = [];
        $n =floor(count($aArray) / 2);
        for($i = 0; $i <$n; $i++) {
            $aLeft[] = $aArray[$i];
        }
        for($i = $n; $i <count($aArray); $i++) {
            $aRight[] = $aArray[$i];
        }

        return self::merge(self::mergeSort($aLeft), self::mergeSort($aRight));
    }

    public static function merge($aLeft, $aRight) {
        $aResult = [];
        $iL = 0;
        $iR = 0;

        while($iL < count($aLeft) && $iR < count($aRight)) {
            if($aLeft[$iL] <= $aRight[$iR]) {
                $aResult[] = $aLeft[$iL];
                $iL++;
            } else {
                $aResult[] = $aRight[$iR];
                $iR++;
            }
        }

        while($iL < count($aLeft)) {
            $aResult[] = $aLeft[$iL];
            $iL++;
        }
        while($iR < count($aRight)) {
            $aResult[] = $aRight[$iR];
            $iR++;
        }

        return $aResult;

    }
}

class SolveArchive
{

}


There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.Split the row of the pearls to the maximal number of good segments. Note that each pearl should appear in exactly one segment of the partition.As 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 integer n (1 ≤ n ≤ 3·105) — the number of pearls in a row. The second line contains n integers ai (1 ≤ ai ≤ 109) – the type of the i-th pearl.

On the first line print integer k — the maximal number of segments in a partition of the row. Each of the next k lines should contain two integers lj, rj (1 ≤ lj ≤ rj ≤ n) — the number of the leftmost and the rightmost pearls in the j-th segment. Note you should print the correct partition of the row of the pearls, so each pearl should be in exactly one segment and all segments should contain two pearls of the same type. If there are several optimal solutions print any of them. You can print the segments in any order. If there are no correct partitions of the row print the number "-1".

<?php
$n = intval(trim(fgets(STDIN)));

$sLine = trim( fgets( STDIN ));
$aType = explode(' ',$sLine);
$ans = 0;

$aMap = array();
$res = array();
$pre = -1;

for($i = 0;$i < $n;$i++){
    $aType[ $i ] = intval($aType[ $i ]);
    if(!isset($aMap[ $aType[ $i ] ]) || $aMap[ $aType[ $i ] ] <= intval($pre) ){
        $aMap[ $aType[ $i ] ]  = $i;
    } else {
        $pre = $i;
        $res[] = $i+1;
        $ans ++;
    }
}

if($ans == 0){
    echo -1;
    exit;
}
if($res[$ans - 1] < $n){
    $res[$ans - 1] = $n;
}
printf("%d\n",$ans);
printf("%d %d\n",1,$res[0]);
for($i = 1; $i < $ans ;$i++ ){
    printf("%d %d\n",$res[ $i - 1 ] + 1,$res[$i]);
}


One morning the Cereal Guy found out that all his cereal flakes were gone. He found a note instead of them. It turned out that his smart roommate hid the flakes in one of n boxes. The boxes stand in one row, they are numbered from 1 to n from the left to the right. The roommate left hints like "Hidden to the left of the i-th box" ("To the left of i"), "Hidden to the right of the i-th box" ("To the right of i"). Such hints mean that there are no flakes in the i-th box as well. The Cereal Guy wants to know the minimal number of boxes he necessarily needs to check to find the flakes considering all the hints. Or he wants to find out that the hints are contradictory and the roommate lied to him, that is, no box has the flakes.

The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000) which represent the number of boxes and the number of hints correspondingly. Next m lines contain hints like "To the left of i" and "To the right of i", where i is integer (1 ≤ i ≤ n). The hints may coincide.

The answer should contain exactly one integer — the number of boxes that should necessarily be checked or "-1" if the hints are contradictory.

<?php

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

list($n, $m) = fscanf($stdin, "%d %d");

$l = 1;
$r = $n;

for ($i=0; $i<$m; $i++) {
    list($dir, $x) = fscanf($stdin, "To the %s of %d");
    if ($dir == "left") {
        if ($x <= $r) {
            $r = $x-1;
        }
    } else {
        if ($x >= $l) {
            $l = $x+1;
        }
    }
}

$razn = $r - $l + 1;
if ($razn <= 0) {
    echo "-1\n";
} else {
    echo "$razn\n";
}

exit;


Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.You are given a tree with $$$n$$$ nodes. In the beginning, $$$0$$$ is written on all edges. In one operation, you can choose any $$$2$$$ distinct leaves $$$u$$$, $$$v$$$ and any real number $$$x$$$ and add $$$x$$$ to values written on all edges on the simple path between $$$u$$$ and $$$v$$$.For example, on the picture below you can see the result of applying two operations to the graph: adding $$$2$$$ on the path from $$$7$$$ to $$$6$$$, and then adding $$$-0.5$$$ on the path from $$$4$$$ to $$$5$$$.   Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?Leaf is a node of a tree of degree $$$1$$$. Simple path is a path that doesn't contain any node twice.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes. Each of the next $$$n-1$$$ lines contains two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$), meaning that there is an edge between nodes $$$u$$$ and $$$v$$$. It is guaranteed that these edges form a tree.

If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".  Otherwise, output "YES".  You can print each letter in any case (upper or lower).

NoteIn the first example, we can add any real $$$x$$$ to the value written on the only edge $$$(1, 2)$$$.  In the second example, one of configurations that we can't reach is $$$0$$$ written on $$$(1, 2)$$$ and $$$1$$$ written on $$$(2, 3)$$$.  Below you can see graphs from examples $$$3$$$, $$$4$$$:


Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.There are exactly two exits from Mr. Black's house, let's name them left and right exits. There are several doors in each of the exits, so each door in Mr. Black's house is located either in the left or in the right exit. You know where each door is located. Initially all the doors are closed. Mr. Black can exit the house if and only if all doors in at least one of the exits is open. You are given a sequence in which Mr. Black opened the doors, please find the smallest index $$$k$$$ such that Mr. Black can exit the house after opening the first $$$k$$$ doors.We have to note that Mr. Black opened each door at most once, and in the end all doors became open.

The first line contains integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of doors. The next line contains $$$n$$$ integers: the sequence in which Mr. Black opened the doors. The $$$i$$$-th of these integers is equal to $$$0$$$ in case the $$$i$$$-th opened door is located in the left exit, and it is equal to $$$1$$$ in case it is in the right exit. It is guaranteed that there is at least one door located in the left exit and there is at least one door located in the right exit.

Print the smallest integer $$$k$$$ such that after Mr. Black opened the first $$$k$$$ doors, he was able to exit the house.

NoteIn the first example the first two doors are from the left exit, so when Mr. Black opened both of them only, there were two more closed door in the left exit and one closed door in the right exit. So Mr. Black wasn't able to exit at that moment.When he opened the third door, all doors from the right exit became open, so Mr. Black was able to exit the house.In the second example when the first two doors were opened, there was open closed door in each of the exit.With three doors opened Mr. Black was able to use the left exit.

<?php
# 1143A
$input = fopen('php://stdin', 'rb');
$doorsCount = (int)fgets($input);
$doors = [];
for ($i = 1; $i <= $doorsCount; $i++) {
    $type = fgetc($input);
    fgetc($input);
    $doors[$type] = $i;
}

echo min($doors);

<?php
$n = fgets(STDIN);
$x = array_map('intval', explode(' ', trim(fgets(STDIN))));
for ($i = $n - 1; $x[$i] == $x[$n - 1]; $i--);
echo $i + 1;

<?php

$n = trim(fgets(STDIN));
$arr = explode(" ", trim(fgets(STDIN)));

$cnt = array_count_values($arr);

for($i = 0; $i < count($arr); $i++) {
    $arr[$i] ? $cnt[1]-- : $cnt[0]--;
    if (!($cnt[0] and $cnt[1])) {
        $out = $i;
        break;
    }
}

echo  $out+1;


You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.You are given a time in format HH:MM that is currently displayed on the broken clock. Your goal is to change minimum number of digits in order to make clocks display the correct time in the given format.For example, if 00:99 is displayed, it is enough to replace the second 9 with 3 in order to get 00:39 that is a correct time in 24-hours format. However, to make 00:99 correct in 12-hours format, one has to change at least two digits. Additionally to the first change one can replace the second 0 with 1 and obtain 01:39.

The first line of the input contains one integer 12 or 24, that denote 12-hours or 24-hours format respectively. The second line contains the time in format HH:MM, that is currently displayed on the clock. First two characters stand for the hours, while next two show the minutes.

The only line of the output should contain the time in format HH:MM that is a correct time in the given format. It should differ from the original in as few positions as possible. If there are many optimal solutions you can print any of them.

<?php
$input = fopen("php://stdin", 'r');
$data = stream_get_contents($input);

$data_arr = explode(PHP_EOL,$data);
$time_format = $data_arr[0];
$time = $data_arr[1];
$time_arr = explode(':',$time);
$hours = $time_arr[0];
$minutes = $time_arr[1];

function correct_hours()
{
    global $hours;
    global $time_format;
    $h_1 = $hours[0];
    $h_2 = $hours[1];
    if ($time_format==12)
    {
        if ($h_2==0) {
            if ($h_1!==1) {
                $h_1 = 1;
            }
        }
        else {
            if (!in_array($h_1,[0,1])) {
                $h_1 = 0;
            }
            if ($h_1==1) {
                if (!in_array($h_2,[0,1,2]))
                {
                    $h_2 = 0;
                }
            }
        }
    }
    else {
        if ($h_1 > 2) {
            $h_1 = 1;
        }
        elseif ($h_1==2) {
            if ($h_2 > 3) {
                $h_2 = 2;
            }
        }
    }
    return $h_1.$h_2;
}

function correct_minutes()
{
    global $minutes;
    $m_1 = $minutes[0];
    $m_2 = $minutes[1];

    if ($m_1 > 5) {
        $m_1 = 3;
    }
    return $m_1.$m_2;
}

$out_hours = correct_hours();
$out_minutes = correct_minutes();
echo $out_hours.':'.$out_minutes;

<?php

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

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

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

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

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

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

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

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

function diffCnt($baseTime, $time) {
	$return = 0;
	for ($i = 0; $i < 5; $i++) {
		if ($baseTime[$i] != $time[$i]) {
			$return++;
		}
	}
	return $return;
}

function getAnswer($is_test = false, $f = false) {
	$stream = STDIN;
	if ($is_test)
		$stream = $f;
	/* begin body */
	$format = readNum($stream);
	$baseTime = readString($stream);
	$answer = array(
		'res' => '',
		'diff' => 55,
	);
	$minHour = 0;
	$maxHour = 23;
	if ($format == 12) {
		$minHour = 1;
		$maxHour = 12;
	}
	for ($hour = $minHour; $hour <= $maxHour; $hour++) {
		for ($minute = 0; $minute < 60; $minute++) {
			$checkHour = $hour;
			while (strlen($checkHour) < 2)
				$checkHour = '0' . $checkHour;
			$checkMinute = $minute;
			while (strlen($checkMinute) < 2)
				$checkMinute = '0' . $checkMinute;
			$checkTime = "{$checkHour}:{$checkMinute}";

			$diff = diffCnt($baseTime, $checkTime);
			if ($diff < $answer['diff']) {
				$answer['diff'] = $diff;
				$answer['res'] = $checkTime;
			}
		}
	}
	echo $answer['res'];
	/* / end body */
}

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

<?php
$format=trim(fgets(STDIN));
$input=trim(fgets(STDIN));
$l=preg_split('//',$input,-1,PREG_SPLIT_NO_EMPTY);
$hh='';$mm='';
list($hh,$mm)=explode(':',$input);
if($format=='12'){
	if($hh>12)
		if($hh{0}>1){
			if($hh{1}>0) $l[0]='0';
			else $l[0]='1';
		}else $l[1]='2';
}else
	if($hh>23) $l[0]='0';
if($mm>59)
	$l[3]='0';
fwrite(STDOUT,implode('',$l));
fwrite(STDOUT,PHP_EOL.'Press "Enter" to exit...'); exit(fgets(STDIN)); //Остановка
?>

<?php
$format=trim(fgets(STDIN));
$input=trim(fgets(STDIN));
$l=preg_split('//',$input,-1,PREG_SPLIT_NO_EMPTY);
$hh='';$mm='';
list($hh,$mm)=explode(':',$input);
if($format=='12'){
	if($hh>12)
		if($hh{1}>0) $l[0]='0';
		else $l[1]='1';
	if($hh<1)
		$l[1]='1';
}else
	if($hh>23) $l[0]='0';
if($mm>59)
	$l[3]='0';
fwrite(STDOUT,implode('',$l));
?>

<?php
$format=trim(fgets(STDIN));
$input=trim(fgets(STDIN));
$l=preg_split('//',$input,-1,PREG_SPLIT_NO_EMPTY);
$hh='';$mm='';
list($hh,$mm)=explode(':',$input);
if($format=='12'){
	if($hh>12)
		if($hh{0}>1) $l[0]='0';
		else $l[1]='1';
	if($hh<1)
		$l[1]='1';
}else
	if($hh>23) $l[0]='0';
if($mm>59)
	$l[3]='0';
fwrite(STDOUT,implode('',$l));
?>

<?php
$format=trim(fgets(STDIN));
$input=trim(fgets(STDIN));
$l=preg_split('//',$input,-1,PREG_SPLIT_NO_EMPTY);
$hh='';$mm='';
list($hh,$mm)=explode(':',$input);
if($format=='12'){
	if($hh>12)
		if($hh{1}>0) $l[0]='0';
		else $l[1]='1';
}else
	if($hh>23) $l[0]='0';
if($mm>59)
	$l[3]='0';
fwrite(STDOUT,implode('',$l));
?>

<?php

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

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

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

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

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

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

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

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

function diffCnt($baseTime, $time) {
	$return = 0;
	for ($i = 0; $i < 5; $i++) {
		if ($baseTime[$i] != $time[$i]) {
			$return++;
		}
	}
	return $return;
}

function getAnswer($is_test = false, $f = false) {
	$stream = STDIN;
	if ($is_test)
		$stream = $f;
	/* begin body */
	$format = readNum($stream);
	$baseTime = readString($stream);
	$answer = array(
		'res' => '',
		'diff' => 55,
	);
	$minHour = 0;
	$maxHour = 23;
	if ($format == 12) {
		$minHour = 1;
		$maxHour = 12;
	}
	for ($hour = $minHour; $hour < $maxHour; $hour++) {
		for ($minute = 0; $minute < 60; $minute++) {
			$checkHour = $hour;
			while (strlen($checkHour) < 2)
				$checkHour = '0' . $checkHour;
			$checkMinute = $minute;
			while (strlen($checkMinute) < 2)
				$checkMinute = '0' . $checkMinute;
			$checkTime = "{$checkHour}:{$checkMinute}";
			$diff = diffCnt($baseTime, $checkTime);
			if ($diff < $answer['diff']) {
				$answer['diff'] = $diff;
				$answer['res'] = $checkTime;
			}
		}
	}
	echo $answer['res'];
	/* / end body */
}

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

<?php

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

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

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

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

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

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

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

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

function getAnswer($is_test = false, $f = false) {
	$stream = STDIN;
	if ($is_test)
		$stream = $f;
	/* begin body */
	$format = readNum($stream);
	$time = readString($stream);
	list($hour, $minute) = explode(':', $time);
	if ($minute >= 60) {
		$minute = '0' . ($minute % 10);
	}
	if ($format == 24) {
		if ($hour >= 24) {
			$hour = '0' . ($hour % 10);
		}
	} else {
		if ($hour > 12) {
			$hour = '0' . ($hour % 10);
		}
		if ($hour == '00') {
			$hour = '01';
		}
	}
	echo "{$hour}:{$minute}";
	/* / end body */
}

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

<?php

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

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

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

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

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

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

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

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

function getAnswer($is_test = false, $f = false) {
	$stream = STDIN;
	if ($is_test)
		$stream = $f;
	/* begin body */
	$format = readNum($stream);
	$time = readString($stream);
	list($hour, $minute) = explode(':', $time);
	if ($minute >= 60) {
		$minute = '0' . ($minute % 10);
	}
	if ($format == 24) {
		if ($hour >= 24) {
			$hour = '0' . ($hour % 10);
		}
	} else {
		if ($hour >= 12) {
			$hour = '0' . ($hour % 10);
		}
		if ($hour == '00') {
			$hour = '01';
		}
	}
	echo "{$hour}:{$minute}";
	/* / end body */
}

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

<?php

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

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

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

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

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

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

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

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

function getAnswer($is_test = false, $f = false) {
	$stream = STDIN;
	if ($is_test)
		$stream = $f;

	/* begin body */
	$type = readNum($stream);
	$baseTime = readString($stream);

    $clock = explode(":", $baseTime);
    $hour = $clock[0];
    $minutes = $clock[1];
    if ($minutes >= 60) {
        $minutes -= 60;
        $hour + 1;
    }
    if ($minutes < 10) {
        $minutes = '0' . $minutes;
    }
    if ($type == 12) {
        $hour %= $type;
        if ($hour < 10) {
            echo '0' . $hour . ":" . $minutes;
        }
    }
    if ($type == 24) {
        $hour %= $type;
        if ($hour < 10) {
            echo '0' . $hour . ":" . $minutes;
        }
    }
	/* / end body */
}

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


Polycarp has recently got himself a new job. He now earns so much that his old wallet can't even store all the money he has.Berland bills somehow come in lots of different sizes. However, all of them are shaped as rectangles (possibly squares). All wallets are also produced in form of rectangles (possibly squares).A bill $$$x \times y$$$ fits into some wallet $$$h \times w$$$ if either $$$x \le h$$$ and $$$y \le w$$$ or $$$y \le h$$$ and $$$x \le w$$$. Bills can overlap with each other in a wallet and an infinite amount of bills can fit into a wallet. That implies that all the bills Polycarp currently have fit into a wallet if every single one of them fits into it independently of the others.Now you are asked to perform the queries of two types:  $$$+~x~y$$$ — Polycarp earns a bill of size $$$x \times y$$$;  $$$?~h~w$$$ — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \times w$$$. It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.For each query of type $$$2$$$ print "YES" if all the bills he has earned to this moment fit into a wallet of given size. Print "NO" otherwise.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^5$$$) — the number of queries. Each of the next $$$n$$$ lines contains a query of one of these two types:   $$$+~x~y$$$ ($$$1 \le x, y \le 10^9$$$) — Polycarp earns a bill of size $$$x \times y$$$;  $$$?~h~w$$$ ($$$1 \le h, w \le 10^9$$$) — Polycarp wants to check if all the bills he has earned to this moment fit into a wallet of size $$$h \times w$$$.  It is guaranteed that there is at least one query of type $$$1$$$ before the first query of type $$$2$$$ and that there is at least one query of type $$$2$$$ in the input data.

NoteThe queries of type $$$2$$$ of the example:  Neither bill fits;  Both bills fit (just checking that you got that bills can overlap);  Both bills fit (both bills are actually the same);  All bills fit (too much of free space in a wallet is not a problem);  Only bill $$$1 \times 5$$$ fit (all the others don't, thus it's "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;}
}

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

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

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

$ir = new InputReader();

/* TASK */

$n = $ir->readInt();

$smax = 0;
$dmax = 0;
$wmin = 0;
for ($i=0; $i<$n; $i++) {
	list($q, $a, $b) = $ir->readArrayOfString(3);
	$a = (int)$a;
	$b = (int)$b;
	//echo "============ $q $a $b\n";
	if ($q=='+') {
		$smax = max([$smax, $a*$b]);
		$dmax = max([$dmax, $a, $b]);
		$wmin = max([$wmin, min([$a, $b])]);
		//echo "SM $smax : DM $dmax\n";
	} else {
		$s = $a*$b;
		$d = $a>$b ? $a : $b;
		$w = $a>$b ? $b : $a;
		//echo "S  $s : D  $d\n";
		if ($s>=$smax && $d>=$dmax && $w>=$wmin) {
			echo "YES\n";
		} else {
			echo "NO\n";
		}
		flush();
	}
}

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

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

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

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

$ir = new InputReader();

/* TASK */

$n = $ir->readInt();

$smax = 0;
$dmax = 0;
$wmax = 0;
for ($i=0; $i<$n; $i++) {
	list($q, $a, $b) = $ir->readArrayOfString(3);
	$a = (int)$a;
	$b = (int)$b;
	//echo "============ $q $a $b\n";
	if ($q=='+') {
		$smax = max([$smax, $a*$b]);
		$dmax = max([$dmax, $a, $b]);
		$wmin = max([$wmax, intval($smax/$dmax)]);
		//echo "SM $smax : DM $dmax\n";
	} else {
		$s = $a*$b;
		$d = $a>$b ? $a : $b;
		$w = $a>$b ? $b : $a;
		//echo "S  $s : D  $d\n";
		if ($s>=$smax && $d>=$dmax && $w>=$wmin) {
			echo "YES\n";
		} else {
			echo "NO\n";
		}
		flush();
	}
}

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

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

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

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

$ir = new InputReader();

/* TASK */

$n = $ir->readInt();

$smax = 0;
$dmax = 0;
$wmax = 0;
for ($i=0; $i<=$n; $i++) {
	list($q, $a, $b) = $ir->readArrayOfString(3);
	$a = (int)$a;
	$b = (int)$b;
	//echo "============ $q $a $b\n";
	if ($q=='+') {
		$smax = max([$smax, $a*$b]);
		$dmax = max([$dmax, $a, $b]);
		$wmin = max([$wmax, intval($smax/$dmax)]);
		//echo "SM $smax : DM $dmax\n";
	} else {
		$s = $a*$b;
		$d = $a>$b ? $a : $b;
		$w = $a>$b ? $b : $a;
		//echo "S  $s : D  $d\n";
		if ($s>=$smax && $d>=$dmax && $w>=$wmin) {
			echo "YES\n";
		} else {
			echo "NO\n";
		}
		flush();
	}
}

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

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

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

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

$ir = new InputReader();

/* TASK */

$n = $ir->readInt();

$smax = 0;
$dmax = 0;
$wmax = 0;
for ($i=0; $i<$n; $i++) {
	list($q, $a, $b) = $ir->readArrayOfString(3);
	$a = (int)$a;
	$b = (int)$b;
	//echo "============ $q $a $b\n";
	if ($q=='+') {
		$smax = max([$smax, $a*$b]);
		$dmin = max([$dmax, max([$a, $b])]);
		$wmin = max([$wmax, min([$a, $b])]);
		//echo "SM $smax : DM $dmax\n";
	} else {
		$s = $a*$b;
		$d = $a>$b ? $a : $b;
		$w = $a>$b ? $b : $a;
		//echo "S  $s : D  $d\n";
		if ($s>=$smax && $d>=$dmin && $w>=$wmin) {
			echo "YES\n";
		} else {
			echo "NO\n";
		}
		flush();
	}
}

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

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

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

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

$ir = new InputReader();

/* TASK */

$n = $ir->readInt();

$smax = 0;
$dmax = 0;
$wmax = 0;
for ($i=0; $i<$n; $i++) {
	list($q, $a, $b) = $ir->readArrayOfString(3);
	$a = (int)$a;
	$b = (int)$b;
	//echo "============ $q $a $b\n";
	if ($q=='+') {
		$smax = max([$smax, $a*$b]);
		$dmax = max([$dmax, $a, $b]);
		$wmin = max([$wmax, min([$a, $b])]);
		//echo "SM $smax : DM $dmax\n";
	} else {
		$s = $a*$b;
		$d = $a>$b ? $a : $b;
		$w = $a>$b ? $b : $a;
		//echo "S  $s : D  $d\n";
		if ($s>=$smax && $d>=$dmax && $w>=$wmin) {
			echo "YES\n";
		} else {
			echo "NO\n";
		}
		flush();
	}
}


You are given an array $$$a$$$ consisting of $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$.In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array $$$[2, 1, 4]$$$ you can obtain the following arrays: $$$[3, 4]$$$, $$$[1, 6]$$$ and $$$[2, 5]$$$.Your task is to find the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing this operation an arbitrary (possibly, zero) number of times.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$). The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each query print one integer in a single line — the maximum possible number of elements divisible by $$$3$$$ that are in the array after performing described operation an arbitrary (possibly, zero) number of times.

NoteIn the first query of the example you can apply the following sequence of operations to obtain $$$3$$$ elements divisible by $$$3$$$: $$$[3, 1, 2, 3, 1] \rightarrow [3, 3, 3, 1]$$$.In the second query you can obtain $$$3$$$ elements divisible by $$$3$$$ with the following sequence of operations: $$$[1, 1, 1, 1, 1, 2, 2] \rightarrow [1, 1, 1, 1, 2, 3] \rightarrow [1, 1, 1, 3, 3] \rightarrow [2, 1, 3, 3] \rightarrow [3, 3, 3]$$$.

<?php
#1176B
$m = trim(fgets(STDIN));
while ($m--) {
    $n = trim(fgets(STDIN));
    $arr = explode(' ', trim(fgets(STDIN)));
    $mods = [0, 0, 0];
    foreach ($arr as $value) {
        $mods[bcmod($value, 3)]++;
    }
    echo $mods[0] + min($mods[1], $mods[2]) + floor(abs($mods[1] - $mods[2]) / 3) . PHP_EOL;
}

<?php
#1176B
$m = trim(fgets(STDIN));
while ($m--) {
    $n = trim(fgets(STDIN));
    $arr = explode(' ', trim(fgets(STDIN)));
    $mods = [0, 0, 0];
    foreach ($arr as $value) {
        $mods[$value % 3]++;
    }
    echo $mods[0] + min($mods[1], $mods[2]) + floor(abs($mods[1] - $mods[2]) / 3) . PHP_EOL;
}

<?php

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

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

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

    fgets($__fp);
    $nums = array_map('intval', explode(' ', fgets($__fp)));

    $map = [0 => 0, 1 => 0, 2 => 0];
    foreach ($nums as $num) {
        $map[$num % 3]++;
    }

    $min = min($map[1], $map[2]);
    $map[1] -= $min;
    $map[2] -= $min;

    $res[] = $map[0] + $min + floor($map[1] / 3)+ floor($map[2] / 3);
}

echo join(PHP_EOL, $res), PHP_EOL;

<?php

$t = trim(fgets(STDIN));
while ($t--) {
    $n = trim(fgets(STDIN));
    $a = explode(' ', trim(fgets(STDIN)));
    $zeroz=0; $onez=0; $twoz=0; $cizi=0;
    foreach ($a as $e) {
        if(bcmod($e,3)==0) $zeroz++;
        else if(bcmod($e,3)==1) $onez++;
        else if(bcmod($e,3)==2) $twoz++;
    }
    if($onez>=$twoz)
    {
        $cizi+=$twoz;
        $onez-=$twoz;
        $twoz=0;
    }
    else if($twoz>$onez)
    {
        $cizi+=$onez;
        $twoz-=$onez;
        $onez=0;
    }
    if($onez>=3) $cizi+=floor($onez/3);
    else if($twoz>=3) $cizi+=floor($twoz/3);

    echo $zeroz+$cizi. PHP_EOL;
}

<?php
#1176B
$m = trim(fgets(STDIN));
while ($m--) {
    $n = trim(fgets(STDIN));
    $arr = explode(' ', trim(fgets(STDIN)));
    $amount = 0;
    for ($i = 0; $i < $n; $i++) {
        if ($arr[$i] % 3 === 0) {
            $amount++;
            unset($arr[$i]);
        }
    }
    while (count($arr) > 1) {
        $item = array_pop($arr);
        foreach ($arr as $i => $value) {
            if (($item + $value) % 3 === 0) {
                $item = null;
                $amount++;
                unset($arr[$i]);
                break;
            }
        }
        sort($arr);
        if ($item !== null) {
            $arr[0] += $item;
            sort($arr);
        }
    }

    echo $amount . PHP_EOL;
}

<?php

$t = trim(fgets(STDIN));
while ($t--) {
    $n = trim(fgets(STDIN));
    $a = explode(' ', trim(fgets(STDIN)));
    $zeroz=0; $onez=0; $twoz=0; $cizi=0;
    foreach ($a as $e) {
        if(bcmod($e,3)==0) $zeroz++;
        else if(bcmod($e,3)==1) $onez++;
        else if(bcmod($e,3)==2) $twoz++;
    }
    if($onez>=$twoz)
    {
        $cizi+=$twoz;
        $onez-=$twoz;
        $twoz=0;
    }
    else if($twoz>$onez)
    {
        $cizi+=$onez;
        $twoz-=$onez;
        $onez=0;
    }
    if($onez>=3) $cizi+=$onez/3;
    else if($twoz>=3) $cizi+=$twoz/3;

    echo $zeroz+$cizi. PHP_EOL;
}


For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for?Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got one hour! Solve it!  Wheatley decided to try to make a test chamber. He made a nice test chamber, but there was only one detail absent — cubes.For completing the chamber Wheatley needs $$$n$$$ cubes. $$$i$$$-th cube has a volume $$$a_i$$$.Wheatley has to place cubes in such a way that they would be sorted in a non-decreasing order by their volume. Formally, for each $$$i>1$$$, $$$a_{i-1} \le a_i$$$ must hold.To achieve his goal, Wheatley can exchange two neighbouring cubes. It means that for any $$$i>1$$$ you can exchange cubes on positions $$$i-1$$$ and $$$i$$$.But there is a problem: Wheatley is very impatient. If Wheatley needs more than $$$\frac{n \cdot (n-1)}{2}-1$$$ exchange operations, he won't do this boring work.Wheatly wants to know: can cubes be sorted under this conditions?

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — number of cubes. The second line contains $$$n$$$ positive integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$) — volumes of cubes. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a word in a single line: "YES" (without quotation marks) if the cubes can be sorted and "NO" (without quotation marks) otherwise.

NoteIn the first test case it is possible to sort all the cubes in $$$7$$$ exchanges.In the second test case the cubes are already sorted.In the third test case we can make $$$0$$$ exchanges, but the cubes are not sorted yet, so the answer is "NO".


Let $$$n$$$ be a positive integer. Let $$$a, b, c$$$ be nonnegative integers such that $$$a + b + c = n$$$.Alice and Bob are gonna play rock-paper-scissors $$$n$$$ times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock $$$a$$$ times, paper $$$b$$$ times, and scissors $$$c$$$ times.Alice wins if she beats Bob in at least $$$\lceil \frac{n}{2} \rceil$$$ ($$$\frac{n}{2}$$$ rounded up to the nearest integer) hands, otherwise Alice loses.Note that in rock-paper-scissors:  rock beats scissors;  paper beats rock;  scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers $$$a, b, c$$$, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win.If there are multiple answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then, $$$t$$$ testcases follow, each consisting of three lines:    The first line contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).  The second line contains three integers, $$$a, b, c$$$ ($$$0 \le a, b, c \le n$$$). It is guaranteed that $$$a + b + c = n$$$.  The third line contains a string $$$s$$$ of length $$$n$$$. $$$s$$$ is made up of only 'R', 'P', and 'S'. The $$$i$$$-th character is 'R' if for his $$$i$$$-th Bob plays rock, 'P' if paper, and 'S' if scissors.

For each testcase:    If Alice cannot win, print "NO" (without the quotes).  Otherwise, print "YES" (without the quotes). Also, print a string $$$t$$$ of length $$$n$$$ made up of only 'R', 'P', and 'S' — a sequence of hands that Alice can use to win. $$$t$$$ must contain exactly $$$a$$$ 'R's, $$$b$$$ 'P's, and $$$c$$$ 'S's.  If there are multiple answers, print any of them.  The "YES" / "NO" part of the output is case-insensitive (i.e. "yEs", "no" or "YEs" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive.

NoteIn the first testcase, in the first hand, Alice plays paper and Bob plays rock, so Alice beats Bob. In the second hand, Alice plays scissors and Bob plays paper, so Alice beats Bob. In the third hand, Alice plays rock and Bob plays scissors, so Alice beats Bob. Alice beat Bob 3 times, and $$$3 \ge \lceil \frac{3}{2} \rceil = 2$$$, so Alice wins.In the second testcase, the only sequence of hands that Alice can play is "RRR". Alice beats Bob only in the last hand, so Alice can't win. $$$1 < \lceil \frac{3}{2} \rceil = 2$$$.

<?php

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

$n1 = intval(fgets($__fp));

$res = [];

$map = [
    'R' => 'S',
    'P' => 'R',
    'S' => 'P',
];

$back_map = array_flip($map);

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

    $n = intval(trim(fgets($__fp)));

    list($r, $p, $s) = explode(' ', trim(fgets($__fp)));
    $tries = [
        'R' => $r,
        'P' => $p,
        'S' => $s
    ];

    $moves = str_split(trim(fgets($__fp)));

    $success = 0;
    $seq = [];

    foreach ($moves as $q) {

        $k = $back_map[$q];
        if ($tries[$k] > 0) {
            $tries[$k]--;
            $success++;
            $seq[] = $back_map[$q];
        } else {
            $seq[] = null;
        }
    }

    if ($success >= ceil($n / 2)) {
        foreach ($seq as $i123 => $n2) {
            if ($n2 === null) {
                foreach ($tries as $k3 => $nums) {
                    if($nums > 0)
                    {
                        $tries[$k3]--;
                        $seq[$i123] = $k3;
                        break;
                    }
                }
            }
        }

        $res[] = 'YES';
        $res[] = join('', $seq);

    } else {

        $res[] = 'NO';
    }

}

echo implode(PHP_EOL, $res);