Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example:   the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds;  the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array;  the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \ne 1$$$;  the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \ne 1$$$;  the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \le s \le 5000$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

NoteConsider the example test:  in the first test case, the array $$$[1]$$$ meets all conditions;  in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions;  in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions;  in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions.

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

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

for ($i = 0; $i < $n; $i++) {
  $s = trim(fgets($file));

  $ans = ceil(sqrt($s));

  echo $ans.PHP_EOL;
}

?>

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

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

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

}

//$iQueryCount = 1;
$iQueryCount = IO::str();
while($iQueryCount > 0) {
    $iQueryCount--;
    solve();
}
function solve() {
    $j = IO::str();
    $sum = 0;
    $count = 0;
    $n = 1;
    while ($sum < $j) {
        $count++;
        $sum = $sum + $n;
        $n += 2;
    }
    IO::line($count);
}

?>


Polycarpus adores TV series. Right now he is ready to finish watching a season of a popular sitcom "Graph Theory". In total, the season has n episodes, numbered with integers from 1 to n.Polycarpus watches episodes not one by one but in a random order. He has already watched all the episodes except for one. Which episode has Polycaprus forgotten to watch?

The first line of the input contains integer n (2 ≤ n ≤ 100000) — the number of episodes in a season. Assume that the episodes are numbered by integers from 1 to n. The second line contains n - 1 integer a1, a2, ..., an (1 ≤ ai ≤ n) — the numbers of episodes that Polycarpus has watched. All values of ai are distinct.

Print the number of the episode that Polycarpus hasn't watched.

<?php
$a = trim(fgets(STDIN));
$b = explode(" ", trim(fgets(STDIN)));
$c = range(1, $a);
$d = array_diff($c, $b);
print implode("", $d);
?>

<?php
$fh = fopen('php://stdin', 'r');
$input = '';
while ($line = fgets($fh)){
  $input .= $line;
}

list($series_count, $view_series) = explode(PHP_EOL, $input);
$view_series_array = explode(' ', $view_series);

$summ = $series_count * ($series_count + 1) / 2;

foreach ($view_series_array as $num) {
    $summ -= $num;
}

echo $summ;

<?php
$f = fopen ("php://stdin", 'r' ) ;
$lines = file("php://stdin");
function parseint($n){
    return(intval($n));
}
$epson_num = $lines[0];
$epson_watched = array_map("parseint", explode(" ",(strval($lines[1]))));
$epson_lost = (($epson_num * ($epson_num + 1))/2) - array_sum ($epson_watched);

print $epson_lost ;
?>

<?php
$handle = fopen ("php://stdin","r");
$n = fgets($handle);
$result=0;
$tmp=0;
$tmp=fgets($handle);
$tmp=explode(" ",$tmp);
for($i=1;$i<$n+1;$i++)
{
$result+=$tmp[$i-1];
}

echo ($n*($n + 1) / 2) - $result;
?>

<?php
$f = fopen ("php://stdin.txt", 'r' ) ;
$lines = file("php://stdin.txt");
function parseint($n){
    return(intval($n));
}
$epson_num = $lines[0];
$epson_watched = array_map("parseint", explode(" ",(strval($lines[1]))));
$epson_lost = (($epson_num * ($epson_num + 1))/2) - array_sum ($epson_watched);

print $epson_lost ;

?>


Facetook is a well known social network website, and it will launch a new feature called Facetook Priority Wall. This feature will sort all posts from your friends according to the priority factor (it will be described).This priority factor will be affected by three types of actions:   1. "X posted on Y's wall" (15 points),  2. "X commented on Y's post" (10 points),  3. "X likes Y's post" (5 points). X and Y will be two distinct names. And each action will increase the priority factor between X and Y (and vice versa) by the above value of points (the priority factor between X and Y is the same as the priority factor between Y and X).You will be given n actions with the above format (without the action number and the number of points), and you have to print all the distinct names in these actions sorted according to the priority factor with you.

The first line contains your name. The second line contains an integer n, which is the number of actions (1 ≤ n ≤ 100). Then n lines follow, it is guaranteed that each one contains exactly 1 action in the format given above. There is exactly one space between each two words in a line, and there are no extra spaces. All the letters are lowercase. All names in the input will consist of at least 1 letter and at most 10 small Latin letters.

Print m lines, where m is the number of distinct names in the input (excluding yourself). Each line should contain just 1 name. The names should be sorted according to the priority factor with you in the descending order (the highest priority factor should come first). If two or more names have the same priority factor, print them in the alphabetical (lexicographical) order. Note, that you should output all the names that are present in the input data (excluding yourself), even if that person has a zero priority factor. The lexicographical comparison is performed by the standard "<" operator in modern programming languages. The line a is lexicographically smaller than the line b, if either a is the prefix of b, or if exists such an i (1 ≤ i ≤ min(|a|, |b|)), that ai < bi, and for any j (1 ≤ j < i) aj = bj, where |a| and |b| stand for the lengths of strings a and b correspondently.

ahmed
3
ahmed posted on fatma's wall
fatma commented on ahmed's post
mona likes ahmed's post

<?php
    //$in = fopen("input.in", "r");
    $in = fopen("php://stdin", "r");
    $name = trim(fgets($in));
    $n = trim(fgets($in));
    for($i = 0; $i < $n; $i++)
    {
        $tokens = split(" ", fgets($in));
        $point = 0;
        $a = "";
        if($tokens[1] == "posted")
        {
            $point = 15;
            list($a, $tmp) = split("'", $tokens[3]);
        }
        else if ($tokens[1] == "commented")
        {
            $point = 10;
            list($a, $tmp) = split("'", $tokens[3]);
        }
        else
        {
            $point = 5;
            list($a, $tmp) = split("'", $tokens[2]);
        }
        if(!($tokens[0] == $name || $a == $name)) $point = 0;
        $map[$tokens[0]] += $point;
        $map[$a] += $point;
    }
    unset($map[$name]);
    foreach($map as $key => $value) $arr[] = array($key, $value);
    function my_cmp($a, $b)
    {
        if($a[1]!= $b[1]) return $a[1] > $b[1] ? -1 : 1;
        return $a[0] < $b[0] ? -1 : 1;
    }
    usort($arr, "my_cmp");

    foreach($arr as $val) echo $val[0] . "\n";
    fclose($in);
?>

<?php
$iam = trim(fgets(STDIN));
$n = trim(fgets(STDIN));
$friends = array();
for($i=0; $i<$n; $i++)
{
	$str = trim(fgets(STDIN));

	preg_match("!(\w{1,10}) posted on (\w{1,10})'s wall!", $str, $matches);
	if(!empty($matches))
	{
		if($matches[1]==$iam)
		{
			if(!isset($friends[$matches[2]]))
				$friends[$matches[2]] = 15;
			else
				$friends[$matches[2]] += 15;
		}
		elseif($matches[2]==$iam)
		{
			if(!isset($friends[$matches[1]]))
				$friends[$matches[1]] = 15;
			else
				$friends[$matches[1]] += 15;
		}
		else
		{
			if(!isset($friends[$matches[1]]))
				$friends[$matches[1]] = 0;
			if(!isset($friends[$matches[2]]))
				$friends[$matches[2]] = 0;
		}
	}
	else
	{
		preg_match("!(\w{1,10}) commented on (\w{1,10})'s post!", $str, $matches);
		if(!empty($matches))
		{
			if($matches[1]==$iam)
			{
				if(!isset($friends[$matches[2]]))
					$friends[$matches[2]] = 10;
				else
					$friends[$matches[2]] += 10;
			}
			elseif($matches[2]==$iam)
			{
				if(!isset($friends[$matches[1]]))
					$friends[$matches[1]] = 10;
				else
					$friends[$matches[1]] += 10;
			}
			else
			{
				if(!isset($friends[$matches[1]]))
					$friends[$matches[1]] = 0;
				if(!isset($friends[$matches[2]]))
					$friends[$matches[2]] = 0;
			}
		}
		else
		{
			preg_match("!(\w{1,10}) likes (\w{1,10})'s post!", $str, $matches);
			if(!empty($matches))
			{
				if($matches[1]==$iam)
				{
					if(!isset($friends[$matches[2]]))
						$friends[$matches[2]] = 5;
					else
						$friends[$matches[2]] += 5;
				}
				elseif($matches[2]==$iam)
				{
					if(!isset($friends[$matches[1]]))
						$friends[$matches[1]] = 5;
					else
						$friends[$matches[1]] += 5;
				}
				else
				{
					if(!isset($friends[$matches[1]]))
						$friends[$matches[1]] = 0;
					if(!isset($friends[$matches[2]]))
						$friends[$matches[2]] = 0;
				}
			}
		}
	}
}

arsort($friends);

function prr($arr)
{
	sort($arr);
	foreach($arr as $value)
		print $value."\n";
}

for($i=15000;$i>=0; $i-=5)
{
	$temp = array();
	foreach($friends as $key=>$value)
	{
		if($value == $i)
			$temp[] = $key;
	}
	prr($temp);
}

?>

<?
$name=trim(fgets(STDIN));
$n=trim(fgets(STDIN));
for($i=0;$i<$n;$i++)
    $arr[]=trim(fgets(STDIN));
$privs=array('posted on','commented on','likes');
foreach($arr as $val){
    preg_match('/(.*?) (posted on|commented on|likes) (.*?)(\'s)/',$val,$m);
//  print_r ($m);
    if($m[2]=='posted on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=15; $newarr[$m[1]]+=15;}
    if($m[2]=='commented on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=10; $newarr[$m[1]]+=10;}
    if($m[2]=='likes' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=5; $newarr[$m[1]]+=5;}
    if($m[1]!=$name && $m[3]!=$name) {$newarr[$m[1]]+=0; $newarr[$m[3]]+=0;}
}
unset($newarr[$name]);
ksort($newarr);
foreach($newarr as $key=>$val){
     $new2[]=array($key,$val);
}
function cmp($a,$b) {
    if ($a[1]==$b[1])
return $a[0]>$b[0];
    else return $a[1]<$b[1];
}
usort($new2,'cmp');
//print_r($newarr);
foreach($new2 as $val){
    echo $val[0]."\n";
}
//print_r($new2);

?>

<?php
// $input = fopen('input','r');
$name = trim(fgets(STDIN));
$nr = trim(fgets(STDIN));
$assoc = [];

for ($i = 0; $i < $nr; $i++) {
    $action[] = trim(fgets(STDIN));
    $action[$i] = explode(' ', $action[$i]);

    if ($action[$i][1] == 'posted') {
        $name = substr($action[$i][3],0,-2);
        @$assoc[$name] += 15;
    } elseif ($action[$i][1] == 'commented') {
        $name = $action[$i][0];
        @$assoc[$name] += 10;
    } elseif ($action[$i][1] == 'likes') {
        $name = $action[$i][0];
        @$assoc[$name] += 5;
    }
}

ksort($assoc);
foreach($assoc as $x => $x_value) {
    echo  $x . "</br>";
  }

<?php
//$input = fopen('input','r');
$name = trim(fgets(STDIN));
$nr = trim(fgets(STDIN));
$assoc = [];

for ($i = 0; $i < $nr; $i++) {
    $action[] = trim(fgets(STDIN));
    $action[$i] = explode(' ', $action[$i]);

    if ($action[$i][1] == 'posted') {
        $name = substr($action[$i][3],0,-2);
        @$assoc[$name] += 15;
    } elseif ($action[$i][1] == 'commented') {
        $name = $action[$i][0];
        @$assoc[$name] += 10;
    } elseif ($action[$i][1] == 'likes') {
        $name = $action[$i][0];
        @$assoc[$name] += 5;
    }
}

ksort($assoc);
foreach($assoc as $x => $x_value) {
    echo  $x . "</br>";
  }

<?php
$input = fopen('input','r');
$name = trim(fgets($input));
$nr = trim(fgets($input));
$assoc = [];

for ($i = 0; $i < $nr; $i++) {
    $action[] = trim(fgets($input));
    $action[$i] = explode(' ', $action[$i]);

    if ($action[$i][1] == 'posted') {
        $name = substr($action[$i][3],0,-2);
        @$assoc[$name] += 15;
    } elseif ($action[$i][1] == 'commented') {
        $name = $action[$i][0];
        @$assoc[$name] += 10;
    } elseif ($action[$i][1] == 'likes') {
        $name = $action[$i][0];
        @$assoc[$name] += 5;
    }
}

ksort($assoc);
foreach($assoc as $x => $x_value) {
    echo  $x . "</br>";
  }

<?php
$iam = trim(fgets(STDIN));
$n = trim(fgets(STDIN));
$friends = array();
for($i=0; $i<$n; $i++)
{
	$str = trim(fgets(STDIN));

	preg_match("!(\w{1,10}) posted on (\w{1,10})'s wall!", $str, $matches);
	if(!empty($matches))
	{
		if($matches[1]==$iam)
		{
			if(!isset($friends[$matches[2]]))
				$friends[$matches[2]] = 15;
			else
				$friends[$matches[2]] += 15;
		}
		elseif($matches[2]==$iam)
		{
			if(!isset($friends[$matches[1]]))
				$friends[$matches[1]] = 15;
			else
				$friends[$matches[1]] += 15;
		}
		else
		{
			if(!isset($friends[$matches[1]]))
				$friends[$matches[1]] = 0;
			if(!isset($friends[$matches[2]]))
				$friends[$matches[2]] = 0;
		}
	}
	else
	{
		preg_match("!(\w{1,10}) commented on (\w{1,10})'s post!", $str, $matches);
		if(!empty($matches))
		{
			if($matches[1]==$iam)
			{
				if(!isset($friends[$matches[2]]))
					$friends[$matches[2]] = 10;
				else
					$friends[$matches[2]] += 10;
			}
			elseif($matches[2]==$iam)
			{
				if(!isset($friends[$matches[1]]))
					$friends[$matches[1]] = 10;
				else
					$friends[$matches[1]] += 10;
			}
			else
			{
				if(!isset($friends[$matches[1]]))
					$friends[$matches[1]] = 0;
				if(!isset($friends[$matches[2]]))
					$friends[$matches[2]] = 0;
			}
		}
		else
		{
			preg_match("!(\w{1,10}) likes (\w{1,10})'s post!", $str, $matches);
			if(!empty($matches))
			{
				if($matches[1]==$iam)
				{
					if(!isset($friends[$matches[2]]))
						$friends[$matches[2]] = 5;
					else
						$friends[$matches[2]] += 5;
				}
				elseif($matches[2]==$iam)
				{
					if(!isset($friends[$matches[1]]))
						$friends[$matches[1]] = 5;
					else
						$friends[$matches[1]] += 5;
				}
				else
				{
					if(!isset($friends[$matches[1]]))
						$friends[$matches[1]] = 0;
					if(!isset($friends[$matches[2]]))
						$friends[$matches[2]] = 0;
				}
			}
		}
	}
}

arsort($friends);

function prr($arr)
{
	sort($arr);
	foreach($arr as $value)
		print $value."\n";
}

for($i=0;$i<=15000; $i+=5)
{
	$temp = array();
	foreach($friends as $key=>$value)
	{
		if($value == $i)
			$temp[] = $key;
	}
	prr($temp);
}

?>

<?
$fopen=fopen('input.txt','r');
define(STDIN,$fopen);
/*
http://codeforces.ru/problemset/problem/59/B
$n=trim(fgets(STDIN));
$arr=explode(' ',trim(fgets(STDIN)));
for($i=0;$i<$n;$i++)
    $arr[]=trim(fgets(STDIN));
*/
?>
<?
$name=trim(fgets(STDIN));
$n=trim(fgets(STDIN));
for($i=0;$i<$n;$i++)
    $arr[]=trim(fgets(STDIN));
$privs=array('posted on','commented on','likes');
foreach($arr as $val){
    preg_match('/(.*?) (posted on|commented on|likes) (.*?)(\'s)/',$val,$m);
//  print_r ($m);
    if($m[2]=='posted on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=15; $newarr[$m[1]]+=0;}
    if($m[2]=='commented on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=10; $newarr[$m[1]]+=0;}
    if($m[2]=='likes' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=5; $newarr[$m[1]]+=0;}
    if($m[1]!=$name && $m[3]!=$name) {$newarr[$m[1]]+=0; $newarr[$m[3]]+=0;}
}
unset($newarr[$name]);
ksort($newarr);
foreach($newarr as $key=>$val){
     $new2[]=array($key,$val);
}
function cmp($a,$b) {
    if ($a[1]==$b[1])
    return $a[0]<$b[0];
    else return $a[1]>$b[1];
}
usort($new2,'cmp');
//print_r($newarr);
foreach($new2 as $val){
    echo $val[0]."\n";
}
//print_r($new2);

?>

<?
$name=trim(fgets(STDIN));
$n=trim(fgets(STDIN));
for($i=0;$i<$n;$i++)
    $arr[]=trim(fgets(STDIN));
$privs=array('posted on','commented on','likes');
foreach($arr as $val){
    preg_match('/(.*?) (posted on|commented on|likes) (.*?)(\'s)/',$val,$m);
//  print_r ($m);
    if($m[2]=='posted on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=15; $newarr[$m[1]]+=0;}
    if($m[2]=='commented on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=10; $newarr[$m[1]]+=0;}
    if($m[2]=='likes' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=5; $newarr[$m[1]]+=0;}
    if($m[1]!=$name && $m[3]!=$name) {$newarr[$m[1]]+=0; $newarr[$m[3]]+=0;}
}
unset($newarr[$name]);
ksort($newarr);
foreach($newarr as $key=>$val){
     $new2[]=array($key,$val);
}
function cmp($a,$b) {
    if ($a[0]==$b[0])
    return $a[1]<$b[1];
    else return $a[0]>$b[0];
}
usort($new2,'cmp');
//print_r($newarr);
foreach($new2 as $val){
    echo $val[0]."\n";
}
//print_r($new2);

?>

<?
$name=trim(fgets(STDIN));
$n=trim(fgets(STDIN));
for($i=0;$i<$n;$i++)
    $arr[]=trim(fgets(STDIN));
$privs=array('posted on','commented on','likes');
foreach($arr as $val){
    preg_match('/(.*?) (posted on|commented on|likes) (.*?)(\'s)/',$val,$m);
    if($m[2]=='posted on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=15; $newarr[$m[1]]+=0;}
    if($m[2]=='commented on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=10; $newarr[$m[1]]+=0;}
    if($m[2]=='likes' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=5; $newarr[$m[1]]+=0;}
    if($m[1]!=$name && $m[3]!=$name) {$newarr[$m[1]]+=0; $newarr[$m[3]]+=0;}
}
unset($newarr[$name]);
ksort($newarr);
foreach($newarr as $key=>$val){
     $new2[]=array($key,$val);
}
function cmp($a,$b) {
    if ($a[1]==$b[1])
return $a[0]>$b[0];
    else return $a[1]<$b[1];
}
usort($new2,'cmp');
foreach($new2 as $val){
    echo $val[0]."\n";
}
?>

<?
$name=trim(fgets(STDIN));
$n=trim(fgets(STDIN));
for($i=0;$i<$n;$i++)
    $arr[]=trim(fgets(STDIN));
$privs=array('posted on','commented on','likes');
foreach($arr as $val){
    preg_match('/(.*?) (posted on|commented on|likes) (.*?)(\'s)/',$val,$m);
//  print_r ($m);
    if($m[2]=='posted on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=15; $newarr[$m[1]]+=0;}
    if($m[2]=='commented on' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=10; $newarr[$m[1]]+=0;}
    if($m[2]=='likes' && ($m[1]==$name || $m[3]==$name)) {$newarr[$m[3]]+=5; $newarr[$m[1]]+=0;}
    if($m[1]!=$name && $m[3]!=$name) {$newarr[$m[1]]+=0; $newarr[$m[3]]+=0;}
}
unset($newarr[$name]);
ksort($newarr);
foreach($newarr as $key=>$val){
     $new2[]=array($key,$val);
}
function cmp($a,$b) {
    if ($a[1]==$b[1])
return $a[0]>$b[0];
    else return $a[1]<$b[1];
}
usort($new2,'cmp');
//print_r($newarr);
foreach($new2 as $val){
    echo $val[0]."\n";
}
//print_r($new2);

?>


A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival programme at least once. In other words, each integer from 1 to k occurs in the sequence a1, a2, ..., an at least once.Valentine is a movie critic. He wants to watch some movies of the festival and then describe his impressions on his site.As any creative person, Valentine is very susceptive. After he watched the movie of a certain genre, Valentine forms the mood he preserves until he watches the next movie. If the genre of the next movie is the same, it does not change Valentine's mood. If the genres are different, Valentine's mood changes according to the new genre and Valentine has a stress.Valentine can't watch all n movies, so he decided to exclude from his to-watch list movies of one of the genres. In other words, Valentine is going to choose exactly one of the k genres and will skip all the movies of this genre. He is sure to visit other movies.Valentine wants to choose such genre x (1 ≤ x ≤ k), that the total number of after-movie stresses (after all movies of genre x are excluded) were minimum.

The first line of the input contains two integers n and k (2 ≤ k ≤ n ≤ 105), where n is the number of movies and k is the number of genres. The second line of the input contains a sequence of n positive integers a1, a2, ..., an (1 ≤ ai ≤ k), where ai is the genre of the i-th movie. It is guaranteed that each number from 1 to k occurs at least once in this sequence.

Print a single number — the number of the genre (from 1 to k) of the excluded films. If there are multiple answers, print the genre with the minimum number.

NoteIn the first sample if we exclude the movies of the 1st genre, the genres 2, 3, 2, 3, 3, 3 remain, that is 3 stresses; if we exclude the movies of the 2nd genre, the genres 1, 1, 3, 3, 3, 1, 1, 3 remain, that is 3 stresses; if we exclude the movies of the 3rd genre the genres 1, 1, 2, 2, 1, 1 remain, that is 2 stresses.In the second sample whatever genre Valentine excludes, he will have exactly 3 stresses.


You are given three sequences: $$$a_1, a_2, \ldots, a_n$$$; $$$b_1, b_2, \ldots, b_n$$$; $$$c_1, c_2, \ldots, c_n$$$.For each $$$i$$$, $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$.Find a sequence $$$p_1, p_2, \ldots, p_n$$$, that satisfy the following conditions: $$$p_i \in \{a_i, b_i, c_i\}$$$ $$$p_i \neq p_{(i \mod n) + 1}$$$.In other words, for each element, you need to choose one of the three possible values, such that no two adjacent elements (where we consider elements $$$i,i+1$$$ adjacent for $$$i<n$$$ and also elements $$$1$$$ and $$$n$$$) will have equal value.It can be proved that in the given constraints solution always exists. You don't need to minimize/maximize anything, you need to find any proper sequence.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 100$$$): the number of elements in the given sequences. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$). The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \leq b_i \leq 100$$$). The fourth line contains $$$n$$$ integers $$$c_1, c_2, \ldots, c_n$$$ ($$$1 \leq c_i \leq 100$$$). It is guaranteed that $$$a_i \neq b_i$$$, $$$a_i \neq c_i$$$, $$$b_i \neq c_i$$$ for all $$$i$$$.

For each test case, print $$$n$$$ integers: $$$p_1, p_2, \ldots, p_n$$$ ($$$p_i \in \{a_i, b_i, c_i\}$$$, $$$p_i \neq p_{i \mod n + 1}$$$). If there are several solutions, you can print any.


Alice and Bob play a game. They have a binary string $$$s$$$ (a string such that each character in it is either $$$0$$$ or $$$1$$$). Alice moves first, then Bob, then Alice again, and so on.During their move, the player can choose any number (not less than one) of consecutive equal characters in $$$s$$$ and delete them.For example, if the string is $$$10110$$$, there are $$$6$$$ possible moves (deleted characters are bold):  $$$\textbf{1}0110 \to 0110$$$;  $$$1\textbf{0}110 \to 1110$$$;  $$$10\textbf{1}10 \to 1010$$$;  $$$101\textbf{1}0 \to 1010$$$;  $$$10\textbf{11}0 \to 100$$$;  $$$1011\textbf{0} \to 1011$$$. After the characters are removed, the characters to the left and to the right of the removed block become adjacent. I. e. the following sequence of moves is valid: $$$10\textbf{11}0 \to 1\textbf{00} \to 1$$$.The game ends when the string becomes empty, and the score of each player is the number of $$$1$$$-characters deleted by them.Each player wants to maximize their score. Calculate the resulting score of Alice.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 500$$$) — the number of test cases. Each test case contains exactly one line containing a binary string $$$s$$$ ($$$1 \le |s| \le 100$$$).

For each test case, print one integer — the resulting score of Alice (the number of $$$1$$$-characters deleted by her).

NoteQuestions about the optimal strategy will be ignored.

<?php
$inputCount = trim(fgets(STDIN));
for ($i = 0; $i < $inputCount; $i++) runProgram();

function runProgram()
{
  $line = trim(fgets(STDIN));
  $points = 0;

  for ($j = 1;; $j++) {
    $max = 0;
    $counter = 0;

    // Get maximum from 1..1 from current line
    for ($i = 0; $i < strlen($line); $i++) {
      if ($line[$i] == '1') {
        $counter += 1;
      } else {
        $counter = 0;
      }

      if ($counter > $max) $max = $counter;
    }

    if ($j % 2 != 0) $points += $max;

    if ($max == 0) break;
    else {
      $search = str_repeat('1', $max);
      $line = preg_replace("/$search/", '', $line, 1);
    }
  }

  echo "$points\n";
}

<?php

$inputs[0] = 5;
$inputs[1] ='01111001';
$inputs[2] ='0000';
$inputs[3] ='111111';
$inputs[4] ='101010101';
$inputs[5] ='011011110111';

$debug = false;

$tests = $debug ? $inputs[0] : readline();
$answers = [];
for ($t = 1; $t <= $tests; $t++){

	$score = 0;
	$str = $debug ? $inputs[$t] : readline();
	$len = strlen($str);

		$counter = 0;
		$consecutives = [];
		for ($i = 0; $i < $len; $i++){
			if($str[$i] == '1'){
				$counter++;
				if($i == $len-1 && $counter > 0) $consecutives[]= $counter;
			}else {
				if($counter > 0) $consecutives[]= $counter;
				$counter = 0;
			}
		}

		rsort($consecutives);

		$alice = 0;
		$bob = 0;
		foreach ($consecutives as $round => $score){
			if($round == 0){
				$alice += $score;
			}else{
				if($round % 2) $bob += $score; else $alice+= $score;
			}
		}

	$answers[]= $alice;

}
foreach ($answers as $a) echo $a . PHP_EOL;

<?php

$inputs[0] = 5;
$inputs[1] ='01111001';
$inputs[2] ='0000';
$inputs[3] ='111111';
$inputs[4] ='101010101';
$inputs[5] ='011011110111';

$debug = false;

$answers = [];
$tests = readline();
for ($t = 1; $t <= $tests; $t++){

	$score = 0;
	#$str = $inputs[$t];
	$str = readline();
	$len = strlen($str);

	$round = 0;
	while (true){

		$round++;

		$max_start = -1;
		$start = -1;
		$max = -1;
		$counter = 0;

		for ($i = 0; $i < $len; $i++){
			if($str[$i] == '1' && $counter == 0){
				$start = $i;
				$counter++;
			}elseif ($str[$i] == '1' && $counter != 0){
				$counter++;
			}else{
				if($counter > $max){
					$max = $counter;
					$max_start = $start;
				}
				$counter = 0;
			}
		}
		if($counter > $max){
			$max = $counter;
			$max_start = $start;
		}else{
			if($debug) echo "Counter ($counter) no es mayor a max ($max)". PHP_EOL;
		}

		if($debug) echo "Replacing from $max_start to $max" . PHP_EOL;
		$str = substr_replace($str,'', $max_start, $max);
		$len = strlen($str);
		if($round % 2){
			$score += $max;
			if($debug) echo "Round $t-$round: $str - Alice +$max". PHP_EOL;
		}else{
			//$score += $max;
			if($debug) echo "Round $t-$round: $str - Bob +$max". PHP_EOL;
		}

		if($max == 0) break;

	}
	$answers[]= $score;

}
foreach ($answers as $a) echo $a.PHP_EOL;


Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In the end, Polycarpus got a list of n tasks that went to the SMSC of the corporation. Each task was described by the time it was received by the SMSC and the number of text messages to send. More formally, the i-th task was described by two integers ti and ci — the receiving time (the second) and the number of the text messages, correspondingly.Polycarpus knows that the SMSC cannot send more than one text message per second. The SMSC uses a queue to organize its work. Consider a time moment x, the SMSC work at that moment as follows:  If at the time moment x the queue is not empty, then SMSC sends one message from the queue (SMSC gets the message from the head of the queue). Otherwise it doesn't send messages at the time moment x.  If at the time moment x SMSC receives a task, then it adds to the queue all the messages from this task (SMSC adds messages to the tail of the queue). Note, that the messages from the task cannot be send at time moment x. That's because the decision about sending message or not is made at point 1 before adding these messages to the queue. Given the information about all n tasks, Polycarpus wants to count two values: the time when the last text message was sent and the maximum size of the queue at some time. Help him count these two characteristics he needs to evaluate the efficiency of the SMSC.

The first line contains a single integer n (1 ≤ n ≤ 103) — the number of tasks of the SMSC. Next n lines contain the tasks' descriptions: the i-th line contains two space-separated integers ti and ci (1 ≤ ti, ci ≤ 106) — the time (the second) when the i-th task was received and the number of messages to send, correspondingly. It is guaranteed that all tasks were received at different moments of time. It is guaranteed that the tasks are sorted in the chronological order, that is, ti < ti + 1 for all integer i (1 ≤ i < n).

In a single line print two space-separated integers — the time when the last text message was sent and the maximum queue size at a certain moment of time.

NoteIn the first test sample:   second 1: the first message has appeared in the queue, the queue's size is 1;  second 2: the first message is sent, the second message has been received, the queue's size is 1;  second 3: the second message is sent, the queue's size is 0, Thus, the maximum size of the queue is 1, the last message was sent at the second 3.

<?
$num = trim(fgets(STDIN));
for($i = 0; $i < $num; $i++){
    $arr[] = explode(' ', trim(fgets(STDIN)));
}
$sms_now = 0;
$time_last = 0;
$max = 0;
$now = 0;
foreach($arr as $a){
    if($sms_now != 0){
        if($sms_now - ($a[0] - $time_last) >= 0)
            $tmp = $sms_now - ($a[0] - $time_last);
        else
            $tmp = 0;
        $sms_now =  $tmp + $a[1];
    }
    else
        $sms_now = $a[1];
    if($max < $sms_now)
        $max = $sms_now;
    $time_last = $a[0];
}
echo ($time_last+$sms_now) . ' ' . $max . '
';
?>

<?

$n = (int)fgets(STDIN);

$msg = array();
while($n--) {
    list($time, $msg_cnt) = explode(" ", fgets(STDIN));
    $msg[$time] = $msg_cnt;
}

$queue_cnt = 0;
$queue_max = 0;
$last_time = 0;
$total_time = 0;
foreach($msg as $time => $cnt) {
    $time_diff = $time - $last_time;
    $last_time = $time;
    $queue_cnt = max(0, $queue_cnt - $time_diff);

    $queue_cnt += $cnt;
    $queue_max = max($queue_cnt, $queue_max);

    $total_time += $time_diff;
}

$total_time += $queue_cnt;

echo $total_time, " ", $queue_max;

<?php

$fIn = fopen('php://stdin', 'r');
$n = intval(fgets($fIn));
$queue = 0;
$maxSize = 0;
$time = 0;
$prevTime = 0;
for ($i = 0; $i < $n; ++$i) {
    $str = fgets($fIn);
    $str = preg_split('[ ]', $str);
    $queue += $str[1];
    if ($i != 0) {
        $queue -= $str[0] - $prevTime;
        $queue = max($str[1], $queue);
    }
    if ($queue > $maxSize) {
        $maxSize = $queue;
    }
    $prevTime = $str[0];
    #echo $prevTime, ' ', $queue, PHP_EOL;
    $time += $str[0];
}
fclose($fIn);
echo ($prevTime + $queue), ' ', $maxSize;
?>

<?php
$file = "php://stdin";
$lines = explode("\n", str_replace("\r", "", file_get_contents($file)));
$n = array_shift($lines);
$queue = 0;
$p = 0;
$max = 0;

for ($i = 0; $i < $n; $i++) {
    list($time, $count) = explode(" ", $lines[$i]);
    $queue = max(0, $queue - $time + $p) + $count;
    $max = max($queue, $max);
    $p = $time;
}
$time = $p + $queue;
echo $time, " ", $max;

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

<?
$num = trim(fgets(STDIN));
for($i = 0; $i < $num; $i++){
    $arr[] = explode(' ', trim(fgets(STDIN)));
}
$sms_now = 0;
$time_last = 0;
$max = 0;
$now = 0;
foreach($arr as $a){
if(trim($a[0]) - $time_last >= 0)
$tmp = trim($a[0]) - $time_last;
else $tmp = 0;
    if($sms_now != 0)
        $sms_now = ($sms_now - $tmp) + trim($a[1]);
    else
        $sms_now = trim($a[1]);
    if($max < $sms_now)
        $max = $sms_now;
    $time_last = trim($a[0]);
}
echo ($time_last+$sms_now) . ' ' . $max . '
';
?>

<?

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

$sms_now = 0;
$time_last = 0;
$max = 0;
$now = 0;
foreach($arr as $a){

    if($sms_now != 0)
        $sms_now = ($sms_now - ($a[0] - $time_last)) + $a[1];
    else
        $sms_now = $a[1];
    if($max < $sms_now)
        $max = $sms_now;
    $time_last = $a[0];
}
echo ($time_last+$sms_now) . ' ' . $max . '
';
?>

<?php

$fIn = fopen('php://stdin', 'r');
$n = intval(fgets($fIn));
$queue = 0;
$maxSize = 0;
$time = 0;
$prevTime = 0;
for ($i = 0; $i < $n; ++$i) {
    $str = fgets($fIn);
    $str = preg_split('[ ]', $str);
    $queue += $str[1];
    if ($i != 0) {
        $queue -= max(0, $str[0] - $prevTime);
        $queue = max(0, $queue);
    }
    if ($queue > $maxSize) {
        $maxSize = $queue;
    }
    $prevTime = $str[0];
    #echo $prevTime, ' ', $queue, PHP_EOL;
    $time += $str[0];
}
fclose($fIn);
if ($queue == 0)
    $queue = $str[1];
echo ($prevTime + $queue), ' ', $maxSize;
?>

<?php

$fIn = fopen('php://stdin', 'r');
$n = intval(fgets($fIn));
$queue = 0;
$maxSize = 0;
$time = 0;
$prevTime = 0;
for ($i = 0; $i < $n; ++$i) {
    $str = fgets($fIn);
    $str = preg_split('[ ]', $str);
    $queue += $str[1];
    if ($i != 0) {
        $queue -= max(0, $str[0] - $prevTime);
        $queue = max(0, $queue);
    }
    if ($queue > $maxSize) {
        $maxSize = $queue;
    }
    $prevTime = $str[0];
    #echo $prevTime, ' ', $queue, PHP_EOL;
    $time += $str[0];
}
fclose($fIn);

echo ($prevTime + $queue), ' ', $maxSize;
?>

<?php

$fIn = fopen('php://stdin', 'r');
$n = intval(fgets($fIn));
$queue = 0;
$maxSize = 0;
$time = 0;
$prevTime = 0;
for ($i = 0; $i < $n; ++$i) {
    $str = fgets($fIn);
    $str = preg_split('[ ]', $str);
    $queue += $str[1];
    if ($i != 0)
        $queue -= max(0, $str[0] - $prevTime);
    if ($queue > $maxSize) {
        $maxSize = $queue;
    }
    $prevTime = $str[0];
    $time += $str[0];
}
fclose($fIn);

echo ($prevTime + $queue), ' ', $maxSize;
?>


You've got an array, consisting of n integers a1, a2, ..., an. Also, you've got m queries, the i-th query is described by two integers li, ri. Numbers li, ri define a subsegment of the original array, that is, the sequence of numbers ali, ali + 1, ali + 2, ..., ari. For each query you should check whether the corresponding segment is a ladder. A ladder is a sequence of integers b1, b2, ..., bk, such that it first doesn't decrease, then doesn't increase. In other words, there is such integer x (1 ≤ x ≤ k), that the following inequation fulfills: b1 ≤ b2 ≤ ... ≤ bx ≥ bx + 1 ≥ bx + 2... ≥ bk. Note that the non-decreasing and the non-increasing sequences are also considered ladders.

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of array elements and the number of queries. The second line contains the sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 109), where number ai stands for the i-th array element. The following m lines contain the description of the queries. The i-th line contains the description of the i-th query, consisting of two integers li, ri (1 ≤ li ≤ ri ≤ n) — the boundaries of the subsegment of the initial array. The numbers in the lines are separated by single spaces.

Print m lines, in the i-th line print word "Yes" (without the quotes), if the subsegment that corresponds to the i-th query is the ladder, or word "No" (without the quotes) otherwise.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array();
$e = 1;
for($x = 1; $x < $a - 1; $x++)
{
    if(($c[$x - 1] > $c[$x]) && ($c[$x] < $c[$x + 1]))
    {
        $e++;
        $d[$x] = $e;
        $e++;
    }
    else
    {
        $d[$x] = $e;
    }
}
array_unshift($d, "1");
array_unshift($d, $d[1]);
unset($d[0]);
array_push($d, $d[count($d)]);
for($x = 1; $x < $b; $x++)
{
    list($f, $g) = explode(" ", trim(fgets(STDIN)));
    if($d[$g] - $d[$f] > 1)
    {
        print "No\n";
    }
    else
    {
        print "Yes\n";
    }
}
list($f, $g) = explode(" ", trim(fgets(STDIN)));
if($d[$g] - $d[$f] > 1)
{
    print "No";
}
else
{
    print "Yes";
}
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array();
$e = 1;
for($x = 1; $x < $a - 1; $x++)
{
    if(($c[$x - 1] > $c[$x]) && ($c[$x] < $c[$x + 1]))
    {
        $e++;
        $d[$x] = $e;
        $e++;
    }
    else
    {
        $d[$x] = $e;
    }
}
array_unshift($d, $d[1]);
array_unshift($d, $d[1]);
unset($d[0]);
array_push($d, $d[count($d)]);
for($x = 1; $x < $b; $x++)
{
    list($f, $g) = explode(" ", trim(fgets(STDIN)));
    if($d[$g] - $d[$f] > 1)
    {
        print "No\n";
    }
    else
    {
        print "Yes\n";
    }
}
list($f, $g) = explode(" ", trim(fgets(STDIN)));
if($d[$g] - $d[$f] > 1)
{
    print "No";
}
else
{
    print "Yes";
}
?>

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array();
$e = 1;
for($x = 1; $x < $a - 1; $x++)
{
    if(($c[$x - 1] > $c[$x]) && ($c[$x] < $c[$x + 1]))
    {
        $e++;
        $d[$x] = $e;
        $e++;
    }
    else
    {
        $d[$x] = $e;
    }
}
array_unshift($d, $d[1]);
array_unshift($d, $d[1]);
unset($d[0]);
array_push($d, $d[count($d) - 1]);
for($x = 1; $x < $b; $x++)
{
    list($f, $g) = explode(" ", trim(fgets(STDIN)));
    if($d[$g] - $d[$f] > 1)
    {
        print "No\n";
    }
    else
    {
        print "Yes\n";
    }
}
list($f, $g) = explode(" ", trim(fgets(STDIN)));
if($d[$g] - $d[$f] > 1)
{
    print "No";
}
else
{
    print "Yes";
}
?>


Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matrix should be represented by character "*". Look at the examples to understand what you need to draw.

The only line contains an integer n (3 ≤ n ≤ 101; n is odd).

***D***
**DDD**
*DDDDD*
DDDDDDD
*DDDDD*
**DDD**
***D***

<?php
/**
 * Cik d burtus vajadzees i-tajaa rindaa
 * 1  2  3  4  5  6   7
 * 2  4  6  8  10 12  14
 * 1  3  5  7  9  11  13
 */
function D($i)
{
	return $i * 2 - 1;
}

fscanf(STDIN, "%d\n", $n);
$output = "";
for ($row = 1; $row <= $n; $row++)
{
	$D_count = D(min($n + 1 - $row, $row));
	$S_count = ($n - $D_count) / 2;

	$output .= str_repeat("*", $S_count);
	$output .= str_repeat("D", $D_count);
	$output .= str_repeat("*", $S_count);
	$output .= "\n";
}

fprintf(STDOUT, "%s", $output);
?>

<?php
// 454A     Маленькая пони и пещера кристаллов
$in = fopen("php://stdin", 'r');

$input_line = fgets($in);
$n = (int) $input_line;

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

$out = array();

$m = ($n + 1) /2;

for ($i=0; $i < $m ; $i++) {
    $out[$i]  = str_repeat('*', $m-$i-1);
    $out[$i] .= str_repeat('D', ($i+1)*2-1);
    $out[$i] .= str_repeat('*', $m-$i-1);
    $out[$i] .= "\n";
    if ($i !== $n) {
        $out[$n-$i-1] = $out[$i];
    }
}

for ($i=0; $i < $n ; $i++) {
    echo $out[$i];
}

?>

<?php
error_reporting("off");
//454A: Little Pony and Crystal Mine
$n = trim(fgets(STDIN)); //$n = 227;
$dsize = 1;
for ($i = $n; $i > ceil($n / 2); $i--) {
  $a = ($n - $dsize) / 2;
  echo str_repeat("*", $a);
  echo str_repeat("D", $dsize);
  echo str_repeat("*", $a)."\n";
  $dsize = $dsize + 2;
}
echo str_repeat("D", $dsize)."\n";
$dsize = $dsize - 2;
$top = ceil($n / 2) + 1;
for ($i = $top; $i <= $n; $i++) {
  $a = ($n - $dsize) / 2;
  echo str_repeat("*", $a);
  echo str_repeat("D", $dsize);
  echo str_repeat("*", $a)."\n";
  $dsize = $dsize - 2;
}
?>

<?php
/**
 * Cik d burtus vajadzees i-tajaa rindaa
 * 1  2  3  4  5  6   7
 * 2  4  6  8  10 12  14
 * 1  3  5  7  9  11  13
 */
function D($i)
{
	return $i * 2 - 1;
}

fscanf(STDIN, "%d\n", $n);
$output = "";
for ($row = 1; $row <= $n; $row++)
{
	$D_count = D(min($n + 1 - $row, $row));
	$S_count = ($n - $D_count) / 2;

	$output .= str_repeat("*", $S_count);
	$output .= str_repeat("D", $D_count);
	$output .= str_repeat("*", $S_count);
	$output .= "\n";
}

fprintf(STDOUT, "%d", $output);
?>


Recently, Polycarp completed $$$n$$$ successive tasks.For each completed task, the time $$$s_i$$$ is known when it was given, no two tasks were given at the same time. Also given is the time $$$f_i$$$ when the task was completed. For each task, there is an unknown value $$$d_i$$$ ($$$d_i>0$$$) — duration of task execution.It is known that the tasks were completed in the order in which they came. Polycarp performed the tasks as follows:  As soon as the very first task came, Polycarp immediately began to carry it out.  If a new task arrived before Polycarp finished the previous one, he put the new task at the end of the queue.  When Polycarp finished executing the next task and the queue was not empty, he immediately took a new task from the head of the queue (if the queue is empty — he just waited for the next task). Find $$$d_i$$$ (duration) of each task.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The descriptions of the input data sets follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$). The second line of each test case contains exactly $$$n$$$ integers $$$s_1 < s_2 < \dots < s_n$$$ ($$$0 \le s_i \le 10^9$$$). The third line of each test case contains exactly $$$n$$$ integers $$$f_1 < f_2 < \dots < f_n$$$ ($$$s_i < f_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each of $$$t$$$ test cases print $$$n$$$ positive integers $$$d_1, d_2, \dots, d_n$$$ — the duration of each task.

NoteFirst test case:The queue is empty at the beginning: $$$[ ]$$$. And that's where the first task comes in. At time $$$2$$$, Polycarp finishes doing the first task, so the duration of the first task is $$$2$$$. The queue is empty so Polycarp is just waiting.At time $$$3$$$, the second task arrives. And at time $$$7$$$, the third task arrives, and now the queue looks like this: $$$[7]$$$.At the time $$$10$$$, Polycarp finishes doing the second task, as a result, the duration of the second task is $$$7$$$.And at time $$$10$$$, Polycarp immediately starts doing the third task and finishes at time $$$11$$$. As a result, the duration of the third task is $$$1$$$.    An example of the first test case.

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

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

 function solve()
 {
     $n = IO::getInt();
     $a = IO::getArray();
     $b = IO::getArray();
     $ans = [];
     $max = $a[0];
     for($i=0; $i<$n; $i++) {
          $max = IO::getMaxValue($max, $a[$i]);
          $ans[] = $b[$i] - $max;
          $max = IO::getMaxValue($max, $b[$i]);

     }
      IO::prArray($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
{

}


Ivan is playing a strange game.He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:  Initially Ivan's score is 0;  In each column, Ivan will find the topmost 1 (that is, if the current column is j, then he will find minimum i such that ai, j = 1). If there are no 1's in the column, this column is skipped;  Ivan will look at the next min(k, n - i + 1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score. Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.

The first line contains three integer numbers n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100). Then n lines follow, i-th of them contains m integer numbers — the elements of i-th row of matrix a. Each number is either 0 or 1.

Print two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.

NoteIn the first example Ivan will replace the element a1, 2.


Vasya came up with a password to register for EatForces — a string $$$s$$$. The password in EatForces should be a string, consisting of lowercase and uppercase Latin letters and digits.But since EatForces takes care of the security of its users, user passwords must contain at least one digit, at least one uppercase Latin letter and at least one lowercase Latin letter. For example, the passwords "abaCABA12", "Z7q" and "3R24m" are valid, and the passwords "qwerty", "qwerty12345" and "Password" are not. A substring of string $$$s$$$ is a string $$$x = s_l s_{l + 1} \dots s_{l + len - 1} (1 \le l \le |s|, 0 \le len \le |s| - l + 1)$$$. $$$len$$$ is the length of the substring. Note that the empty string is also considered a substring of $$$s$$$, it has the length $$$0$$$.Vasya's password, however, may come too weak for the security settings of EatForces. He likes his password, so he wants to replace some its substring with another string of the same length in order to satisfy the above conditions. This operation should be performed exactly once, and the chosen string should have the minimal possible length.Note that the length of $$$s$$$ should not change after the replacement of the substring, and the string itself should contain only lowercase and uppercase Latin letters and digits.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of testcases. Each of the next $$$T$$$ lines contains the initial password $$$s~(3 \le |s| \le 100)$$$, consisting of lowercase and uppercase Latin letters and digits. Only $$$T = 1$$$ is allowed for hacks.

For each testcase print a renewed password, which corresponds to given conditions.  The length of the replaced substring is calculated as following: write down all the changed positions. If there are none, then the length is $$$0$$$. Otherwise the length is the difference between the first and the last changed position plus one. For example, the length of the changed substring between the passwords "abcdef" $$$\rightarrow$$$ "a7cdEf" is $$$4$$$, because the changed positions are $$$2$$$ and $$$5$$$, thus $$$(5 - 2) + 1 = 4$$$. It is guaranteed that such a password always exists. If there are several suitable passwords — output any of them.

NoteIn the first example Vasya's password lacks a digit, he replaces substring "C" with "4" and gets password "abcD4E". That means, he changed the substring of length 1.In the second example Vasya's password is ok from the beginning, and nothing has to be changed. That is the same as replacing the empty substring with another empty substring (length 0).

<?php

function process($str)
{
    $ex = [];

    $a = null;
    $b = null;
    $c = null;

    $str = str_split($str);

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

        $num = ord($str[$i]);

        if ($num <= ord('9')) {
            $a = $i;
        } elseif ($num <= ord('Z')) {
            $b = $i;
        } else {
            $c = $i;
        }
    }

    if($a !== null)
    {
        $ex['1'] = $a;
    }
    if($b !== null)
    {
        $ex['A'] = $b;
    }
    if($c !== null)
    {
        $ex['a'] = $c;
    }

    $insert = array_values(array_diff(['1', 'A', 'a'], array_keys($ex)));

    if (count($ex) == 1) {

        $pos = reset($ex);
        $i = $pos != 0 ? 0 : $pos + 1;
        $j = $i + 1 != $pos ? $i + 1 : $pos + 1;

        $str[$i] = $insert[0];
        $str[$j] = $insert[1];

    } elseif (count($ex) == 2) {

        list($a, $b) = array_values($ex);

        $t = $a;
        $a = $a > $b ? $b : $a;
        $b = $a == $b ? $t : $b;

        $insert = $insert[0];
        $str[0 < $a ? 0 : ($a + 1 == $b ? $b + 1 : $a + 1)] = $insert;
    }

    return implode($str);
}

$handle = fopen("php://stdin", "r");
$n = (int)fgets($handle);

$list = [];

for ($i = 0; $i < $n; $i++) {
    $str = trim(fgets($handle));
    $list[] = process($str);
}

foreach ($list as $str) {
    echo $str, PHP_EOL;
}


Given a permutation $$$p$$$ of length $$$n$$$, find its subsequence $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ of length at least $$$2$$$ such that:  $$$|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$$$ is as big as possible over all subsequences of $$$p$$$ with length at least $$$2$$$.  Among all such subsequences, choose the one whose length, $$$k$$$, is as small as possible. If multiple subsequences satisfy these conditions, you are allowed to find any of them.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deleting some (possibly, zero or all) elements.A permutation of length $$$n$$$ is an array of length $$$n$$$ in which every element from $$$1$$$ to $$$n$$$ occurs exactly once.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the length of the permutation $$$p$$$. The second line of each test case contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_{n}$$$ ($$$1 \le p_i \le n$$$, $$$p_i$$$ are distinct) — the elements of the permutation $$$p$$$. The sum of $$$n$$$ across the test cases doesn't exceed $$$10^5$$$.

For each test case, the first line should contain the length of the found subsequence, $$$k$$$. The second line should contain $$$s_1$$$, $$$s_2$$$, $$$\ldots$$$, $$$s_k$$$ — its elements. If multiple subsequences satisfy these conditions, you are allowed to find any of them.

NoteIn the first test case, there are $$$4$$$ subsequences of length at least $$$2$$$:  $$$[3,2]$$$ which gives us $$$|3-2|=1$$$.  $$$[3,1]$$$ which gives us $$$|3-1|=2$$$.  $$$[2,1]$$$ which gives us $$$|2-1|=1$$$.  $$$[3,2,1]$$$ which gives us $$$|3-2|+|2-1|=2$$$. So the answer is either $$$[3,1]$$$ or $$$[3,2,1]$$$. Since we want the subsequence to be as short as possible, the answer is $$$[3,1]$$$.

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

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

    $t = intval(trim(fgets(STDIN))) ;
    while($t --)
    {
        $n = intval(trim(fgets(STDIN))) ;

        $in_str = explode(" ", trim(fgets(STDIN))) ;
        for($i = 0; $i < $n ; $i ++) $in_str[$i] = intval($in_str[$i]) ;

        $ans = array() ;
        array_push($ans, $in_str[0]) ;

        for($i = 1; $i + 1 < $n; $i ++)
        {
            if($in_str[$i] > $in_str[$i - 1] && $in_str[$i] > $in_str[$i + 1])
                array_push($ans, $in_str[$i]) ;
            else if($in_str[$i] < $in_str[$i - 1] && $in_str[$i] < $in_str[$i + 1])
                array_push($ans, $in_str[$i]) ;
        }
        array_push($ans, $in_str[$n - 1]) ;

        echo count($ans) . "\n" ;
        echo implode(" ", $ans) . "\n" ;
    }
?>


Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?

The first line contains an integer n, which is the size of one message (2 ≤ n ≤ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.

On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.

NoteLet's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".

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

function a($str){
    return strlen(trim($str))+1;
}
$otr = array_map('a', preg_split('~[.?!]~',$text));
$cnt=0;
$last=$n;
foreach($otr as $cur){
    if($cur<2)
        continue;
    if($cur>$n){
        exit('Impossible');
    }
    if($cur+1+$last<=$n)
        $last+=$cur+1;
    else{
        ++$cnt;
        $last=$cur;
    }
}
print $cnt;

<?php
$n = trim(fgets(STDIN));
$str = trim(fgets(STDIN));
$total = 0;
$symbols = 0;
$numb=0;
$second_round=false;
	for($i=0; $i<strlen($str); $i++)
	{
		$symbols++;
		if($str[$i]=='.' || $str[$i]=='?' || $str[$i]=='!')
		{
			if($second_round)
			{
				if($symbols-1>$n)
				{
					print "Impossible";
					return;
				}
			}
			else
			{
				if($symbols>$n)
				{
					print "Impossible";
					return;
				}
			}

			if($total+$symbols<=$n)
			{
				$total+=$symbols;
				$second_round=true;
			}
			else
			{
				$total=$symbols-1;
				$numb++;
				$second_round=true;
			}
			$symbols=0;
		}
	}
print $numb+1;

?>

<?php
$n = (int)fgets(STDIN,1111);
$text=trim(fgets(STDIN,11111));

function a($str){
    return strlen(trim($str))+1;
}
$otr = array_map('a', preg_split('~[.?!]~',$text));
$cnt=0;
$last=$n;
foreach($otr as $cur){
    if($cur<2)
        continue;
    if($cur>$n){
        exit('Impossible');
    }
    if($cur+1+$last<=$n)
        $last+=$cur+1;
    else{
        ++$cnt;
        $last=$cur;
    }
}
print $cnt;

<?php
$n = trim(fgets(STDIN));
$str = trim(fgets(STDIN));
$total = 0;
$symbols = 0;
$numb=0;
	for($i=0; $i<strlen($str); $i++)
	{
		$symbols++;
		if($str[$i]=='.' || $str[$i]=='?' || $str[$i]=='!')
		{
			if($symbols>$n)
			{
				print "Impossible";
				return;
			}

			if($total+$symbols<=$n)
			{
				$total+=$symbols;
			}
			else
			{
				$total=$symbols-1;
				$numb++;
			}
			$symbols=0;
		}
	}
print $numb+1;

?>

<?php
$n = trim(fgets(STDIN));
$str = trim(fgets(STDIN));
$total = 0;
$symbols = 0;
$numb=0;
	for($i=0; $i<strlen($str); $i++)
	{
		$symbols++;
		if($str[$i]=='.' || $str[$i]=='?' || $str[$i]=='!')
		{
			if($symbols>$n)
			{
				print "Imbossible";
				return;
			}

			if($total+$symbols<=$n)
			{
				$total+=$symbols;
			}
			else
			{
				$total=$symbols-1;
				$numb++;
			}
			$symbols=0;
		}
	}
print $numb+1;

?>

<?php
$n = (int)fgets(STDIN,1111);
$text=trim(fgets(STDIN,1111));

function a($str){
    return strlen($str)+1;
}
$otr = array_map('a', preg_split('~[.?!] ~',$text));
$cnt=0;
$last=$n;
foreach($otr as $cur){
    if($cur>$n){
        exit('Impossible');
    }
    if($cur+1+$last<=$n)
        $last+=$cur+1;
    else{
        ++$cnt;
        $last=$cur;
    }
}
print $cnt;

<?php
$n = (int)fgets(STDIN,1111);
$text=trim(fgets(STDIN,1111));

function a($str){
    return strlen(trim($str))+1;
}
$otr = array_map('a', preg_split('~[.?!]~',$text));
$cnt=0;
$last=$n;
//var_dump($otr);
foreach($otr as $cur){
    if($cur<2)
        continue;
    if($cur>$n){
        exit('Impossible');
    }
    if($cur+1+$last<=$n)
        $last+=$cur+1;
    else{
        ++$cnt;
        $last=$cur;
    }
}
print $cnt;


The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.Help the Beaver to write a program that will encrypt messages in the described manner.

The first input line contains three integers n, m and c, separated by single spaces.  The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.  The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key. The input limitations for getting 30 points are:    1 ≤ m ≤ n ≤ 103  1 ≤ c ≤ 103  The input limitations for getting 100 points are:    1 ≤ m ≤ n ≤ 105  1 ≤ c ≤ 103

Print n space-separated integers — the result of encrypting the original message.

NoteIn the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.

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

<?
    define ("TEST", false);
    if (TEST) $GLOBALS['file'] = fopen('input.txt', 'r');
    else $GLOBALS['file'] = fopen('php://stdin', 'r');
    function debug($var){echo '<pre>'; print_r($var); echo '</pre>';}
    function read_str(){return trim(fgets($GLOBALS['file']));}
    function read_array(){return explode(' ', read_str());}
    /***************************************************************/
    $arr = read_array();
    $n = $arr[0];
    $m = $arr[1];
    $c = $arr[2];
    $GLOBALS['c'] = $c;

    $a = read_array();
    $b = read_array();

    $k = $n - $m + 1;

    function add($a, $b)
    {
        return ($a+$b)%$GLOBALS['c'];
    }

    for($i=0; $i<$k; $i++)
    {
        for($j=0; $j<$m; $j++)
        {
            $a[$j+$i] = add($a[$j+$i], $b[$j]);
        }
    }

    foreach($a as $n) echo $n, ' ';
?>


Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price $$$z$$$ chizhiks per coconut. Sasha has $$$x$$$ chizhiks, Masha has $$$y$$$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has $$$5$$$ chizhiks, Masha has $$$4$$$ chizhiks, and the price for one coconut be $$$3$$$ chizhiks. If the girls don't exchange with chizhiks, they will buy $$$1 + 1 = 2$$$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $$$6$$$ chizhiks, Masha will have $$$3$$$ chizhiks, and the girls will buy $$$2 + 1 = 3$$$ coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).

The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$0 \le x, y \le 10^{18}$$$, $$$1 \le z \le 10^{18}$$$) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.

Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.

NoteThe first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy $$$3 + 4 = 7$$$ coconuts.

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = bcdiv($a, $c, 0);
$e = bcdiv($b, $c, 0);
$f = bcadd($d, $e);
$g = bcadd($a, $b);
$h = bcdiv($g, $c, 0);
if($h > $f)
{
     $i = bcmod($a, $c);
     $j = bcmod($b, $c);
     print $h . " " . min(bcsub($c, $i), bcsub($c, $j));
}
else
{
     print $f . " 0";
}
?>

<?php
#1181A
[$s, $m, $c] = explode(' ', trim(fgets(STDIN)));
$nuts = bcadd(explode('.', bcdiv($s, $c))[0], explode('.', bcdiv($m, $c))[0]);
$sFree = bcmod($s, $c);
$mFree = bcmod($m, $c);
$refund = '0';
if ($sFree !== '0' && $mFree !== '0' && bcadd($sFree, $mFree) >= $c) {
    $refund = bcadd($c, bcmul(max($sFree, $mFree), '-1'));
    $nuts = bcadd($nuts, '1');
}
echo $nuts . ' ' . $refund;

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = bcdiv($a, $c, 0);
$e = bcdiv($b, $c, 0);
$f = bcadd($d, $e);
$g = bcadd($a, $b);
$h = bcdiv($g, $c, 0);
if($h > $f)
{
     $i = bcmod($a, $c);
     $j = bcmod($b, $c);
     print $h . " " . min($c - $i, $c - $j);
}
else
{
     print $f . " 0";
}
?>

<?php
list($a, $b, $c) = explode(" ", trim(fgets(STDIN)));
$d = bcdiv($a, $c, 0);
$e = bcdiv($b, $c, 0);
$f = bcadd($d, $e);
$g = bcadd($a, $b);
$h = bcdiv($g, $c, 0);
if($h > $f)
{
     $i = bcmod($a, $c);
     $j = bcmod($b, $c);
     print $h . " " . min($i, $j);
}
else
{
     print $f . " 0";
}
?>

<?php
#1181A
[$s, $m, $c] = explode(' ', trim(fgets(STDIN)));
$nuts = floor($s / $c) + floor($m / $c);
$sFree = $s % $c;
$mFree = $m % $c;
$refund = 0;
if ($sFree !== 0 && $mFree !== 0 && ($sFree + $mFree) >= $c) {
    $refund = $c - max($sFree, $mFree);
    $nuts++;
}
echo $nuts . ' ' . $refund;

<?php
#1181A
[$s, $m, $c] = explode(' ', trim(fgets(STDIN)));

$nuts = floor((float)$s / (float)$c) + floor((float)$m / (float)$c);
$sFree = bcmod($s, $c);
$mFree = bcmod($m, $c);
$refund = 0;
if ($sFree !== 0 && $mFree !== 0 && bcadd($sFree, $mFree) >= $c) {
    $refund = $c - max($sFree, $mFree);
    $nuts++;
}
echo $nuts . ' ' . $refund;


Andryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?

The first line contains the single integer n (1 ≤ n ≤ 105) — the number of sock pairs. The second line contains 2n integers x1, x2, ..., x2n (1 ≤ xi ≤ n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi. It is guaranteed that Andryusha took exactly two socks of each pair.

Print single integer — the maximum number of socks that were on the table at the same time.

NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows:   Initially the table was empty, he took out a sock from pair 2 and put it on the table.  Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table.  Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe.  Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table.  Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe.  Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe.  Thus, at most two socks were on the table at the same time.

<?php
$handle = fopen ("php://stdin","r");
fscanf($handle,"%d",$n);
$arr_temp = fgets($handle);
$arr = explode(" ",$arr_temp);
array_walk($arr,'intval');
$b=array();
$cont=0;
for ($i=0; $i < $n * 2; $i++) {
	if(count($b)>$cont)$cont=count($b);
	if(!isset($b[$arr[$i]])){
		$b[$arr[$i]]=1;
	}else{
		unset($b[$arr[$i]]);
	}
}
print $cont;

<?php
define('SUBMIT', true);
if(SUBMIT){
    $stdin = STDIN;
}else {
    $file = 'sample';
    $stdin = fopen($file, 'r');
}

$n = trim(fgets($stdin));
$ni = array_filter(explode(' ', trim(fgets($stdin))));
$max = 0;
$current = 0;

$table = [];
for($i = 0; $i < $n*2; $i++){
    if(!isset($table[$ni[$i]])){
        $current++;
        $table[$ni[$i]] = 1;
        if($current > $max){
            $max = $current;
        }
    }else{
        $current--;
    }

}
echo $max;

/**
 * I/O samples
 *
 * trim(fgets($stdin));
 * fscanf($stdin, "%d %d %d", $n, $m, $k);
 * array_filter(explode(' ', trim(fgets($stdin))));
 *
 * print();
 *
 */


You have $$$n$$$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $$$i$$$-th student skill is denoted by an integer $$$a_i$$$ (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints:  The first team should consist of students with distinct skills (i.e. all skills in the first team are unique).  The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given):  $$$[1, 2, 3]$$$, $$$[4, 4]$$$ is not a good pair of teams because sizes should be the same;  $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ is not a good pair of teams because the first team should not contain students with the same skills;  $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ is not a good pair of teams because the second team should contain students with the same skills;  $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ is a good pair of teams;  $$$[5]$$$, $$$[6]$$$ is a good pair of teams. Your task is to find the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th student. Different students can have the same skills. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$.

NoteIn the first test case of the example, it is possible to construct two teams of size $$$3$$$: the first team is $$$[1, 2, 4]$$$ and the second team is $$$[4, 4, 4]$$$. Note, that there are some other ways to construct two valid teams of size $$$3$$$.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     $c = explode(" ", trim(fgets(STDIN)));
     $d = array();
     for($y = 0; $y < $b; $y++)
     {
          $d[$c[$y]]++;
     }
     arsort($d);
     $e = reset($d);
     $f = each($d);
     $g = $f[0];
     $h = $f[1];
     if($h == 1)
     {
          print min(floor($b / 2), count($d) - 1, $h) . "\n";
     }
     elseif($h > 1)
     {
          if(count($d) > $h)
          {
               print min(floor($b / 2), count($d), $h) . "\n";
          }
          else
          {
               print min(floor($b / 2), count($d), $h - 1) . "\n";
          }
     }
}
?>

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

for($t = intval(fgets(STDIN)); $t > 0; $t--){

	$n = intval(fgets(STDIN));

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

	$counts = [];
	foreach ($a as $ai) {
		$counts[$ai]++;
	}

	$m1 = max($counts);
	$m2 = count($counts);
	if($m1 == $m2){
		$m = $m1 - 1;
	} else {
		$m = min($m1, $m2);
	}

	echo min(floor(count($a) / 2), $m) . "\n";

}

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

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

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

        $count = array_fill(0, $n + 1, 0) ;
        $total_cnt = 0 ;

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

            $count[$in_str[$i]] ++ ;
            if($count[$in_str[$i]] == 1) $total_cnt ++ ;
        }

        $ans = 0 ;
        for($i = 1; $i <= $n; $i ++)
        {
            if($count[$i] == 0) continue ;

            if($total_cnt - 1 >= $count[$i]) $ans = max($ans, $count[$i]) ;
            if($total_cnt >= $count[$i] - 1) $ans = max($ans, $count[$i] - 1) ;
            if($total_cnt <= $count[$i] - 1) $ans = max($ans, $total_cnt) ;
        }

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

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     $c = explode(" ", trim(fgets(STDIN)));
     $d = array();
     for($y = 0; $y < $b; $y++)
     {
          $d[$c[$y]]++;
     }
     arsort($d);
     $e = reset($d);
     $f = each($d);
     print min(floor($b / 2), $f[1]) . "\n";
}
?>

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     $c = explode(" ", trim(fgets(STDIN)));
     $d = array();
     for($y = 0; $y < $b; $y++)
     {
          $d[$c[$y]]++;
     }
     arsort($d);
     $e = reset($d);
     $f = each($d);
     $g = $f[0];
     $h = $f[1];
     if($h == 1)
     {
          print min(floor($b / 2), count($d) - 1, $h) . "\n";
     }
     elseif($h > 1)
     {
          if(count($d) >= $h)
          {
               print min(floor($b / 2), count($d), $h) . "\n";
          }
          else
          {
               print min(floor($b / 2), count($d), $h - 1) . "\n";
          }
     }
}
?>

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

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

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

        $count = array_fill(0, $n + 1, 0) ;
        $total_cnt = 0 ;

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

            $count[$in_str[$i]] ++ ;
            if($count[$in_str[$i]] == 1) $total_cnt ++ ;
        }

        $ans = 0 ;
        for($i = 1; $i <= $n; $i ++)
        {
            if($count[$i] == 0) continue ;

            if($total_cnt - 1 >= $count[$i]) $ans = max($ans, $count[$i]) ;
            if($total_cnt >= $count[$i] - 1) $ans = max($ans, $count[$i] - 1) ;
        }

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


On the way to school, Karen became fixated on the puzzle game on her phone!  The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500).

If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done:   row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row".  col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column".  If there are multiple optimal solutions, output any one of them.

NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:  In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:  Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.


User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.

The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds.

In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.

NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4).   A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.


Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 ≤ l ≤ i ≤ r ≤ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.

Output the only line — Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically. The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 ≤ i ≤ |a|), that ai < bi, and for any j (1 ≤ j < i) aj = bj. |a| stands for the length of string a.

4
hello
party
abefglghjdhfgj
IVan
petrsmatchwin
a


A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true:  Employee A is the immediate manager of employee B  Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?

The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager.  It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.

Print a single integer denoting the minimum number of groups that will be formed in the party.

NoteFor the first example, three groups are sufficient, for example:   Employee 1  Employees 2 and 4  Employees 3 and 5

<?php
$boss = array();

function input() {
    return rtrim(fgets(STDIN));
}

function dfs($a)
{
    global $boss;
    if ($boss[$a] == -1) return 1;
    return dfs($boss[$a]) + 1;
}

$n = input();
for ($i = 0; $i < $n; $i++)
{
    $boss[$i] = input();
    if ($boss[$i] != -1) $boss[$i]--;
}
$ret = 1;
for ($i = 0; $i < $n; $i++)
{
    $ret = max($ret, dfs($i));
}
echo "$ret\n";
?>

<?php

fscanf(STDIN, "%d",$cnt);
$j=1;
  while (fscanf(STDIN, "%d", $r)){
    $table[$j]=$r;
    $leveltable[$j]=0;
    $j++;
 }

function GradeLevels(&$leveltable,$table,$cnt,$tolevel){
    $operate = false;
    for($i=1;$i<=$cnt;$i++)
        if ($leveltable[$i]>=($tolevel-1)) {
            $leveltable[$table[$i]]=$tolevel;
            $operate = true;
        }
    return $operate;
}

$tolevel = 1;
while (GradeLevels($leveltable,$table,$cnt, $tolevel))
    $tolevel++;

echo max($leveltable);

?>

<?php

fscanf(STDIN, "%d",$cnt);
$j=1;
  while (fscanf(STDIN, "%d", $r)){
    $table[$j]=$r;
    $leveltable[$j]=0;
    $j++;
 }

function Up2head($i,$table,&$leveltable){
 $tmp=Array();
 $NextTop = $i;
 while (($NextTop!=-1)&&($leveltable[$NextTop]==0)){ //||($leveltable[$NextTop]=0)
   $tmp[] = $NextTop;
   $NextTop = $table[$NextTop];
   }
 for ($k=0;$k<count($tmp);$k++){
   $leveltable[$tmp[$k]]=$leveltable[$NextTop]+count($tmp)-$k;//+$leveltable[$NextTop];
 }
}

for ($i=1; $i<=$cnt;$i++){
  Up2head($i,$table,$leveltable);
}

echo max($leveltable);

?>

<?php

$f = fopen('php://stdin', 'r');
//$f = fopen('test.txt', 'r');
//$a = explode(" ",trim(fgets($f)));

$n = trim(fgets($f));

$a = array();
$start = array();
for($i=1;$i<=$n;$i++){
    $x = trim(fgets($f));
    $a[$i]['director'] = $x;
    $a[$x]['parents'][] = $i;

    if ($x==-1) $start[] = $i;
}

$count = 0;
$maxCount = 0;

function spusk($i,$count){

    global $a,$maxCount;
    $count++;
    $a[$i]['ves'] = $count;

    if ($count>$maxCount){
        $maxCount = $count;
    }
    if (isset($a[$i]['parents'])){
        foreach($a[$i]['parents'] as $k=>$item){
            spusk($item,$count);
        }
    }
}

spusk(-1,0);
echo $maxCount-1;
//print_r($maxCount);

<?php

for(;;){
  $n = fgets(STDIN, 4096);
  if($n === false) break;
  $n = (integer)(trim($n));

  unset($up);
  for($i=0;$i<$n;$i++){
    $k = fgets(STDIN, 4096);
    $k = (integer)(trim($k));

    $up[$i] = $k - 1;
  }

  unset($depth);

  $mx = 0;
  for($i=0;$i<$n;$i++){
    $res = dfs($i, $up, $depth);
    if($mx < $res) $mx = $res;
  }

  echo $mx."\n";
}

function dfs($now, &$up, &$depth){
  if(isset($depth[$now])) return $depth[$now];
  if($up[$now] < 0) $depth[$now] = 1;
  else              $depth[$now] = dfs($up[$now], $up, $depth)+1;
  return $depth[$now];
}

?>

<?php

fscanf(STDIN, "%d",$cnt);
$j=1;
  while (fscanf(STDIN, "%d", $r)){
    $table[$j]=$r;
    $leveltable[$j]=0;
    $j++;
 }

function Up2head($i,$table,&$leveltable){
 $tmp=Array();
 $NextTop = $i;

 while (($NextTop!=-1)){
   $tmp[] = $NextTop;
   $NextTop = $table[$NextTop];
   }

 for ($k=0;$k<count($tmp);$k++){
   $leveltable[$tmp[$k]]=count($tmp)-$k;
 }
}

for ($i=1; $i<=$cnt;$i++){
  Up2head($i,$table,$leveltable);
}

echo max($leveltable);

?>

import java.util.*;

public class Solution
{
    public static void main(String[] args)
    {
        new Solution().calc();
    }

    int[] boss;
    void calc()
    {

        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        boss = new int[n];
        for (int i = 0; i < n; i++)
        {
            boss[i] = cin.nextInt();
            if (boss[i] != -1) boss[i]--;
        }
        int ret = 1;
        for (int i = 0; i < n; i++)
        {
            ret = Math.max(ret, dfs(i));
        }
        System.out.println(ret);
    }

    int dfs(int a)
    {
        if (boss[a] == -1) return 1;
        return dfs(boss[a]) + 1;
    }
}

<?php
fscanf(STDIN, "%d",$n);
  while (fscanf(STDIN, "%d", $r)){
    $table[]=$r;
    $leveltable[]=0;
 }

function GradeLevels(&$leveltable,$table,$tolevel){
    $operate = false;
    for($i=0;$i<count($table);$i++) // посадили всех рабочих
        if ($leveltable[$i]>=($tolevel-1)) {
            $leveltable[$table[$i]]=$tolevel;
            $operate = true;
        }
    return $operate;
}

$tolevel = 1;
while (GradeLevels($leveltable,$tolevel,$tolevel)){
    $tolevel++;
}

echo $tolevel+1;

?>

<?php

$f = fopen('php://stdin', 'r');
//$f = fopen('test.txt', 'r');
//$a = explode(" ",trim(fgets($f)));

$n = trim(fgets($f));

$a = array();
$start = array();
for($i=1;$i<=$n;$i++){
    $x = trim(fgets($f));
    $a[$i]['director'] = $x;
    $a[$x]['parents'][] = $i;

    if ($x==-1) $start[] = $i;
}

$count = 0;
$maxCount = 0;

function spusk($i,$count){

    global $a,$maxCount;
    $count++;
    $a[$i]['ves'] = $count;

    if ($count>=4){
        echo 3;
        exit;
    }
    if ($count>$maxCount){
        $maxCount = $count;
    }
    if (isset($a[$i]['parents'])){
        foreach($a[$i]['parents'] as $k=>$item){
            spusk($item,$count);
        }
    }
}

spusk(-1,0);
echo $maxCount-1;
//print_r($maxCount);


You and your friend are participating in a TV show "Run For Your Prize".At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positions). You have to work as a team and collect all prizes in minimum possible time, in any order.You know that it takes exactly 1 second to move from position x to position x + 1 or x - 1, both for you and your friend. You also have trained enough to instantly pick up any prize, if its position is equal to your current position (and the same is true for your friend). Carrying prizes does not affect your speed (or your friend's speed) at all.Now you may discuss your strategy with your friend and decide who will pick up each prize. Remember that every prize must be picked up, either by you or by your friend.What is the minimum number of seconds it will take to pick up all the prizes?

The first line contains one integer n (1 ≤ n ≤ 105) — the number of prizes. The second line contains n integers a1, a2, ..., an (2 ≤ ai ≤ 106 - 1) — the positions of the prizes. No two prizes are located at the same position. Positions are given in ascending order.

Print one integer — the minimum number of seconds it will take to collect all prizes.

NoteIn the first example you take all the prizes: take the first at 1, the second at 2 and the third at 8.In the second example you take the first prize in 1 second and your friend takes the other in 5 seconds, you do this simultaneously, so the total time is 5.


A $$$\mathbf{0}$$$-indexed array $$$a$$$ of size $$$n$$$ is called good if for all valid indices $$$i$$$ ($$$0 \le i \le n-1$$$), $$$a_i + i$$$ is a perfect square$$$^\dagger$$$.Given an integer $$$n$$$. Find a permutation$$$^\ddagger$$$ $$$p$$$ of $$$[0,1,2,\ldots,n-1]$$$ that is good or determine that no such permutation exists.$$$^\dagger$$$ An integer $$$x$$$ is said to be a perfect square if there exists an integer $$$y$$$ such that $$$x = y^2$$$.$$$^\ddagger$$$ 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 \le t \le 10^4$$$) — the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the permutation $$$p$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output $$$n$$$ distinct integers $$$p_0, p_1, \dots, p_{n-1}$$$ ($$$0 \le p_i \le n-1$$$) — the permutation $$$p$$$ — if the answer exists, and $$$-1$$$ otherwise.


A piece of paper contains an array of n integers a1, a2, ..., an. Your task is to find a number that occurs the maximum number of times in this array.However, before looking for such number, you are allowed to perform not more than k following operations — choose an arbitrary element from the array and add 1 to it. In other words, you are allowed to increase some array element by 1 no more than k times (you are allowed to increase the same element of the array multiple times).Your task is to find the maximum number of occurrences of some number in the array after performing no more than k allowed operations. If there are several such numbers, your task is to find the minimum one.

The first line contains two integers n and k (1 ≤ n ≤ 105; 0 ≤ k ≤ 109) — the number of elements in the array and the number of operations you are allowed to perform, correspondingly. The third line contains a sequence of n integers a1, a2, ..., an (|ai| ≤ 109) — the initial array. The numbers in the lines are separated by single spaces.

In a single line print two numbers — the maximum number of occurrences of some number in the array after at most k allowed operations are performed, and the minimum number that reaches the given maximum. Separate the printed numbers by whitespaces.

NoteIn the first sample your task is to increase the second element of the array once and increase the fifth element of the array twice. Thus, we get sequence 6, 4, 4, 0, 4, where number 4 occurs 3 times.In the second sample you don't need to perform a single operation or increase each element by one. If we do nothing, we get array 5, 5, 5, if we increase each by one, we get 6, 6, 6. In both cases the maximum number of occurrences equals 3. So we should do nothing, as number 5 is less than number 6.In the third sample we should increase the second array element once and the fifth element once. Thus, we get sequence 3, 2, 2, 2, 2, where number 2 occurs 4 times.

<?php
$line=explode(" ",fgets(STDIN));
$n=(int)$line[0];
$k=(int)$line[1];
$a=array();
$line=explode(" ",fgets(STDIN));
foreach ($line as $number) $a[count($a)]=(int)$number;
sort($a);
$j=0;
$ans=0;
$ansn=0;
$used=0;
for ($i=0;$i<$n;$i++)
{
	$used+=($i-$j)*($i?$a[$i]-$a[$i-1]:0);
	while ($used>$k)
	{
		$used-=$a[$i]-$a[$j];
		$j++;
	}
	if ($i-$j+1>$ans)
	{
		$ans=$i-$j+1;
		$ansn=$a[$i];
	}
}
echo "$ans $ansn";
?>