You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} < t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 > 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 300$$$) — the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \le n_i \le 300$$$) — the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.

If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print $$$k_i$$$ — the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$$$ — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.

<?php
$a = trim(fgets(STDIN));
for($x = 0; $x < $a; $x++)
{
     $c = trim(fgets(STDIN));
     $b = trim(fgets(STDIN));
     if(strlen($b) == 1)
     {
          print "NO\n";
     }
     elseif(strlen($b) == 2)
     {
          if($b[0] < $b[1])
          {
               print "YES\n";
               print "2\n";
               print $b[0] . " " . $b[1] . "\n";
          }
          else
          {
               print "NO\n";
          }
     }
     else
     {
          print "YES\n";
          print "2\n";
          print $b[0] . " " . substr($b, 1) . "\n";
     }
}
?>

<?php
fscanf(STDIN,"%d",$tc);
while($tc--)
{
	  fscanf(STDIN,"%d",$len);
	  fscanf(STDIN,"%s",$num);
	  //$digits='123456789';
	  //$str="";
	  $len=strlen($num);

      if($len==2)
       	{
       		if($num[0]<$num[1])
       	 	   echo "YES\n2\n$num[0] $num[1]\n";
       	 	else
       	 		echo "NO\n";

       	}

       	else
       	{
       	 	echo "YES\n2\n$num[0] ";
       	 	echo substr($num,1,$len-1)."\n";
       	}
}

<?php
list($n) = explode(' ', trim(fgets(STDIN)));
$n = intval($n);
for($i=0; $i <$n;$i++){
    list($x) = explode(' ', trim(fgets(STDIN)));
    list($y) = explode(' ', trim(fgets(STDIN)));
    if($x <2){
        echo "NO\n";
    } else{
        $s1 = substr($y,0,1);
        $s2 = substr($y,1,$x);
        if($s1 >= $s2){
            echo "NO\n";
        } else {
            echo "YES\n";
            echo "2\n";
            echo $s1 . ' ' . $s2. "\n";
        }
    }
}

<?php

$n = fgets(STDIN);

for($i = 0; $i<$n; $i++){
    $c = trim(fgets(STDIN));
    $k = trim(fgets(STDIN));

    $yes = false;

    for($j = 1; $j<$c; $j++){
        if(intval(substr($k, 0, $j)) < intval(substr($k,-($c-$j)))){
          $yes = true;
          break;
        }
    }
    if($yes){
        fwrite(STDOUT, "YES\n2\n".substr($k, 0, $j)." ".substr($k,-($c-$j))."\n");
    }else{
        fwrite(STDOUT, "NO\n");
    }
}

?>

<?

$n = trim(fgets(STDIN));
for($i=0;$i<$n;$i++){
	$cnt = intval(trim(fgets(STDIN)));
	$str = trim(fgets(STDIN));

	if($cnt<2){
		echo "NO\n";
	}elseif($cnt==2){
		if(intval(substr($str,0,1))>=intval(substr($str,1,1))){
			echo "NO\n";
		}else{
			echo "YES\n";
			echo "2\n";
			echo substr($str,0,1)." ".substr($str,1,1)."\n";
		}
	}else{
		echo "YES\n";
		echo "2\n";
		echo substr($str,0,1)." ".substr($str,1)."\n";
	}
}

<?php
fscanf(STDIN,"%d",$tc);
while($tc--)
{
	  fscanf(STDIN,"%d",$len);
	  fscanf(STDIN,"%s",$num);
	  $digits='123456789';
	  $str="";
	  $len=strlen($num);
      for ($i=0; $i <strlen($digits) ; $i++)
       {
      	   for ($j=0; $j <$len ; $j++)
      	    {
      	   	    if($digits[$i]==$num[$j])
      	   	    {
      	   	    	$str.=$digits[$i];
      	   	    	break;
      	   	    }

      	    }
       }
       if(strlen($str)==1)
       	 echo "NO\n";
        else if(($len==2)&&($num[0]!=$num[1]))
       	{
       		if($num[0]<$num[1])
       	 	   echo "YES\n2\n$num[0] $num[1]\n";
       	 	else
       	 		echo "NO\n";

       	}

       	else
       	{
       	 	echo "YES\n2\n$num[0] ";
       	 	echo substr($num,1,$len-1)."\n";
       	}
}

<?php

$n = fgets(STDIN);

for($i = 0; $i<$n; $i++){
    $c = trim(fgets(STDIN));
    $k = trim(fgets(STDIN));

    $yes = false;

    for($j = 1; $j<$c; $j++){
        if(intval(substr($k, 0, $j)) < intval(substr($k,-($c-$j)))){
          $yes = true;
          break;
        }
    }
    if($yes){
        fwrite(STDOUT, "YES\n2\n".substr($k, 0, $j)." ".substr($k,$j,0)."\n");
    }else{
        fwrite(STDOUT, "NO\n");
    }
}

?>

<?

$n = trim(fgets(STDIN));
for($i=0;$i<$n;$i++){
	$cnt = intval(trim(fgets(STDIN)));
	$str = trim(fgets(STDIN));

	if($cnt<2){
		echo "NO\n";
	}elseif($cnt==2){
		if(intval(substr($str,0,1))<=intval(substr($str,1,1))){
			echo "NO\n";
		}else{
			echo "YES\n";
			echo "2";
			echo substr($str,0,1)." ".substr($str,1,1)."\n";
		}
	}else{
		echo "YES\n";
		echo "2";
		echo substr($str,0,1)." ".substr($str,1)."\n";
	}
}

<?

$n = trim(fgets(STDIN));
for($i=0;$i<$n;$i++){
	$cnt = intval(trim(fgets(STDIN)));
	$str = trim(fgets(STDIN));

	if($cnt<2){
		echo "NO\n";
	}elseif($cnt==2){
		if(intval(substr($str,0,1))<=intval(substr($str,1,1))){
			echo "NO\n";
		}else{
			echo "YES\n";
			echo substr($str,0,1)." ".substr($str,1,1)."\n";
		}
	}else{
		echo "YES\n";
		echo substr($str,0,1)." ".substr($str,1)."\n";
	}
}

<?
$n = trim(fgets(STDIN));
for($i=0;$i<$n;$i++){
	$cnt = intval(trim(fgets(STDIN)));
	$str = trim(fgets(STDIN));

	if($cnt<2){
		echo "NO\n";
	}elseif($cnt==2){
		if(intval(substr($str,0,1))<=intval(substr($str,1,1))){
			echo "NO\n";
		}else{
			echo substr($str,0,1)." ".substr($str,1,1);
		}
	}else{
		echo substr($str,0,1)." ".substr($str,1);
	}
}

<?

$n = trim(fgets(STDIN));
for($i=0;$i<$n;$i++){
	$cnt = intval(trim(fgets(STDIN)));
	$str = trim(fgets(STDIN));

	if($cnt<2){
		echo "NO\n";
	}elseif($cnt==2){
		if(intval(substr($str,0,1))<=intval(substr($str,1,1))){
			echo "NO\n";
		}else{
			echo "YES\n";
			echo "2\n";
			echo substr($str,0,1)." ".substr($str,1,1)."\n";
		}
	}else{
		echo "YES\n";
		echo "2\n";
		echo substr($str,0,1)." ".substr($str,1)."\n";
	}
}


You are given a string $$$s$$$, consisting only of characters '0' or '1'. Let $$$|s|$$$ be the length of $$$s$$$.You are asked to choose some integer $$$k$$$ ($$$k > 0$$$) and find a sequence $$$a$$$ of length $$$k$$$ such that:   $$$1 \le a_1 < a_2 < \dots < a_k \le |s|$$$;  $$$a_{i-1} + 1 < a_i$$$ for all $$$i$$$ from $$$2$$$ to $$$k$$$. The characters at positions $$$a_1, a_2, \dots, a_k$$$ are removed, the remaining characters are concatenated without changing the order. So, in other words, the positions in the sequence $$$a$$$ should not be adjacent.Let the resulting string be $$$s'$$$. $$$s'$$$ is called sorted if for all $$$i$$$ from $$$2$$$ to $$$|s'|$$$ $$$s'_{i-1} \le s'_i$$$.Does there exist such a sequence $$$a$$$ that the resulting string $$$s'$$$ is sorted?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$s$$$ ($$$2 \le |s| \le 100$$$). Each character is either '0' or '1'.

For each testcase print "YES" if there exists a sequence $$$a$$$ such that removing the characters at positions $$$a_1, a_2, \dots, a_k$$$ and concatenating the parts without changing the order produces a sorted string. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase you can choose a sequence $$$a=[1,3,6,9]$$$. Removing the underlined letters from "10101011011" will produce a string "0011111", which is sorted.In the second and the third testcases the sequences are already sorted.In the fourth testcase you can choose a sequence $$$a=[3]$$$. $$$s'=$$$ "11", which is sorted.In the fifth testcase there is no way to choose a sequence $$$a$$$ such that $$$s'$$$ is sorted.

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $s = str_split(IO::str());
    $d = $s;
    $last0 = -3;
    $bool = true;
    $bl = true;
    foreach ($s as $k => $v) {
        if($v == 1 && $bl) {
            if($k - $last0 >= 2) {
                $last0 = $k;
                unset($d[$k]);
            } else {
                $bl = false;
            }
        }
        if ($v == 0 && !$bl) {
            if($k - $last0 >= 2) {
                $last0 = $k;
                unset($d[$k]);
            } else {
                break;
            }
        }
    }
    $last = -1;
    foreach ($d as $f) {
        if ($last > $f) {
            $bool = false;
            break;
        }
        $last = $f;
    }

    if ($bool) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }

}

<?php
	$t = trim(fgets(STDIN));
	while ($t--) {
		$s = trim(fgets(STDIN));
		$last = 0;
    	$z = false;

	    if($s[0] == '1')
	        $last = 1;

	    for($i = 1; $i < strlen($s); $i++)
	    {
	        if(!$z) {
	            if($s[$i] == '1') {
	                $cur = $i + 1;

	                if($last + 1 >= $cur) $z = true;
	                else $last = $cur;
	            }
	        }
	        else
	        {
	            if($s[$i] == '0')
	            {
	                $cur = $i + 1;

	                if($last + 1 >= $cur)
	                {
	                    print "NO\n";;
	                    continue 2;
	                }

	                $last = $cur;
	            }
	        }
	    }

	    print "YES\n";
	}
?>

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $s = str_split(IO::str());
    $last0 = $last1 = -3;
    $bool0 = $bool1 = true;
    $aZero = $aOne = [];
    foreach ($s as $k => $v) {
        if (($k == 0 && $s[1] != $v) || ($k == count($s) - 1 && $s[count($s) - 2] != $v)) {
            continue;
        }
        if($v == 0) {
            $aZero[$k] = $k;
        } else {
            $aOne[$k] = $k;
        }
    }

    for($i = 0; $i <= end($aZero); $i++) {
        if ($s[$i] == 1) {
            if ($i - $last1 < 2) {
                $bool1 = false;
            }
            $last1 = $i;
        }
        if ($s[$i] == 0) {
            if ($i - $last0 < 2) {
                $bool0 = false;
            }
            $last0 = $i;
        }
    }

    if ($bool1 || $bool0) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }

}

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $s = str_split(IO::str());
    $last0 = $last1 = -3;
    $bool0 = $bool1 = true;
    $aZero = $aOne = [];
    foreach ($s as $k => $v) {
        if($v == 0) {
            $aZero[$k] = $k;
        } else {
            $aOne[$k] = $k;
        }
    }
    for($i = 0; $i <= end($aZero); $i++) {
        if ($s[$i] == 1) {
            if ($i - $last1 < 2) {
                $bool1 = false;
            }
            $last1 = $i;
        }
        if ($s[$i] == 0) {
            if ($i - $last0 < 2) {
                $bool0 = false;
            }
            $last0 = $i;
        }
    }

    if ($bool1 || $bool0) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }

}

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $s = str_split(IO::str());
    $last = -3;
    $bool = true;
    foreach ($s as $k => $v) {
        if ($v == 0 && $k - $last < 2) {
            $bool = false;
            //break;
        }
        if($v == 0) {
            $last = $k;
        }
    }
    if (!$bool) {
        $bool = true;
        $last1 = -3;
        for ($i = 0; $i < $last; $i++) {
            if ($s[$i] == 1 && $i - $last1 < 2) {
                $bool = false;
                break;
            }
            if($s[$i] == 1) {
                $last1 = $i;
            }
        }
    }

    if ($bool) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }

}

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $s = str_split(IO::str());
    $last = -3;
    $bool = true;
    foreach ($s as $k => $v) {
        if ($v == 0 && $k - $last < 2) {
            $bool = false;
            //break;
        }
        if($v == 0) {
            $last = $k;
        }
    }
    if (!$bool && $last + 1 != count($s)) {
        $bool = true;
        $last1 = -3;
        for ($i = 0; $i < $last; $i++) {
            if ($s[$i] == 1 && $i - $last1 < 2) {
                $bool = false;
                break;
            }
            if($s[$i] == 1) {
                $last1 = $i;
            }
        }
    }

    if ($bool) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }

}

<?php
# ╔══╗─╔═══╗╔╗╔═╗╔════╗╔═══╗╔════╗
# ║╔╗║─║╔══╝║║║╔╝╚══╗═║║╔═╗║║╔╗╔╗║
# ║╚╝╚╗║╚══╗║╚╝╝───╔╝╔╝║║─║║╚╝║║╚╝
# ║╔═╗║║╔══╝║╔╗║──╔╝╔╝─║╚═╝║──║║
# ║╚═╝║║╚══╗║║║╚╗╔╝═╚═╗║╔═╗║──║║
# ╚═══╝╚═══╝╚╝╚═╝╚════╝╚╝─╚╝──╚╝

class IO {
    public static function arr($sDelimeter = ' ') { return explode($sDelimeter, trim(fgets(STDIN))); }
    public static function str() { return trim(fgets(STDIN)); }
    public static function yes() { echo 'YES' . PHP_EOL; }
    public static function no() { echo 'NO' . PHP_EOL; }
    public static function line($sLine) { echo $sLine . PHP_EOL; }
    public static function lcm($x, $y) {
        $p = $x;
        $q = $y;
        while ($x != $y)
        {
            if ($x > $y)
                $x = $x - $y;
            else
                $y = $y - $x;
        }
        return ($p*$q)/$x;
    }
}

//$iQueryCount = 1;
$iQueryCount = IO::str();

while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $s = str_split(IO::str());
    $last = -3;
    $bool = true;
    foreach ($s as $k => $v) {
        if ($v == 0 && $k - $last < 2) {
            $bool = false;
            break;
        }
        if($v == 0) {
            $last = $k;
        }
    }
    if (!$bool) {
        $bool = true;
        $last1 = -3;
        for ($i = 0; $i < $last; $i++) {
            if ($s[$i] == 1 && $i - $last1 < 2) {
                $bool = false;
                break;
            }
            if($s[$i] == 1) {
                $last1 = $i;
            }
        }
    }

    if ($bool) {
        IO::line('YES');
    } else {
        IO::line('NO');
    }

}


Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$$$ Here $$$\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 45\,000$$$)

If such partition doesn't exist, print "No" (quotes for clarity). Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitions — print any of them.

NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\mathrm{gcd}(2, 4) = 2 > 1$$$, hence that is one of the possible answers.


Consider an array $$$a$$$ of $$$n$$$ positive integers.You may perform the following operation:   select two indices $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$), then  decrease all elements $$$a_l, a_{l + 1}, \dots, a_r$$$ by $$$1$$$. Let's call $$$f(a)$$$ the minimum number of operations needed to change array $$$a$$$ into an array of $$$n$$$ zeros.Determine if for all permutations$$$^\dagger$$$ $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true. $$$^\dagger$$$ An array $$$b$$$ is a permutation of an array $$$a$$$ if $$$b$$$ consists of the elements of $$$a$$$ in arbitrary order. For example, $$$[4,2,3,4]$$$ is a permutation of $$$[3,2,4,4]$$$ while $$$[1,2,2]$$$ is not a permutation of $$$[1,2,3]$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — description of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "YES" (without quotes) if for all permutations $$$b$$$ of $$$a$$$, $$$f(a) \leq f(b)$$$ is true, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we can change all elements to $$$0$$$ in $$$5$$$ operations. It can be shown that no permutation of $$$[2, 3, 5, 4]$$$ requires less than $$$5$$$ operations to change all elements to $$$0$$$.In the third test case, we need $$$5$$$ operations to change all elements to $$$0$$$, while $$$[2, 3, 3, 1]$$$ only needs $$$3$$$ operations.

<?php

fscanf(STDIN, '%u', $t);
while ($t--) {
    fscanf(STDIN, '%u', $n);

    $ar = fscanf(STDIN, str_repeat('%u ', $n));

    if ($n <= 2) {
        echo 'YES'.PHP_EOL;
        continue;
    }

    // try asc

    $sorted = true;

    for ($i = 1; $i < $n; ++$i) {
        if ($ar[$i - 1] > $ar[$i]) {
            $sorted = false;
            break;
        }
    }

    if (!$sorted) {
        $sorted = true;
        for (++$i; $i < $n; ++$i) {
            if ($ar[$i - 1] < $ar[$i]) {
                $sorted = false;
                break;
            }
        }
    }

    if ($sorted) {
        echo 'YES'.PHP_EOL;
    } else {
        echo 'NO'.PHP_EOL;
    }
}

/*

1
5
1 2 3 2 1
// yes

1
5
3 2 1 2 3
// no

1
5
1 2 3 4 5
// yes

1
4
1 1 1 1
// yes

1
7
2 1 3 4 2 1 2
// no
 */

<?php

fscanf(STDIN, '%u', $t);
while ($t--) {
    fscanf(STDIN, '%u', $n);

    $ar = fscanf(STDIN, str_repeat('%u ', $n));

    if ($n <= 2) {
        echo 'YES'.PHP_EOL;
        continue;
    }

//    // try desc
//
//    $sorted = true;
//    for ($i = 1; $i < $n; ++$i) {
//        if ($ar[$i - 1] < $ar[$i]) {
//            $sorted = false;
//            break;
//        }
//    }
//    // 4 4 3 2 1
//    if (!$sorted) {
//        $sorted = true;
//
//        for (++$i; $i < $n; ++$i) {
//            if ($ar[$i - 1] > $ar[$i]) {
//                $sorted = false;
//                break;
//            }
//        }
//    }

    // try asc
    $sorted = false;

    if (!$sorted) {
        $sorted = true;

        for ($i = 1; $i < $n; ++$i) {
            if ($ar[$i - 1] > $ar[$i]) {
                $sorted = false;
                break;
            }
        }

        if (!$sorted) {
            $sorted = true;
            for (++$i; $i < $n; ++$i) {
                if ($ar[$i - 1] < $ar[$i]) {
                    $sorted = false;
                    break;
                }
            }
        }
    }

    if ($sorted) {
        echo 'YES'.PHP_EOL;
    } else {
        echo 'NO'.PHP_EOL;
    }
}

/*

1
5
1 2 3 2 1
// yes

1
5
3 2 1 2 3
// no

1
5
1 2 3 4 5
// yes

1
4
1 1 1 1

1
7
2 1 3 4 2 1 2
// no
 */

<?php
$cin = fopen("php://stdin", "r");
$cout = fopen("php://stdout", "w");

$t; $n; $arr;
fscanf($cin, "%d\n", $t);
for ($T = 0; $T < $t; $T++) {
    fscanf($cin, "%d\n", $n);
    $arr = explode(" ", trim(fgets($cin)));
    $p = [(int)$arr[0]];
    $prev = (int)$arr[0];
    for ($i = 1; $i < $n; $i++) {
        if ((int)$arr[$i] != $prev) {
            array_push($p, (int)$arr[$i]);
        }
        $prev = (int)$arr[$i];
    }
    $works = true;
    for ($i = 1; $i < count($p) - 1; $i++) {
        if ($p[$i-1] > $p[$i] and $p[$i] < $p[$i+1]) $works = false;
    }
    if ($works) fwrite($cout, "YES\n");
    else fwrite($cout, "NO\n");
} ?>

<?php

fscanf(STDIN, '%u', $t);
while ($t--) {
    fscanf(STDIN, '%u', $n);

    $ar = fscanf(STDIN, str_repeat('%u ', $n));

    if ($n <= 2) {
        echo 'YES'.PHP_EOL;
        continue;
    }

    $sorted = true;
    for ($i = 1; $i < $n; ++$i) {
        if ($ar[$i] > $ar[$i - 1]) {
            $sorted = false;
            break;
        }
    }
    // 4 4 3 2 1
    if (!$sorted) {
        $sorted = true;

        for (++$i; $i < $n; ++$i) {
            if ($ar[$i] < $ar[$i - 1]) {
                $sorted = false;
                break;
            }
        }
    }

    // try desc

    if (!$sorted) {
        $sorted = true;

        for ($i = 1; $i < $n; ++$i) {
            if ($ar[$i] < $ar[$i - 1]) {
                $sorted = false;
                break;
            }
        }

        if (!$sorted) {
            $sorted = true;
            for (++$i; $i < $n; ++$i) {
                if ($ar[$i] > $ar[$i - 1]) {
                    $sorted = false;
                    break;
                }
            }
        }
    }

    if ($sorted) {
        echo 'YES'.PHP_EOL;
    } else {
        echo 'NO'.PHP_EOL;
    }
}

/*

1
5
1 2 3 2 1
// yes

1
5
3 2 1 2 3
// yes

1
5
1 2 3 4 5
// yes

1
4
1 1 1 1

 */


A bracket sequence is called regular if it is possible to obtain correct arithmetic expression by inserting characters «+» and «1» into this sequence. For example, sequences «(())()», «()» and «(()(()))» are regular, while «)(», «(()» and «(()))(» are not.One day Johnny got bracket sequence. He decided to remove some of the brackets from it in order to obtain a regular bracket sequence. What is the maximum length of a regular bracket sequence which can be obtained?

Input consists of a single line with non-empty string of «(» and «)» characters. Its length does not exceed 106.

Output the maximum possible length of a regular bracket sequence.

<?php
$s = rtrim(fgets(STDIN));
$ret = strlen($s);
$now = 0;
foreach (str_split($s) as $c)
{
    if ($c == '(')
    {
        $now++;
    }
    else
    {
        $now--;
        if ($now < 0)
        {
            $now++;
            $ret--;
        }
    }
}
$ret -= $now;
echo "$ret\n";
?>


You have a string $$$s$$$ consisting of lowercase Latin alphabet letters. You can color some letters in colors from $$$1$$$ to $$$k$$$. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, $$$k$$$ strings will be created, $$$i$$$-th of them will contain all the characters colored in the color $$$i$$$, written in the order of their sequence in the string $$$s$$$.Your task is to color the characters of the string so that all the resulting $$$k$$$ strings are palindromes, and the length of the shortest of these $$$k$$$ strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input data sets in the test.  The descriptions of the input data sets follow. The first line of the description of each input data set contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the length of the string and the number of colors in which its letters can be painted. The second line of the description of each input data set contains a string $$$s$$$ of length $$$n$$$ consisting of lowercase letters of the Latin alphabet. It is guaranteed that the sum of n over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each set of input data, output a single integer  — the maximum length of the shortest palindrome string that can be obtained.

10

8 2

bxyaxzay

6 3

aaaaaa

6 1

abcdef

6 6

abcdef

3 2

dxd

11 2

abcabcabcac

6 6

sipkic

7 2

eatoohd

3 1

llw

6 2

bfvfbv

Note In the first test case, $$$s$$$="bxyaxzay", $$$k=2$$$. We use indices in the string from $$$1$$$ to $$$8$$$. The following coloring will work: $$$\mathtt{\mathbf{\color{red}{b}\color{blue}{xy}\color{red}{a}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$ (the letter z remained uncolored). After painting:  swap two red characters (with the indices $$$1$$$ and $$$4$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{x}z\color{red}{a}\color{blue}{y}}}$$$;  swap two blue characters (with the indices $$$5$$$ and $$$8$$$), we get $$$\mathtt{\mathbf{\color{red}{a}\color{blue}{xy}\color{red}{b}\color{blue}{y}z\color{red}{a}\color{blue}{x}}}$$$. Now, for each of the two colors we write out the corresponding characters from left to right, we get two strings $$$\mathtt{\mathbf{\color{red}{aba}}}$$$ and $$$\mathtt{\mathbf{\color{blue}{xyyx}}}$$$. Both of them are palindromes, the length of the shortest is $$$3$$$. It can be shown that the greatest length of the shortest palindrome cannot be achieved. In the second set of input data, the following coloring is suitable: $$$[1, 1, 2, 2, 3, 3]$$$. There is no need to swap characters. Both received strings are equal to aa, they are palindromes and their length is $$$2$$$. In the third set of input data, you can color any character and take it into a string. In the fourth set of input data, you can color the $$$i$$$th character in the color $$$i$$$. In the fifth set of input data can be colored in each of the colors of one character. In the sixth set of input data, the following coloring is suitable: $$$[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0]$$$. Rearrange the characters so as to get the palindromes abcba and acbca.

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = str_replace ([ "\r", "\n" ], "", fgets (STDIN));

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    if (floor ($n / $k) == 1)
    {
        return 1;
    }

    $Letters = [];

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    $DivPalindromes = [];
    $CurrentOne = 0;

    $EvenLettersSum = 0;

    foreach ($Letters as $Letter => &$Count)
    {
        if ($Count % 2 == 0)
        {
            $EvenLettersSum += $Count;
            $Count = 0;
        }
        else
        {
            $EvenLettersSum += $Count - 1;
            $Count = 1;
        }
    }

    $OddRemainders = array_sum ($Letters);

    $EvenPairs = $EvenLettersSum / 2;

    $PairsByPalindrome  = floor ($EvenPairs / $k);
    $RemainingEvenPairs = $EvenPairs % $k;

    for ($i = 0; $i < $k; $i++)
    {
        $DivPalindromes [] = 2 * $PairsByPalindrome;
    }

    for ($i = 0; $i < $RemainingEvenPairs; $i++)
    {
        $DivPalindromes [$i] += 2;
    }

    sort ($DivPalindromes);

    $c = count ($DivPalindromes);

    if ($OddRemainders > 0)
    {
        $i = 0;

        do
        {
            $DivPalindromes [$i++]++;
            $OddRemainders--;
        } while ($i < $c && $OddRemainders > 0);
    }

    $DivPalindromes = array_values (
        array_filter ($DivPalindromes)
    );

    $c = count ($DivPalindromes);

    $min = min ($DivPalindromes);

    $i = -1;
    $j = $c;

    while (in_array ($min, $DivPalindromes))
    {
        do
        {
            $j--;

            if ($j <= 0) break 2;
        } while ($DivPalindromes [$j] % 2 != 0);

        do
        {
            $i++;
            if ($i >= $c) break 2;
        } while ($DivPalindromes [$i] % 2 != 0);

        if ($DivPalindromes [$j] - $DivPalindromes [$i] >= 2)
        {
            $DivPalindromes [$i]++;
            $DivPalindromes [$j]--;
        }
    }

    return min ($DivPalindromes);
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = str_replace ([ "\r", "\n" ], "", fgets (STDIN));

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    if (floor ($n / $k) == 1)
    {
        return 1;
    }

    $Letters = [];

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    $DivPalindromes = [];
    $CurrentOne = 0;

    $EvenLettersSum = 0;

    foreach ($Letters as $Letter => &$Count)
    {
        if ($Count % 2 == 0)
        {
            $EvenLettersSum += $Count;
            $Count = 0;
        }
        else
        {
            $EvenLettersSum += $Count - 1;
            $Count = 1;
        }
    }

    $OddRemainders = array_sum ($Letters);

    $EvenPairs = $EvenLettersSum / 2;

    $PairsByPalindrome  = floor ($EvenPairs / $k);
    $RemainingEvenPairs = $EvenPairs % $k;

    for ($i = 0; $i < $k; $i++)
    {
        $DivPalindromes [] = 2 * $PairsByPalindrome;
    }

    for ($i = 0; $i < $RemainingEvenPairs; $i++)
    {
        $DivPalindromes [$i] += 2;
    }

    sort ($DivPalindromes);

    $c = count ($DivPalindromes);

    if ($OddRemainders > 0)
    {
        $i = 0;

        do
        {
            $DivPalindromes [$i++]++;
            $OddRemainders--;
        } while ($i < $c && $OddRemainders > 0);
    }

    $DivPalindromes = array_values (
        array_filter ($DivPalindromes)
    );

    $c = count ($DivPalindromes);

    for ($i = 0; $i < $c - 1; $i++)
    {
        if ($DivPalindromes [$i] % 2 == 0 &&
            $DivPalindromes [$i + 1] % 2 == 0 &&
            $DivPalindromes [$i + 1] - $DivPalindromes [$i] >= 2)
        {
            $DivPalindromes [$i]++;
            $DivPalindromes [$i + 1]--;
        }
    }

    return min ($DivPalindromes);
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = str_replace ([ "\r", "\n" ], "", fgets (STDIN));

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    $Letters = [];

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    $DivPalindromes = [];
    $CurrentOne = 0;

    $EvenLettersSum = 0;

    foreach ($Letters as $Letter => &$Count)
    {
        if ($Count % 2 == 0)
        {
            $EvenLettersSum += $Count;
            $Count = 0;
        }
        else
        {
            $EvenLettersSum += $Count - 1;
            $Count = 1;
        }
    }

    $OddRemainders = array_sum ($Letters);

    $EvenPairs = $EvenLettersSum / 2;

    $PairsByPalindrome  = floor ($EvenPairs / $k);
    $RemainingEvenPairs = $EvenPairs % $k;

    for ($i = 0; $i < $k; $i++)
    {
        $DivPalindromes [] = 2 * $PairsByPalindrome;
    }

    for ($i = 0; $i < $RemainingEvenPairs; $i++)
    {
        $DivPalindromes [$i] += 2;
    }

    sort ($DivPalindromes);

    $c = count ($DivPalindromes);

    if ($OddRemainders > 0)
    {
        $i = 0;

        do
        {
            $DivPalindromes [$i++]++;
            $OddRemainders--;
        } while ($i < $c && $OddRemainders > 0);
    }

    $DivPalindromes = array_values (
        array_filter ($DivPalindromes)
    );

    $c = count ($DivPalindromes);

    for ($i = 0; $i < $c - 1; $i++)
    {
        if ($DivPalindromes [$i] % 2 == 0 &&
            $DivPalindromes [$i + 1] % 2 == 0 &&
            $DivPalindromes [$i + 1] - $DivPalindromes [$i] >= 2)
        {
            $DivPalindromes [$i]++;
            $DivPalindromes [$i + 1]--;
        }
    }

    return min ($DivPalindromes);
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = str_replace ([ "\r", "\n" ], "", fgets (STDIN));

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    $Letters = [];

    $MaxEvenPalindromeLength = 0;

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    foreach ($Letters as $Letter => $Count)
    {
        if ($Count % 2 == 0)
        {
            $MaxEvenPalindromeLength += $Count;
            unset ($Letters [$Letter]);
        }
    }

    $Length2 = $MaxEvenPalindromeLength / $k;

    if ($Length2 < 1)
    {
        return 1;
    }

    if ($Length2 % 2 != 0)
    {
        foreach ($Letters as $Letter => &$Count)
        {
            $Count--;
        }

        unset ($Count);
    }

    return $Length2 + floor (array_sum (array_values ($Letters)) / $k);
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = str_replace ([ "\r", "\n" ], "", fgets (STDIN));

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    $Letters = [];

    $MaxPalindromeLength   = 0;
    $LongestOddLetterCount = 0;
    $OddLettersTotal       = 0;
    $EvenLettersTotal      = 0;

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    foreach ($Letters as $Letter => $Count)
    {
        if ($Count % 2 == 0)
        {
            $EvenLettersTotal++;
            $MaxPalindromeLength += $Count;
        }
        else
        {
            $OddLettersTotal++;

            if ($Count > $LongestOddLetterCount)
            {
                $LongestOddLetterCount = $Count;
            }
        }
    }

    if ($EvenLettersTotal == $OddLettersTotal)
    {
        $MaxPalindromeLength += $OddLettersTotal;
    }
    else
    {
        $MaxPalindromeLength += $LongestOddLetterCount;
    }

    return (($MaxPalindromeLength - $MaxPalindromeLength % $k) / $k)
        ? : 1;
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = fgets (STDIN);

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    $Letters = [];

    $MaxPalindromeLength   = 0;
    $LongestOddLetterCount = 0;
    $OddLettersTotal       = 0;

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    foreach ($Letters as $Letter => $Count)
    {
        if ($Count % 2 == 0)
        {
            $MaxPalindromeLength += $Count;
        }
        else
        {
            $OddLettersTotal++;

            if ($Count > $LongestOddLetterCount)
            {
                $LongestOddLetterCount = $Count;
            }
        }
    }

    if ($n / $k == $OddLettersTotal)
    {
        $MaxPalindromeLength += $OddLettersTotal;
    }
    else
    {
        $MaxPalindromeLength += $LongestOddLetterCount;
    }

    return (($MaxPalindromeLength - $MaxPalindromeLength % $k) / $k)
        ? : 1;
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = fgets (STDIN);

    echo (Task1624D ($str, $n, $k) ? : 1) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    $Letters = [];

    $MaxPalindromeLength   = 0;
    $LongestOddLetterCount = 0;

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    foreach ($Letters as $Letter => $Count)
    {
        if ($Count % 2 == 0)
        {
            $MaxPalindromeLength += $Count;
        }
        else
        {
            if ($Count > $LongestOddLetterCount)
            {
                $LongestOddLetterCount = $Count;
            }
        }
    }

    $MaxPalindromeLength += $LongestOddLetterCount;

    return ($MaxPalindromeLength - $MaxPalindromeLength % $k) / $k;
}

<?php

$t = fgets (STDIN);

for ($i = 0; $i < $t; $i++)
{
    list ($n, $k) = explode (" ",
        str_replace ([ "\r", "\n" ], "", fgets (STDIN))
    );

    $str = fgets (STDIN);

    echo Task1624D ($str, $n, $k) . "\n";
}

function Task1624D (&$str, &$n, &$k)
{
    if ($n == $k) { return 1; }

    $Letters = [];

    $MaxPalindromeLength   = 0;
    $LongestOddLetterCount = 0;

    foreach (str_split ($str) as $Letter)
    {
        @$Letters [$Letter]++;
    }

    foreach ($Letters as $Letter => $Count)
    {
        if ($Count % 2 == 0)
        {
            $MaxPalindromeLength += $Count;
        }
        else
        {
            if ($Count > $LongestOddLetterCount)
            {
                $LongestOddLetterCount = $Count;
            }
        }
    }

    $MaxPalindromeLength += $LongestOddLetterCount;

    return ($MaxPalindromeLength - $MaxPalindromeLength % $k) / $k;
}


Consider a table of size $$$n \times m$$$, initially fully white. Rows are numbered $$$1$$$ through $$$n$$$ from top to bottom, columns $$$1$$$ through $$$m$$$ from left to right. Some square inside the table with odd side length was painted black. Find the center of this square.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 115$$$) — the number of rows and the number of columns in the table. The $$$i$$$-th of the next $$$n$$$ lines contains a string of $$$m$$$ characters $$$s_{i1} s_{i2} \ldots s_{im}$$$ ($$$s_{ij}$$$ is 'W' for white cells and 'B' for black cells), describing the $$$i$$$-th row of the table.

Output two integers $$$r$$$ and $$$c$$$ ($$$1 \le r \le n$$$, $$$1 \le c \le m$$$) separated by a space — the row and column numbers of the center of the black square.


Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets of stickers as she wants, and may specify any string of length n for the sheets, but all the sheets must be identical, so the string is the same for all sheets. Once she attains the sheets of stickers, she will take some of the stickers from the sheets and arrange (in any order) them to form s. Determine the minimum number of sheets she has to buy, and provide a string describing a possible sheet of stickers she should buy.

The first line contains string s (1 ≤ |s| ≤ 1000), consisting of lowercase English characters only. The second line contains an integer n (1 ≤ n ≤ 1000).

On the first line, print the minimum number of sheets Piegirl has to buy. On the second line, print a string consisting of n lower case English characters. This string should describe a sheet of stickers that Piegirl can buy in order to minimize the number of sheets. If Piegirl cannot possibly form the string s, print instead a single line with the number -1.

NoteIn the second example, Piegirl can order 3 sheets of stickers with the characters "nab". She can take characters "nab" from the first sheet, "na" from the second, and "a" from the third, and arrange them to from "banana".

<?php
	// God & me
	// Together :)
	$inf = 1e9;
	$INPUTS = preg_split("/[\s]+/", file_get_contents('php://stdin'));
	function in(){
		global $INPUTS;
		static $i = 0;
		return $INPUTS[$i++];
	}
	$s = in(); $n = in();
	for($i = 0; $i < strlen($s); $i++)
		$cnt[ $s[ $i ] ]++;
	$lo = 0; $hi = $inf;
	while($hi - $lo > 1){
		$mid = floor(($lo + $hi) / 2);
		$used = 0;
		foreach($cnt as $val)
			$used += ceil($val / $mid);
		if($used <= $n)
			$hi = $mid;
		else
			$lo = $mid;
	}
	if($hi == $inf){
		echo -1;  exit();
	}
	echo $hi . PHP_EOL;
	foreach($cnt as $key => $val)
		for($i = 0; $i < ceil($val / $hi); $i++){
			echo $key;  $n--;
		}
	while($n--)
		echo 'z';
?>


Valera is a little boy. Yesterday he got a huge Math hometask at school, so Valera didn't have enough time to properly learn the English alphabet for his English lesson. Unfortunately, the English teacher decided to have a test on alphabet today. At the test Valera got a square piece of squared paper. The length of the side equals n squares (n is an odd number) and each unit square contains some small letter of the English alphabet.Valera needs to know if the letters written on the square piece of paper form letter "X". Valera's teacher thinks that the letters on the piece of paper form an "X", if:  on both diagonals of the square paper all letters are the same;  all other squares of the paper (they are not on the diagonals) contain the same letter that is different from the letters on the diagonals. Help Valera, write the program that completes the described task for him.

The first line contains integer n (3 ≤ n < 300; n is odd). Each of the next n lines contains n small English letters — the description of Valera's paper.

Print string "YES", if the letters on the paper form letter "X". Otherwise, print string "NO". Print the strings without quotes.

<?php
$a = trim(fgets(STDIN));
$b = array();
$c = array();
for($x = 0; $x < $a; $x++)
{
    $d = str_split(trim(fgets(STDIN)));
    for($y = 0; $y < $a; $y++)
    {
        if(($y != $x) && ($y != $a - $x - 1))
        {
            array_push($b, $d[$y]);
        }
        else
        {
            array_push($c, $d[$y]);
        }
    }
}
$e = array_unique($b);
sort($e);
$f = array_unique($c);
sort($f);
if((count($e) == 1) && (count($f) == 1) && ($e[0] != $f[0]))
{
    print "YES";
}
else
{
    print "NO";
}
?>

<?php
define('LOCAL_ENV', false);
if (LOCAL_ENV) {
    error_reporting(E_ALL & !E_NOTICE);
    $test = <<<INPUT
3
xpx
pxp
xpe
INPUT;
    $stdin = fopen('php://temp/in', 'rw');
    fwrite($stdin, $test);
    rewind($stdin);
} else {
    error_reporting(0);
    $stdin = STDIN;
}
define('MY_STDIN', $stdin);

$n = (int) trim(fgets(MY_STDIN));
$d = ''; $x = '';
$res = true;
for ($i = 0; $i < $n; $i++) {
    $s = trim(fgets(MY_STDIN));
    if (empty($x)) {
        $x = $s{0}; $d = $s{1};
        if ($x == $d) {
            $res = false;
            break;
        }
    }
    for ($j = 0; $j < $n; $j++) {
        if (($i == $j) || ($i == $n-$j-1)) {
            if ($s{$j} != $x) {
                $res = false;
                break 2;
            }
        } else {
            if ($s{$j} != $d) {
                $res = false;
                break 2;
            }
        }
    }
}
echo $res ? "YES" : "NO";

#!/usr/bin/env php
<?php
function createLine ($x, $y, $count, $i) {
	$half = floor($count / 2);
	$string =
		str_repeat($y, ($i < $half) ? $i : ($count - $i - 1)) .
		str_repeat($x, ($i == $half) ? 0 : 1) .
		str_repeat($y, ($i < $half) ? ($half - $i - 1) : 0) .
		str_repeat($y, ($i > $half) ? ($i - $half - 1) : 0);
	$string .= str_repeat(($i == $half) ? $x : $y, 1) . strrev($string);
	return $string;
}
$count = trim(fgets(STDIN));

$line = trim(fgets(STDIN));
$x = $line[0];
$y = $line[1];
if ($x === $y) {
	die('NO');
}
if ($line !== createLine($x, $y, $count, 0)) {
	die('NO');
}
for ($i = 1, $il = $count; $i < $il; $i++) {
	$line = trim(fgets(STDIN));
	if ($line !== createLine($x, $y, $count, $i)) {
		die('NO');
	}
}

die('YES');

<?php
define('LOCAL_ENV', false);
if (LOCAL_ENV) {
    error_reporting(E_ALL & !E_NOTICE);
    $test = <<<INPUT
3
xpx
pxp
xpe
INPUT;
    $stdin = fopen('php://temp/in', 'rw');
    fwrite($stdin, $test);
    rewind($stdin);
} else {
    error_reporting(0);
    $stdin = STDIN;
}
define('MY_STDIN', $stdin);

$n = (int) trim(fgets(MY_STDIN));
$d = ''; $x = '';
$res = true;
for ($i = 0; $i < $n; $i++) {
    $s = trim(fgets(MY_STDIN));
    if (empty($x)) {
        $x = $s{0}; $d = $s{1};
    }
    for ($j = 0; $j < $n; $j++) {
        if (($i == $j) || ($i == $n-$j-1)) {
            if ($s{$j} != $x) {
                $res = false;
                break 2;
            }
        } else {
            if ($s{$j} != $d) {
                $res = false;
                break 2;
            }
        }
    }
}
echo $res ? "YES" : "NO";

<?php
define('LOCAL_ENV', false);
if (LOCAL_ENV) {
    error_reporting(E_ALL & !E_NOTICE);
    $test = <<<INPUT
3
xpx
pxp
xpe
INPUT;
    $stdin = fopen('php://temp/in', 'rw');
    fwrite($stdin, $test);
    rewind($stdin);
} else {
    error_reporting(0);
    $stdin = STDIN;
}
define('MY_STDIN', $stdin);

$n = (int) trim(fgets(MY_STDIN));
$d = ''; $x = '';
$res = true;
for ($i = 0; $i < $n; $i++) {
    $s = trim(fgets(MY_STDIN));
    if (empty($x)) {
        $x = $s{0}; $d = $s{1};
        if ($x != $d) {
            $res = false;
            break;
        }
    }
    for ($j = 0; $j < $n; $j++) {
        if (($i == $j) || ($i == $n-$j-1)) {
            if ($s{$j} != $x) {
                $res = false;
                break 2;
            }
        } else {
            if ($s{$j} != $d) {
                $res = false;
                break 2;
            }
        }
    }
}
echo $res ? "YES" : "NO";

#!/usr/bin/env php
<?php
function createLine ($x, $y, $count, $i) {
	$half = floor($count / 2);
	$string =
		str_repeat($y, ($i < $half) ? $i : ($count - $i - 1)) .
		str_repeat($x, ($i == $half) ? 0 : 1) .
		str_repeat($y, ($i < $half) ? ($half - $i - 1) : 0) .
		str_repeat($y, ($i > $half) ? ($i - $half - 1) : 0);
	$string .= str_repeat(($i == $half) ? $x : $y, 1) . strrev($string);
	return $string;
}
$count = trim(fgets(STDIN));

$line = trim(fgets(STDIN));
$x = $line[0];
$y = $line[1];
if ($line !== createLine($x, $y, $count, 0)) {
	die('NO');
}
for ($i = 1, $il = $count; $i < $il; $i++) {
	$line = trim(fgets(STDIN));
	if ($line !== createLine($x, $y, $count, $i)) {
		die('NO');
	}
}

die('YES');


Sakuzyo - ImprintingA.R.C. Markland-N is a tall building with $$$n$$$ floors numbered from $$$1$$$ to $$$n$$$. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor $$$s$$$ of the building. On each floor (including floor $$$s$$$, of course), there is a restaurant offering meals. However, due to renovations being in progress, $$$k$$$ of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then the descriptions of $$$t$$$ test cases follow. The first line of a test case contains three integers $$$n$$$, $$$s$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le s \le n$$$, $$$1 \le k \le \min(n-1, 1000)$$$) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants. The second line of a test case contains $$$k$$$ distinct integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — the floor numbers of the currently closed restaurants. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$1000$$$.

For each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor $$$s$$$ to a floor with an open restaurant.

NoteIn the first example test case, the nearest floor with an open restaurant would be the floor $$$4$$$.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the $$$6$$$-th floor.


You have a garland consisting of $$$n$$$ lamps. Each lamp is colored red, green or blue. The color of the $$$i$$$-th lamp is $$$s_i$$$ ('R', 'G' and 'B' — colors of lamps in the garland).You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garland is nice.A garland is called nice if any two lamps of the same color have distance divisible by three between them. I.e. if the obtained garland is $$$t$$$, then for each $$$i, j$$$ such that $$$t_i = t_j$$$ should be satisfied $$$|i-j|~ mod~ 3 = 0$$$. The value $$$|x|$$$ means absolute value of $$$x$$$, the operation $$$x~ mod~ y$$$ means remainder of $$$x$$$ when divided by $$$y$$$.For example, the following garlands are nice: "RGBRGBRG", "GB", "R", "GRBGRBG", "BRGBRGB". The following garlands are not nice: "RR", "RGBG".Among all ways to recolor the initial garland to make it nice you have to choose one with the minimum number of recolored lamps. If there are multiple optimal solutions, print any of them.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of lamps. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ characters 'R', 'G' and 'B' — colors of lamps in the garland.

In the first line of the output print one integer $$$r$$$ — the minimum number of recolors needed to obtain a nice garland from the given one. In the second line of the output print one string $$$t$$$ of length $$$n$$$ — a nice garland obtained from the initial one with minimum number of recolors. If there are multiple optimal solutions, print any of them.

<?php
	fscanf(STDIN, "%d", $n);
	fscanf(STDIN, "%s", $s);
	$l = strlen($s);

	$mdiff = -1;
	$mrs = "";
	$comb = array("RGB", "RBG", "GRB", "GBR", "BRG", "BGR");
	for($z=0; $z<6; $z++) {
		$diff = 0;
		$rgb = $comb[$z];
		$rs = $s;
		for($i=0; $i<$l; $i++) {
			$c = $rgb[$i%3];
			if($s[$i]!=$c) $diff++;
			$rs[$i] = $c;
		}
		if($mdiff==-1 || $diff<$mdiff) {
			$mdiff = $diff;
			$mrs = $rs;
		}
	}
	echo "$mdiff\n";
	echo "$mrs";
?>

<?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();
$s = $ir->readString();

$a = [
	'RGB' => ['R', 'G', 'B', 0],
	'GBR' => ['G', 'B', 'R', 0],
	'BRG' => ['B', 'R', 'G', 0],

	'RBG' => ['R', 'B', 'G', 0],
	'BGR' => ['B', 'G', 'R', 0],
	'GRB' => ['G', 'R', 'B', 0],
];

for ($i = 0; $i<$n; $i++) {
	$j = $i%3;
	foreach ($a as &$aa) {
		if ($aa[$j] != $s[$i]) {
			$aa[3] += 1;
		}
	}
	unset($aa);
}

$min = $a['RGB'][3];
$seq = 'RGB';
foreach ($a as $k=>$aa) {
	if ($aa[3] < $min) {
		$min = $aa[3];
		$seq = $k;
	}
}

$s = str_repeat($seq, intval($n/3)+1);
$s = substr($s, 0, $n);
echo $min."\n";
echo $s;

<?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();
$s = $ir->readString();

$a = [
	'RGB' => ['R', 'G', 'B', 0],
	'GBR' => ['G', 'B', 'R', 0],
	'BRG' => ['B', 'R', 'G', 0],

	'RBG' => ['R', 'B', 'G', 0],
	'BGR' => ['B', 'G', 'R', 0],
	'GRB' => ['G', 'R', 'B', 0],
];

for ($i = 0; $i<$n; $i++) {
	$j = $i%3;
	foreach ($a as &$aa) {
		if ($aa[$j] != $s[$i]) {
			$aa[3] += 1;
		}
	}
}

$min = 1e6;
$seq = '';
foreach ($a as $k=>$aa) {
	if ($aa[3] < $min) {
		$min = $aa[3];
		$seq = $k;
	}
}

$s = str_repeat($seq, intval($n/3)+1);
$s = substr($s, 0, $n);
echo $min."\n";
echo $s;


You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.

The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n. The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.   In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.  In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.  In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.

Output the answer with absolute or relative error no more than 1e - 9.

NoteConsider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability , the interval will consist of a single element and the permutation will not be altered. With probability  we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability  the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to .

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

$ranges = array();
for ($l = 0; $l < $n; $l++) {
  for ($r = $l; $r < $n; $r++) {
    $ranges[] = array($l, $r - $l + 1);
  }
}

$max1 = count($ranges);
$max2 = $k >= 2 ? $max1 : 1;
$max3 = $k >= 3 ? $max1 : 1;
$max4 = $k >= 4 ? $max1 : 1;

$sum = 0;

for ($rng1 = 0; $rng1 < $max1; $rng1++) {
  $np1 = substr_replace($p, strrev(substr($p, $ranges[$rng1][0], $ranges[$rng1][1])), $ranges[$rng1][0], $ranges[$rng1][1]);
  for ($rng2 = 0; $rng2 < $max2; $rng2++) {
    $np2 = substr_replace($np1, strrev(substr($np1, $ranges[$rng2][0], $ranges[$rng2][1])), $ranges[$rng2][0], $ranges[$rng2][1]);
    for ($rng3 = 0; $rng3 < $max3; $rng3++) {
      $np3 = substr_replace($np2, strrev(substr($np2, $ranges[$rng3][0], $ranges[$rng3][1])), $ranges[$rng3][0], $ranges[$rng3][1]);
      for ($rng4 = 0; $rng4 < $max4; $rng4++) {
        $np4 = substr_replace($np3, strrev(substr($np3, $ranges[$rng4][0], $ranges[$rng4][1])), $ranges[$rng4][0], $ranges[$rng4][1]);
        for ($i = 0; $i < $n; $i++) {
          for ($j = $i + 1; $j < $n; $j++) {
            if ($np4[$j] < $np4[$i]) {
              $sum++;
            }
          }
        }
      }
    }
  }
}

printf("%.10f", $sum / pow($max1, $k));

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

$ranges = array();
for ($l = 0; $l < $n; $l++) {
  for ($r = $l; $r < $n; $r++) {
    $ranges[] = array($l, $r - $l + 1);
  }
}

$max1 = count($ranges);
$max2 = $k >= 2 ? $max1 : 1;
$max3 = $k >= 3 ? $max1 : 1;
$max4 = $k >= 4 ? $max1 : 1;

$sum = 0;

for ($rng1 = 0; $rng1 < $max1; $rng1++) {
  $np1 = $p;
  array_splice($np1, $ranges[$rng1][0], $ranges[$rng1][1], array_reverse(array_slice($np1, $ranges[$rng1][0], $ranges[$rng1][1])));
  for ($rng2 = 0; $rng2 < $max2; $rng2++) {
    $np2 = $np1;
    array_splice($np2, $ranges[$rng2][0], $ranges[$rng2][1], array_reverse(array_slice($np2, $ranges[$rng2][0], $ranges[$rng2][1])));
    for ($rng3 = 0; $rng3 < $max3; $rng3++) {
      $np3 = $np2;
      array_splice($np3, $ranges[$rng3][0], $ranges[$rng3][1], array_reverse(array_slice($np3, $ranges[$rng3][0], $ranges[$rng3][1])));
      for ($rng4 = 0; $rng4 < $max4; $rng4++) {
        $np4 = $np3;
        array_splice($np4, $ranges[$rng4][0], $ranges[$rng4][1], array_reverse(array_slice($np4, $ranges[$rng4][0], $ranges[$rng4][1])));
        for ($i = 0; $i < $n; $i++) {
          for ($j = $i + 1; $j < $n; $j++) {
            if ($np4[$j] < $np4[$i]) {
              $sum++;
            }
          }
        }
      }
    }
  }
}

printf("%.10f", $sum / pow($max1, $k));


Phoenix has collected $$$n$$$ pieces of gold, and he wants to weigh them together so he can feel rich. The $$$i$$$-th piece of gold has weight $$$w_i$$$. All weights are distinct. He will put his $$$n$$$ pieces of gold on a weight scale, one piece at a time. The scale has an unusual defect: if the total weight on it is exactly $$$x$$$, it will explode. Can he put all $$$n$$$ gold pieces onto the scale in some order, without the scale exploding during the process? If so, help him find some possible order. Formally, rearrange the array $$$w$$$ so that for each $$$i$$$ $$$(1 \le i \le n)$$$, $$$\sum\limits_{j = 1}^{i}w_j \ne x$$$.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$; $$$1 \le x \le 10^4$$$) — the number of gold pieces that Phoenix has and the weight to avoid, respectively.  The second line of each test case contains $$$n$$$ space-separated integers $$$(1 \le w_i \le 100)$$$ — the weights of the gold pieces. It is guaranteed that the weights are pairwise distinct.

For each test case, if Phoenix cannot place all $$$n$$$ pieces without the scale exploding, print NO. Otherwise, print YES followed by the rearranged array $$$w$$$. If there are multiple solutions, print any.

NoteIn the first test case, Phoenix puts the gold piece with weight $$$3$$$ on the scale first, then the piece with weight $$$2$$$, and finally the piece with weight $$$1$$$. The total weight on the scale is $$$3$$$, then $$$5$$$, then $$$6$$$. The scale does not explode because the total weight on the scale is never $$$2$$$.In the second test case, the total weight on the scale is $$$8$$$, $$$9$$$, $$$11$$$, $$$14$$$, then $$$18$$$. It is never $$$3$$$.In the third test case, Phoenix must put the gold piece with weight $$$5$$$ on the scale, and the scale will always explode.

<?php

/*
 * http://codeforces.com/contest/1515
 */

// $file = fopen("./input.txt", "r");
$file = fopen("php://stdin", "r");

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

for ($i=0; $i<$rowsNumber; $i++) {
    list($n, $x) = explode(" ", trim(fgets($file)));
    $pieces      = explode(" ", trim(fgets($file)));

    $n = (int) $n;
    $x = (int) $x;

    if (array_sum($pieces) < $x) {
        echo "YES" . PHP_EOL;
        echo implode(" ", $pieces);
        echo PHP_EOL;

        continue;
    }

    if (array_sum($pieces) === $x) {
        echo "NO" . PHP_EOL;

        continue;
    }

    $sum = 0;
    for ($j=0; $j<count($pieces)-1; $j++) {
        $sum += $pieces[$j];

        if ($sum === $x) {
            $buffer       = $pieces[$j];
            $pieces[$j]   = $pieces[$j+1];
            $pieces[$j+1] = $buffer;
        }
    }

    echo "YES" . PHP_EOL;
    echo implode(" ", $pieces);
    echo PHP_EOL;
}

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

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

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

  rsort($a);
  $sum = array_sum($a);

  if ($sum == $x) { echo 'NO'.PHP_EOL; }

  if ($sum < $x) {
    echo 'YES'.PHP_EOL;
    for ($j = 0; $j < $n; $j++) {
      echo $a[$j].' ';
    }
    echo PHP_EOL;
  }

  if ($sum > $x) {
    $m = 0;
    for ($j = 0; $j < $n; $j++) { $m += $a[$j]; $r[$j] = $m; }

    $c = array_search($x, $r);
    if ($c === false) {
      $f = 1;
    } else {
      $d = $n + 1;
      while ($d--) {
        $m = $a[$n - 1];
        unset($a[$n - 1]);
        array_unshift($a, $m);

        $r = array();
        $m = 0;

        for ($j = 0; $j < $n; $j++) { $m += $a[$j]; $r[$j] = $m; }

        $c = array_search($x, $r);
        if ($c === false) { $f = 1; break; }
        $g++;
      }
    }

    if ($f == 1) {
      echo 'YES'.PHP_EOL;
      for ($j = 0; $j < $n; $j++) { echo $a[$j].' '; }
      echo PHP_EOL;
    } else { echo 'NO'.PHP_EOL; }
}

}

?>

<?php

/*
 * http://codeforces.com/contest/1515
 */

// $file = fopen("./input.txt", "r");
$file = fopen("php://stdin", "r");

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

for ($i=0; $i<$rowsNumber; $i++) {
    list($n, $x) = explode(" ", trim(fgets($file)));
    $pieces      = explode(" ", trim(fgets($file)));

    $n = (int) $n;
    $x = (int) $x;

    if (array_sum($pieces) < $x) {
        echo "YES" . PHP_EOL;
        echo implode(" ", $pieces);
        echo PHP_EOL;

        return;
    }

    if (array_sum($pieces) === $x) {
        echo "NO" . PHP_EOL;

        return;
    }

    $sum = 0;
    for ($j=0; $j<count($pieces)-1; $j++) {
        $sum += $pieces[$j];

        if ($sum === $x) {
            $buffer       = $pieces[$j];
            $pieces[$j]   = $pieces[$j+1];
            $pieces[$j+1] = $buffer;
        }
    }

    echo "YES" . PHP_EOL;
    echo implode(" ", $pieces);
    echo PHP_EOL;
}