A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence $$$s$$$ and an integer number $$$k$$$. Your task is to find a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$.It is guaranteed that such sequence always exists.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 2 \cdot 10^5$$$, both $$$n$$$ and $$$k$$$ are even) — the length of $$$s$$$ and the length of the sequence you are asked to find. The second line is a string $$$s$$$ — regular bracket sequence of length $$$n$$$.

Print a single string — a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$. It is guaranteed that such sequence always exists.


There are $$$n$$$ athletes in front of you. Athletes are numbered from $$$1$$$ to $$$n$$$ from left to right. You know the strength of each athlete — the athlete number $$$i$$$ has the strength $$$s_i$$$.You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.You want the strongest athlete from the first team to differ as little as possible from the weakest athlete from the second team. Formally, you want to split the athletes into two teams $$$A$$$ and $$$B$$$ so that the value $$$|\max(A) - \min(B)|$$$ is as small as possible, where $$$\max(A)$$$ is the maximum strength of an athlete from team $$$A$$$, and $$$\min(B)$$$ is the minimum strength of an athlete from team $$$B$$$.For example, if $$$n=5$$$ and the strength of the athletes is $$$s=[3, 1, 2, 6, 4]$$$, then one of the possible split into teams is:   first team: $$$A = [1, 2, 4]$$$,  second team: $$$B = [3, 6]$$$. In this case, the value $$$|\max(A) - \min(B)|$$$ will be equal to $$$|4-3|=1$$$. This example illustrates one of the ways of optimal split into two teams.Print the minimum value $$$|\max(A) - \min(B)|$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case consists of two lines.  The first line contains positive integer $$$n$$$ ($$$2 \le n \le 50$$$) — number of athletes.  The second line contains $$$n$$$ positive integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le 1000$$$), where $$$s_i$$$ — is the strength of the $$$i$$$-th athlete. Please note that $$$s$$$ values may not be distinct.

For each test case print one integer — the minimum value of $$$|\max(A) - \min(B)|$$$ with the optimal split of all athletes into two teams. Each of the athletes must be a member of exactly one of the two teams.

NoteThe first test case was explained in the statement. In the second test case, one of the optimal splits is $$$A=[2, 1]$$$, $$$B=[3, 2, 4, 3]$$$, so the answer is $$$|2-2|=0$$$.

<?php
function inputInt($sys){
    fscanf($sys,"%d",$n);
    return $n;
}
function inputArray($sys){
    fscanf($sys, "%[^\n]", $tempA);
    $arr = array_map('intval', preg_split('/ /', $tempA, -1, PREG_SPLIT_NO_EMPTY));
    return $arr;
}

$stdin = fopen('php://stdin', 'r');
$T=inputInt($stdin);
function solve($sys){
    $n=inputInt($sys);
    $arr=inputArray($sys);
    sort($arr);
    $min=1e9;
    for ($i=1;$i<$n;++$i){
           $min=min($arr[$i]-$arr[$i-1],$min);
    }
    echo $min."\n";
}
while ($T--){
    solve($stdin);
}


The letters shop showcase is a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters. As the name tells, letters are sold in the shop.Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string $$$s$$$.There are $$$m$$$ friends, the $$$i$$$-th of them is named $$$t_i$$$. Each of them is planning to estimate the following value: how many letters (the length of the shortest prefix) would s/he need to buy if s/he wanted to construct her/his name of bought letters. The name can be constructed if each letter is presented in the equal or greater amount.  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="arya" $$$5$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="harry" $$$6$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="ray" $$$5$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="r" $$$2$$$ letters have to be bought ("arrayhead").  For example, for $$$s$$$="arrayhead" and $$$t_i$$$="areahydra" all $$$9$$$ letters have to be bought ("arrayhead"). It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.Note that the values for friends are independent, friends are only estimating them but not actually buying the letters.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of showcase string $$$s$$$. The second line contains string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains one integer $$$m$$$ ($$$1 \le m \le 5 \cdot 10^4$$$) — the number of friends. The $$$i$$$-th of the next $$$m$$$ lines contains $$$t_i$$$ ($$$1 \le |t_i| \le 2 \cdot 10^5$$$) — the name of the $$$i$$$-th friend. It is guaranteed that $$$\sum \limits_{i=1}^m |t_i| \le 2 \cdot 10^5$$$.

For each friend print the length of the shortest prefix of letters from $$$s$$$ s/he would need to buy to be able to construct her/his name of them. The name can be constructed if each letter is presented in the equal or greater amount. It is guaranteed that every friend can construct her/his name using the letters from the string $$$s$$$.

9
arrayhead
5
arya
harry
ray
r
areahydra

<?php
#1187A
$n = (int)trim(fgets(STDIN));
$str = trim(fgets(STDIN));
$m = (int)trim(fgets(STDIN));
$posAll = [];
for ($i = 0; $i < $n; $i++) {
    $posAll[$str[$i]][] = $i;
}
while ($m--) {
    $name = trim(fgets(STDIN));
    $max = 0;
    $nameLength = strlen($name);
    $pos = [];
    for ($i = 0; $i < $nameLength; $i++) {
        $letter = $name[$i];
        $p = $pos[$letter] ?? 0;
        $pos[$letter] = $p + 1;
        $max = max($max, $posAll[$letter][$p]);
    }
    echo ($max + 1) . PHP_EOL;
}

<?php
#1187A
$n = (int)trim(fgets(STDIN));
$str = trim(fgets(STDIN));
$n = (int)trim(fgets(STDIN));
while ($n--) {
    $name = trim(fgets(STDIN));
    $max = 0;
    $nameLength = strlen($name);
    $pos = [];
    for ($i = 0; $i < $nameLength; $i++) {
        $letter = $name[$i];
        if (!isset($pos[$letter])) {
            $pos[$letter] = strpos($str, $letter);
            $max = max($max, $pos[$letter]);
        }
    }
    echo ($max + 1) . PHP_EOL;
}


Snark and Philip are preparing the problemset for the upcoming pre-qualification round for semi-quarter-finals. They have a bank of n problems, and they want to select any non-empty subset of it as a problemset.k experienced teams are participating in the contest. Some of these teams already know some of the problems. To make the contest interesting for them, each of the teams should know at most half of the selected problems.Determine if Snark and Philip can make an interesting problemset!

The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 4) — the number of problems and the number of experienced teams. Each of the next n lines contains k integers, each equal to 0 or 1. The j-th number in the i-th line is 1 if j-th team knows i-th problem and 0 otherwise.

Print "YES" (quotes for clarity), if it is possible to make an interesting problemset, and "NO" otherwise. You can print each character either upper- or lowercase ("YeS" and "yes" are valid when the answer is "YES").

NoteIn the first example you can't make any interesting problemset, because the first team knows all problems.In the second example you can choose the first and the third problems.


You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the display one position to the right (the last digit becomes the first one). For example, if the display is currently showing number 579, then if we push the first button, the display will show 680, and if after that we push the second button, the display will show 068.You know that the lock will open if the display is showing the smallest possible number that can be obtained by pushing the buttons in some order. The leading zeros are ignored while comparing numbers. Now your task is to find the desired number.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of digits on the display. The second line contains n digits — the initial state of the display.

Print a single line containing n digits — the desired state of the display containing the smallest possible number.


You find yourself on an unusual crossroad with a weird traffic light. That traffic light has three possible colors: red (r), yellow (y), green (g). It is known that the traffic light repeats its colors every $$$n$$$ seconds and at the $$$i$$$-th second the color $$$s_i$$$ is on.That way, the order of the colors is described by a string. For example, if $$$s=$$$"rggry", then the traffic light works as the following: red-green-green-red-yellow-red-green-green-red-yellow- ... and so on.More formally, you are given a string $$$s_1, s_2, \ldots, s_n$$$ of length $$$n$$$. At the first second the color $$$s_1$$$ is on, at the second — $$$s_2$$$, ..., at the $$$n$$$-th second the color $$$s_n$$$ is on, at the $$$n + 1$$$-st second the color $$$s_1$$$ is on and so on.You need to cross the road and that can only be done when the green color is on. You know which color is on the traffic light at the moment, but you don't know the current moment of time. You need to find the minimum amount of time in which you are guaranteed to cross the road.You can assume that you cross the road immediately. For example, with $$$s=$$$"rggry" and the current color r there are two options: either the green color will be on after $$$1$$$ second, or after $$$3$$$. That way, the answer is equal to $$$3$$$ — that is the number of seconds that we are guaranteed to cross the road, if the current color is r.

The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 10^4$$$) — the number of test cases. Then the description of the test cases follows. The first line of each test case contains an integer $$$n$$$ and a symbol $$$c$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$c$$$ is one of allowed traffic light colors r, y or g)— the length of the string $$$s$$$ and the current color of the traffic light.  The second line of each test case contains a string $$$s$$$ of the length $$$n$$$, consisting of the letters r, y and g. It is guaranteed that the symbol g is in the string $$$s$$$ and the symbol $$$c$$$ is in the string $$$s$$$.  It is guaranteed, that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case output the minimal number of second in which you are guaranteed to cross the road.

6

5 r

rggry

1 g

g

3 r

rrg

5 y

yrrgy

7 r

rgrgyrg

9 y

rrrgyyygy

NoteThe first test case is explained in the statement.In the second test case the green color is on so you can cross the road immediately. In the third test case, if the red color was on at the second second, then we would wait for the green color for one second, and if the red light was on at the first second, then we would wait for the green light for two seconds.In the fourth test case the longest we would wait for the green color is if we wait for it starting from the fifth second.

<?php
//[$n,$m] = array_map('intval', explode(' ', trim(fgets(STDIN))));
[$t] = array_map('intval', explode(' ', trim(fgets(STDIN))));
//$a = array_map('intval', explode(' ', trim(fgets(STDIN))));
//[$s,$t] = explode(' ', trim(fgets(STDIN)));
//[$s] = explode(' ', trim(fgets(STDIN)));
//$s = explode(' ', trim(fgets(STDIN)));
//function decr($v){return --$v;}
//$alpha='abcdefghijklmnopqrstuvwxyz';
//$mod=1000000009;
//$mod=1000000007;
//$mod=998244353;
//$a=[];
//$b=[];
for($i=0;$i<$t;$i++){
    [$n, $c] = explode(' ', trim(fgets(STDIN)));
    [$s] = explode(' ', trim(fgets(STDIN)));
    if($c == "g") {
        $ans[] = 0;
        continue;
    }
    $n = intval($n);
    $gpos = [];
    $cpos = [];
    for($j=0;$j<$n*2;$j++){
        if($s[$j%$n]=="g") $gpos[] = $j+1;
    }
    for($j=0;$j<$n;$j++){
        if($s[$j%$n]==$c) $cpos[] = $j+1;
    }
    $ptn = 0;
    foreach($cpos as $p){
        $o = searchPosGT($gpos, $p);
        //echo ">>". ($gpos[$o]-$p);
        //echo PHP_EOL;
        $ptn = max($ptn, $gpos[$o]-$p);
    }
    //echo "--".PHP_EOL;
    $ans[] = $ptn;
}
echo implode(PHP_EOL,$ans);

  // $arrayの中で$xより大きい値を持つ最初の位置を返す
  // 存在しない場合は-1
  // $arrayは昇順にソートされている前提
  function searchPosGT(&$a, $x){
    $ok=count($a);
    $ng=-1;
    if($ng === 0) return -1;
    while($ok-$ng > 1){
      $m=($ng+$ok)>>1;
      //echo "m:".$m." ok:".$ok." ng:".$ng." a:".$a[$m]." x:".$x.PHP_EOL;
      if($a[$m] > $x) $ok = $m;
      else $ng = $m;
    }
    if($ok === count($a)) return -1;
    return $ok;
  }


Gildong is playing a video game called Block Adventure. In Block Adventure, there are $$$n$$$ columns of blocks in a row, and the columns are numbered from $$$1$$$ to $$$n$$$. All blocks have equal heights. The height of the $$$i$$$-th column is represented as $$$h_i$$$, which is the number of blocks stacked in the $$$i$$$-th column.Gildong plays the game as a character that can stand only on the top of the columns. At the beginning, the character is standing on the top of the $$$1$$$-st column. The goal of the game is to move the character to the top of the $$$n$$$-th column.The character also has a bag that can hold infinitely many blocks. When the character is on the top of the $$$i$$$-th column, Gildong can take one of the following three actions as many times as he wants:   if there is at least one block on the column, remove one block from the top of the $$$i$$$-th column and put it in the bag;  if there is at least one block in the bag, take one block out of the bag and place it on the top of the $$$i$$$-th column;  if $$$i < n$$$ and $$$|h_i - h_{i+1}| \le k$$$, move the character to the top of the $$$i+1$$$-st column. $$$k$$$ is a non-negative integer given at the beginning of the game. Note that it is only possible to move to the next column. In actions of the first two types the character remains in the $$$i$$$-th column, and the value $$$h_i$$$ changes.The character initially has $$$m$$$ blocks in the bag. Gildong wants to know if it is possible to win the game. Help Gildong find the answer to his question.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le 10^6$$$, $$$0 \le k \le 10^6$$$) — the number of columns in the game, the number of blocks in the character's bag at the beginning, and the non-negative integer $$$k$$$ described in the statement. The second line of each test case contains $$$n$$$ integers. The $$$i$$$-th integer is $$$h_i$$$ ($$$0 \le h_i \le 10^6$$$), the initial height of the $$$i$$$-th column.

For each test case, print "YES" if it is possible to win the game. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can take one block from the $$$1$$$-st column, move to the $$$2$$$-nd column, put the block on the $$$2$$$-nd column, then move to the $$$3$$$-rd column.In the second case, Gildong has to put the block in his bag on the $$$1$$$-st column to get to the $$$2$$$-nd column. But it is impossible to get to the $$$3$$$-rd column because $$$|h_2 - h_3| = 3 > k$$$ and there is no way to decrease the gap.In the fifth case, the character is already on the $$$n$$$-th column from the start so the game is won instantly.

<?php
list($p) = explode(' ', trim(fgets(STDIN)));
for ($i = 0; $i < $p; $i++){
    list($n,$m,$k) = explode(' ', trim(fgets(STDIN)));
    $aArray = [];
    $aArray = explode(' ', trim(fgets(STDIN)));
    $c = $m;
    $bFlag = true;
    for($j = 0; $j < $n - 1; $j++){
        $c += $aArray[$j] - max(($aArray[$j + 1] - $k),0);
        if($c < 0){
            $bFlag = false;
        }
    }

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

}


After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size $$$n$$$. Let's call them $$$a$$$ and $$$b$$$.Note that a permutation of $$$n$$$ elements is a sequence of numbers $$$a_1, a_2, \ldots, a_n$$$, in which every number from $$$1$$$ to $$$n$$$ appears exactly once. The message can be decoded by an arrangement of sequence $$$a$$$ and $$$b$$$, such that the number of matching pairs of elements between them is maximum. A pair of elements $$$a_i$$$ and $$$b_j$$$ is said to match if:   $$$i = j$$$, that is, they are at the same index.  $$$a_i = b_j$$$ His two disciples are allowed to perform the following operation any number of times:   choose a number $$$k$$$ and cyclically shift one of the permutations to the left or right $$$k$$$ times. A single cyclic shift to the left on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_2, c_2:=c_3, \ldots, c_n:=c_1$$$ simultaneously. Likewise, a single cyclic shift to the right on any permutation $$$c$$$ is an operation that sets $$$c_1:=c_n, c_2:=c_1, \ldots, c_n:=c_{n-1}$$$ simultaneously.Help Ishika and Hriday find the maximum number of pairs of elements that match after performing the operation any (possibly zero) number of times.

The first line of the input contains a single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le n)$$$ — the elements of the first permutation. The third line contains $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_n$$$ $$$(1 \le b_i \le n)$$$ — the elements of the second permutation.

Print the maximum number of matching pairs of elements after performing the above operations some (possibly zero) times.

NoteFor the first case: $$$b$$$ can be shifted to the right by $$$k = 1$$$. The resulting permutations will be $$$\{1, 2, 3, 4, 5\}$$$ and $$$\{1, 2, 3, 4, 5\}$$$.For the second case: The operation is not required. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$1$$$.For the third case: $$$b$$$ can be shifted to the left by $$$k = 1$$$. The resulting permutations will be $$$\{1, 3, 2, 4\}$$$ and $$$\{2, 3, 1, 4\}$$$. Positions $$$2$$$ and $$$4$$$ have matching pairs of elements. For all possible rotations of $$$a$$$ and $$$b$$$, the number of matching pairs won't exceed $$$2$$$.

<?php
    define("MAXN", 1024) ;

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

    $arr_a = explode(" ", trim(fgets(STDIN))) ;

    $map_a = array_fill(0, $n + 1, 0) ;
    for($i = 0; $i < $n ; $i ++) $map_a[intval($arr_a[$i])] = $i ;

    $arr_b = explode(" ", trim(fgets(STDIN))) ;
    $map_b = array_fill(0, $n + 1, 0) ;

    $ans = 0 ;
    for($i = 0; $i < $n; $i ++)
    {
        $offset = ($map_a[intval($arr_b[$i])] - $i + $n)%$n ;

        $map_b[$offset] ++ ;

        $ans = max($ans, $map_b[$offset]) ;
    }

    echo $ans . "\n" ;
?>

<?php
    define("MAXN", 1024) ;

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

    $arr_a = explode(" ", trim(fgets(STDIN))) ;

    $map_a = array_fill(0, $n + 1, 0) ;
    for($i = 0; $i < $n ; $i ++) $map_a[intval($arr_a[$i])] = $i ;

    $arr_b = explode(" ", trim(fgets(STDIN))) ;
    $map_b = array_fill(0, $n + 1, 0) ;

    $ans = 0 ;
    for($i = 0; $i < $n; $i ++)
    {
        $offset = $map_a[intval($arr_b[$i])] - $i ;
        if($offset < 0) $offset += $n ;

        $map_b[$offset] ++ ;
        $ans = max($ans, $map_b[$offset]) ;
    }

    echo $ans . "\n" ;
?>


Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for $$$n$$$ last days: $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ is the price of berPhone on the day $$$i$$$.Polycarp considers the price on the day $$$i$$$ to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if $$$n=6$$$ and $$$a=[3, 9, 4, 6, 7, 5]$$$, then the number of days with a bad price is $$$3$$$ — these are days $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) and $$$5$$$ ($$$a_5=7$$$).Print the number of days with a bad price.You have to answer $$$t$$$ independent data sets.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of sets of input data in the test. Input data sets must be processed independently, one after another. Each input data set consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of days. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the price on the $$$i$$$-th day. It is guaranteed that the sum of $$$n$$$ over all data sets in the test does not exceed $$$150000$$$.

Print $$$t$$$ integers, the $$$j$$$-th of which should be equal to the number of days with a bad price in the $$$j$$$-th input data set.

<?php
$x = rtrim(fgets(STDIN));
for($i = 0; $i < $x; $i++){
    $y = rtrim(fgets(STDIN));
    $a = rtrim(fgets(STDIN));
    $arr = explode(" ",$a);
    $arr = array_reverse($arr);
    $s = $arr[0]; $z = 0;
    for ($j = 1; $j < $y; $j++){
        if ($arr[$j] > $s){
            $z++;
        }
        $s = min($s, $arr[$j]);
    }
    printf("%d\n", $z);
}
?>


The map of Berland is a rectangle of the size n × m, which consists of cells of size 1 × 1. Each cell is either land or water. The map is surrounded by the ocean. Lakes are the maximal regions of water cells, connected by sides, which are not connected with the ocean. Formally, lake is a set of water cells, such that it's possible to get from any cell of the set to any other without leaving the set and moving only to cells adjacent by the side, none of them is located on the border of the rectangle, and it's impossible to add one more water cell to the set such that it will be connected with any other cell.You task is to fill up with the earth the minimum number of water cells so that there will be exactly k lakes in Berland. Note that the initial number of lakes on the map is not less than k.

The first line of the input contains three integers n, m and k (1 ≤ n, m ≤ 50, 0 ≤ k ≤ 50) — the sizes of the map and the number of lakes which should be left on the map. The next n lines contain m characters each — the description of the map. Each of the characters is either '.' (it means that the corresponding cell is water) or '*' (it means that the corresponding cell is land). It is guaranteed that the map contain at least k lakes.

In the first line print the minimum number of cells which should be transformed from water to land.  In the next n lines print m symbols — the map after the changes. The format must strictly follow the format of the map in the input data (there is no need to print the size of the map). If there are several answers, print any of them.  It is guaranteed that the answer exists on the given data.

NoteIn the first example there are only two lakes — the first consists of the cells (2, 2) and (2, 3), the second consists of the cell (4, 3). It is profitable to cover the second lake because it is smaller. Pay attention that the area of water in the lower left corner is not a lake because this area share a border with the ocean.


The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of the remaining binary digits, written in the corresponding order (possible, with leading zeroes).The Little Elephant wants the number he is going to write on the paper to be as large as possible. Help him find the maximum number that he can obtain after deleting exactly one binary digit and print it in the binary notation.

The single line contains integer a, written in the binary notation without leading zeroes. This number contains more than 1 and at most 105 digits.

In the single line print the number that is written without leading zeroes in the binary notation — the answer to the problem.

NoteIn the first sample the best strategy is to delete the second digit. That results in number 112 = 310.In the second sample the best strategy is to delete the third or fourth digits — that results in number 110102 = 2610.

<?php
$a = str_split(trim(fgets(STDIN)));
$b = 0;
$d = $a;
for($x = 0; $x < count($d); $x++)
{
    if($a[$x] == 0)
    {
        $b = 1;
        array_splice($a, $x, 1);
        break;
    }
}
if($b == 1)
{
    $c = array_reverse($a);
    $e = 0;
    for($x = 0; $x < count($a); $x++)
    {
        $f = $c[$x] * (pow(2, $x));
        $e += $f;
    }
    $a = array_reverse($c);
    print implode("", $a);
}
else
{
    array_splice($a, -1, 1);
    $c = array_reverse($a);
    $e = 0;
    for($x = 0; $x < count($a); $x++)
    {
        $f = $c[$x] * (pow(2, $x));
        $e += $f;
    }
    $a = array_reverse($c);
    print implode("", $a);
}
?>

<?php
// Retrieve input
$stdin = fopen('php://stdin', 'r');
function g() {
	global $stdin;
	return explode(" ", trim(fgets($stdin)));
}

// Codeforces Contest 157 Div 2 Problem C
$raw = g();
$str = $raw[0];

$res = "";
for ($i = 1; $i < strlen($str); $i++) {
	if (substr($str, $i, 1) == "0") {
		$res = substr($str, 0, $i) . substr($str, $i+1, strlen($str)-$i-1);
		break;
	}
}
if ($res == "") {$res = substr($str, 0, strlen($str)-1);}

while ((substr($res, 0, 1) == "0") && (strlen($res) > 1)) {
	$res = substr($res, 1, strlen($res) - 1);
}

echo $res;

// End of submission file
// Submission by chaotic_iak
?>


A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 109) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 10000) — the encoding.

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

<?php
list($a, $b) = explode(" ", trim(fgets(STDIN)));
$c = explode(" ", trim(fgets(STDIN)));
$d = array_sum($c);
$e = $d + ($a - 1);
if($e == $b)
{
     print "YES";
}
else
{
     print "NO";
}
?>

<?php

$line1 = fgets(STDIN);
$line2 = fgets(STDIN);

list($n, $x) = explode(' ', $line1); // n := number of segments; x := length of crossword
$encoding = explode(' ', $line2); // encoding of crossword

$sumOfSegments = array_sum($encoding);

if ($sumOfSegments == $x - $n + 1) {
    echo 'YES';
} else {
    echo 'NO';
}


In this problem you will have to help Berland army with organizing their command delivery system.There are $$$n$$$ officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer $$$a$$$ is the direct superior of officer $$$b$$$, then we also can say that officer $$$b$$$ is a direct subordinate of officer $$$a$$$.Officer $$$x$$$ is considered to be a subordinate (direct or indirect) of officer $$$y$$$ if one of the following conditions holds:  officer $$$y$$$ is the direct superior of officer $$$x$$$;  the direct superior of officer $$$x$$$ is a subordinate of officer $$$y$$$. For example, on the picture below the subordinates of the officer $$$3$$$ are: $$$5, 6, 7, 8, 9$$$.The structure of Berland army is organized in such a way that every officer, except for the commander, is a subordinate of the commander of the army.Formally, let's represent Berland army as a tree consisting of $$$n$$$ vertices, in which vertex $$$u$$$ corresponds to officer $$$u$$$. The parent of vertex $$$u$$$ corresponds to the direct superior of officer $$$u$$$. The root (which has index $$$1$$$) corresponds to the commander of the army.Berland War Ministry has ordered you to give answers on $$$q$$$ queries, the $$$i$$$-th query is given as $$$(u_i, k_i)$$$, where $$$u_i$$$ is some officer, and $$$k_i$$$ is a positive integer.To process the $$$i$$$-th query imagine how a command from $$$u_i$$$ spreads to the subordinates of $$$u_i$$$. Typical DFS (depth first search) algorithm is used here.Suppose the current officer is $$$a$$$ and he spreads a command. Officer $$$a$$$ chooses $$$b$$$ — one of his direct subordinates (i.e. a child in the tree) who has not received this command yet. If there are many such direct subordinates, then $$$a$$$ chooses the one having minimal index. Officer $$$a$$$ gives a command to officer $$$b$$$. Afterwards, $$$b$$$ uses exactly the same algorithm to spread the command to its subtree. After $$$b$$$ finishes spreading the command, officer $$$a$$$ chooses the next direct subordinate again (using the same strategy). When officer $$$a$$$ cannot choose any direct subordinate who still hasn't received this command, officer $$$a$$$ finishes spreading the command.Let's look at the following example:  If officer $$$1$$$ spreads a command, officers receive it in the following order: $$$[1, 2, 3, 5 ,6, 8, 7, 9, 4]$$$.If officer $$$3$$$ spreads a command, officers receive it in the following order: $$$[3, 5, 6, 8, 7, 9]$$$.If officer $$$7$$$ spreads a command, officers receive it in the following order: $$$[7, 9]$$$.If officer $$$9$$$ spreads a command, officers receive it in the following order: $$$[9]$$$.To answer the $$$i$$$-th query $$$(u_i, k_i)$$$, construct a sequence which describes the order in which officers will receive the command if the $$$u_i$$$-th officer spreads it. Return the $$$k_i$$$-th element of the constructed list or -1 if there are fewer than $$$k_i$$$ elements in it.You should process queries independently. A query doesn't affect the following queries.

The first line of the input contains two integers $$$n$$$ and $$$q$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le q \le 2 \cdot 10^5$$$) — the number of officers in Berland army and the number of queries. The second line of the input contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_n$$$ ($$$1 \le p_i < i$$$), where $$$p_i$$$ is the index of the direct superior of the officer having the index $$$i$$$. The commander has index $$$1$$$ and doesn't have any superiors. The next $$$q$$$ lines describe the queries. The $$$i$$$-th query is given as a pair ($$$u_i, k_i$$$) ($$$1 \le u_i, k_i \le n$$$), where $$$u_i$$$ is the index of the officer which starts spreading a command, and $$$k_i$$$ is the index of the required officer in the command spreading sequence.

Print $$$q$$$ numbers, where the $$$i$$$-th number is the officer at the position $$$k_i$$$ in the list which describes the order in which officers will receive the command if it starts spreading from officer $$$u_i$$$. Print "-1" if the number of officers which receive the command is less than $$$k_i$$$. You should process queries independently. They do not affect each other.

<?php
fscanf(STDIN,"%d %d",$n,$q);
$superior_index = fgets(STDIN);
$superior_index = explode(' ',trim($superior_index));
$dfs_id = 0;
$left_id = array();
$right_id = array();
$edge = array();
$value_map = array();
for($i = 0;$i <= $n-2;$i++){
    $id = (int)$superior_index[$i];
    if(!isset($edge[$id])){
      $edge[$id] = array();
    }
    array_push($edge[$id],$i+2);
}
dfs(1);
while($q)
{
  $q--;
  fscanf(STDIN,"%d %d",$u,$k);
  $k--;
  $id = $left_id[$u] + $k;
  if($id > $right_id[$u])
    echo "-1\n";
  else echo "$value_map[$id]\n";
}
function dfs($node){
  global $dfs_id;
  global $edge;
  global $left_id;
  global $right_id;
  global $value_map;
    $left_id[$node] = ++$dfs_id;
    $value_map[$dfs_id] = $node;
    //var_dump($node);
    if(isset($edge[$node])){
      $child_count = count($edge[$node]);
      for($i = 0;$i < $child_count;$i++){
        dfs($edge[$node][$i]);
      }
    }
    $right_id[$node] = $dfs_id;
}


Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:  First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.  Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!

The first line of the input contains integer n (1 ≤ n ≤ 105) — the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi — the coordinates of the i-th alarm clock (0 ≤ xi, yi ≤ 100). Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.

In a single line print a single integer — the minimum number of segments Inna will have to draw if she acts optimally.

NoteIn the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game.

<?php
$a = trim(fgets(STDIN));
$d = array();
$e = array();
for($x = 1; $x <= $a; $x++)
{
    list($b, $c) = explode(" ", trim(fgets(STDIN)));
    array_push($d, $b);
    array_push($e, $c);
}
$f = array_unique($d);
$g = array_unique($e);
print min(count($f), count($g));
?>

<?php
//define('STDIN', fopen('input.txt', 'r'));
$countIteration = trim(fgets(STDIN));

$xArr = []; $yArr = [];
for ($i = 1; $i <= $countIteration; $i++) {
	list($x, $y) = explode(' ', trim(fgets(STDIN)));
	$xArr[(int)$x]++;
	$yArr[(int)$y]++;
}
echo( min( count($xArr), count($yArr) ) );
fclose(STDIN);
?>

<?php
$sec=[];
$first = [];
while ($input = fgets(STDIN))
{
	if ($input==='' || strpos($input,' ')=== false)
	{
		continue;
	}
	$r = explode(' ', $input);
	$first[$r[0]] = true;
	$sec[$r[1]] = true;

}
fwrite(STDOUT,min(count($first),count($sec)));

<?php
error_reporting("off");
//390A: Inna and Alarm Clock
$n = trim(fgets(STDIN));
$x = array();
$y = array();
for ($i = 0; $i < $n; $i++) {
	list($x[], $y[]) = explode(" ", trim(fgets(STDIN)));
}
$xdis = count(array_count_values($x));
$ydis = count(array_count_values($y));
if ($xdis <= $ydis) {
	echo $xdis;
} else {
	echo $ydis;
}
?>

<?php
//define('STDIN', fopen('input.txt', 'r'));
$fStr = fgets(STDIN);

$xArr = []; $yArr = [];
while (!feof(STDIN)) {
	list($x, $y) = explode(' ', trim(fgets(STDIN)));
	$xArr[(int)$x]++;
	$yArr[(int)$y]++;
}
echo( min( count($xArr), count($yArr) ) );
fclose(STDIN);
?>

<?php
$input = fgets(STDIN);
array_shift($input);
array_pop($input);
$first = [];
foreach ($input as $item)
{
	$r = explode(' ', $item);
	$first[$r[0]] = true;
}
fwrite(STDOUT,count($first));

<?php

$first = [];
while ($input = fgets(STDIN))
{
	if ($input==='' || strpos($input,' ')=== false)
	{
		continue;
	}
	$r = explode(' ', $input);
	$first[$r[0]] = true;

}
fwrite(STDOUT,count($first));


Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The only line of each test case contains a prime number $$$n$$$ ($$$2 \leq n \leq 10^5$$$).

For each test case, output a line containing a prime number $$$m$$$ ($$$2 \leq m \leq 10^5$$$) such that $$$n + m$$$ is not prime. It can be proven that under the constraints of the problem, such $$$m$$$ always exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case, $$$m = 2$$$, which is prime, and $$$n + m = 7 + 2 = 9$$$, which is not prime.In the second test case, $$$m = 7$$$, which is prime, and $$$n + m = 2 + 7 = 9$$$, which is not prime.In the third test case, $$$m = 47837$$$, which is prime, and $$$n + m = 75619 + 47837 = 123456$$$, which is not prime.

<?php
    $test_case = readline();
    while($test_case--){
        echo readline() . PHP_EOL;
    }

<?php

$t = intval(trim(fgets(STDIN)));

for ($index = 0; $index < $t; $index++)
{
	echo(intval(trim(fgets(STDIN))) . PHP_EOL);
}


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$) — the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).

NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     $b = trim(fgets(STDIN));
     $c = explode(" ", trim(fgets(STDIN)));
     $d = 0;
     for($y = 1; $y < $b; $y++)
     {
          if($c[$y - 1] > $c[$y])
          {
               $d = 1;
               break;
          }
     }
     if($d == 0)
     {
          print "NO\n";
     }
     else
     {
          print "YES\n";
     }
}
?>


There are $$$n$$$ boxers, the weight of the $$$i$$$-th boxer is $$$a_i$$$. Each of them can change the weight by no more than $$$1$$$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).Write a program that for given current values $$$a_i$$$ will find the maximum possible number of boxers in a team.It is possible that after some change the weight of some boxer is $$$150001$$$ (but no more).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of boxers. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le 150000$$$) is the weight of the $$$i$$$-th boxer.

Print a single integer — the maximum possible number of people in a team.

NoteIn the first example, boxers should not change their weights — you can just make a team out of all of them.In the second example, one boxer with a weight of $$$1$$$ can be increased by one (get the weight of $$$2$$$), one boxer with a weight of $$$4$$$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $$$3$$$ and $$$5$$$, respectively). Thus, you can get a team consisting of boxers with weights of $$$5, 4, 3, 2, 1$$$.


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

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

<?php

//class Room {
//
//    public $h, $len;
//
//    public function __construct($a, $b, $h) {
//        $this->h = $h;
//        $this->len = 2 * ($a + $b);
//    }
//
//}
//
//class Page {
//
//    public $a, $b, $p;
//
//    public function __construct($a, $b, $p) {
//        $this->a = $a;
//        $this->b = $b;
//        $this->p = $p;
//    }
//
//}
//
//function getPrice($room, $page) {
//    $piece = (int)($page -> a / $room->h);
//    if($piece<=0)
//        return 99999999;
//    $wide = $piece * $page -> b;
//
//    $yu_len = $room->len % $wide;
//    $rolls = (int)($room->len / $wide) + ($yu_len != 0 ? 1 : 0);
//    return $rolls * $page->p;
//}
//
//$room = array();
//$page = array();
$fr = fopen("php://stdin", "r");
$n = (int) fgets($fr);
$arr = fgets($fr);
fclose($fr);
$arr = explode(' ', $arr);
$ary = array();

foreach ($arr as $value) {
    $value2=(int)$value;
    $ary[$value2] = 1;
}
$cnt = 0;
for ($i = 1; $i <= $n; ++$i) {
    if ($ary[$i] == 1){
//        echo "haha";
        $cnt++;
    }
}
echo $n-$cnt;

//
//for ($i = 0; $i < $rooms; ++$i) {
//    fscanf(STDIN, "%d%d%d", $a, $b, $h);
//    array_push($room, new Room($a, $b, $h));
//}
//
//fscanf(STDIN, "%d", $pages);
//for ($i = 0; $i < $pages; ++$i) {
//    fscanf(STDIN, "%d%d%d", $a, $b, $p);
//    array_push($page, new Page($a, $b, $p));
//}
//
//$sum=0;
//
//foreach ($room as $rm) {
//    $min=99999999;
//    foreach ($page as $pg) {
//        $price=getPrice($rm, $pg);
//        if($price<$min)
//            $min=$price;
//    }
//    $sum+=$min;
//}
//echo $sum;
//
//usort($a, 'cmp');
//$b = Array();
//foreach ($a as $ai) {
//    $l = 0;
//    $r = count($b);
//    while ($l < $r) {
//        $m = ($l + $r) / 2;
//        if ($ai->h > $b[$m]->h) {
//            $l = $m + 1;
//        } else {
//            $r = $m;
//        }
//    }
//    $ai->p = ($r == 0 ? NULL : $b[$r - 1]);
//    $b[$r] = $ai;
//}
//
//echo count($b) . "\n";
//if (count($b) > 0) {
//    $c = Array();
//    for ($p = array_pop($b); $p != NULL; $p = $p->p) {
//        array_unshift($c, $p->i);
//    }
//    print implode($c, ' ') . "\n";
//}
?>

<?php
$fr = fopen("php://stdin", "r");
$n = (int) fgets($fr);
$arr = fgets($fr);
fclose($fr);
$arr = explode(' ', $arr);
$ary = array();

foreach ($arr as $value) {
    $value2=(int)$value;
    $ary[$value2] = 1;
}
$cnt = 0;
for ($i = 1; $i <= $n; ++$i) {
    if ($ary[$i] == 1)
        $cnt++;
}
echo $n-$cnt;

<?php
function lol($a,$i,$n, $s){
    $i++;
     if (!(isset($a[$i])))  return $s;
  if ($n+0.5<$a[$i]) $s++;
  else
  if ($a[$i]==$a[$i+1])  $s++;
    return lol($a, $i, $n, $s);
}
list($n)=explode(" ",trim(fgets(STDIN)));
$a=explode(" ",trim(fgets(STDIN)));
sort($a);
print lol($a, -1, $n,0);
?>

<?php

//class Room {
//
//    public $h, $len;
//
//    public function __construct($a, $b, $h) {
//        $this->h = $h;
//        $this->len = 2 * ($a + $b);
//    }
//
//}
//
//class Page {
//
//    public $a, $b, $p;
//
//    public function __construct($a, $b, $p) {
//        $this->a = $a;
//        $this->b = $b;
//        $this->p = $p;
//    }
//
//}
//
//function getPrice($room, $page) {
//    $piece = (int)($page -> a / $room->h);
//    if($piece<=0)
//        return 99999999;
//    $wide = $piece * $page -> b;
//
//    $yu_len = $room->len % $wide;
//    $rolls = (int)($room->len / $wide) + ($yu_len != 0 ? 1 : 0);
//    return $rolls * $page->p;
//}
//
//$room = array();
//$page = array();
$fr = fopen("php://stdin", "r");
$n = (int) fgets($fr);
$arr = fgets($fr);
fclose($fr);
$arr = explode(' ', $arr);
$ary = array();

foreach ($arr as $value) {
    $value=(int)$value;
    $ary[$value2] = 1;
}
$cnt = 0;
for ($i = 1; $i <= $n; ++$i) {
    if ($ary[$i] == NULL){
//        echo "haha";
        $cnt++;
    }
}
echo $cnt;

//
//for ($i = 0; $i < $rooms; ++$i) {
//    fscanf(STDIN, "%d%d%d", $a, $b, $h);
//    array_push($room, new Room($a, $b, $h));
//}
//
//fscanf(STDIN, "%d", $pages);
//for ($i = 0; $i < $pages; ++$i) {
//    fscanf(STDIN, "%d%d%d", $a, $b, $p);
//    array_push($page, new Page($a, $b, $p));
//}
//
//$sum=0;
//
//foreach ($room as $rm) {
//    $min=99999999;
//    foreach ($page as $pg) {
//        $price=getPrice($rm, $pg);
//        if($price<$min)
//            $min=$price;
//    }
//    $sum+=$min;
//}
//echo $sum;
//
//usort($a, 'cmp');
//$b = Array();
//foreach ($a as $ai) {
//    $l = 0;
//    $r = count($b);
//    while ($l < $r) {
//        $m = ($l + $r) / 2;
//        if ($ai->h > $b[$m]->h) {
//            $l = $m + 1;
//        } else {
//            $r = $m;
//        }
//    }
//    $ai->p = ($r == 0 ? NULL : $b[$r - 1]);
//    $b[$r] = $ai;
//}
//
//echo count($b) . "\n";
//if (count($b) > 0) {
//    $c = Array();
//    for ($p = array_pop($b); $p != NULL; $p = $p->p) {
//        array_unshift($c, $p->i);
//    }
//    print implode($c, ' ') . "\n";
//}

<?php
function lol($a,$i,$n, $s){
    $i++;
     if (!(isset($a[$i])))  return $s;
  if ($n+0.5<$a[$i]) $s++;
  else
  if ($a[$i]==$a[$i+1])  $s++;
    return lol($a, $i, $n, $s);
}
list($n)=explode(" ",fgets(STDIN));
$a=  explode (" ",fgets(STDIN));
sort($a);
print lol($a, -1, $n,0);
?>

<?php
function lol($a,$i,$n,$s){
    $i++;
     if (!(isset($a[$i])))  return $s;
  if ($n+0.5<$a[$i]) $s++;
  else
  if ($a[$i]==$a[$i+1])  $s++;
    return lol($a, $i, $n, $s);
}
list($n)=explode(" ",fgets(STDIN));
$a=  explode (" ",fgets(STDIN));
sort($a);
print lol($a, -1, $n,0);
?>


Sasha and Dima want to buy two $$$n$$$-tier cakes. Each cake should consist of $$$n$$$ different tiers: from the size of $$$1$$$ to the size of $$$n$$$. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are $$$2 \cdot n$$$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $$$i$$$-th house you can buy a tier of the size $$$a_i$$$ ($$$1 \le a_i \le n$$$).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $$$1$$$, then $$$2$$$, then $$$3$$$ and so on up to $$$n$$$.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $$$1$$$.

The first line of the input contains an integer number $$$n$$$ — the number of tiers in each cake ($$$1 \le n \le 10^5$$$). The second line contains $$$2 \cdot n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is equal to the size of the tier, which can be bought in the $$$i$$$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $$$1$$$ to $$$n$$$ occurs in $$$a$$$ exactly two times.

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $$$n$$$ tiers in ascending order of their sizes.

NoteIn the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $$$1$$$ near the $$$1$$$-st house ($$$a_1=1$$$);  Dima goes to the house $$$2$$$;  Dima buys a tier of size $$$1$$$ near the $$$2$$$-nd house ($$$a_2=1$$$);  Sasha goes to the house $$$4$$$;  Sasha buys a tier of size $$$2$$$ near the $$$4$$$-th house ($$$a_4=2$$$);  Sasha goes to the house $$$5$$$;  Sasha buys a tier of size $$$3$$$ near the $$$5$$$-th house ($$$a_5=3$$$);  Dima goes to the house $$$3$$$;  Dima buys a tier of size $$$2$$$ near the $$$3$$$-rd house ($$$a_3=2$$$);  Dima goes to the house $$$6$$$;  Dima buys a tier of size $$$3$$$ near the $$$6$$$-th house ($$$a_6=3$$$). So, Sasha goes the distance $$$3+1=4$$$, and Dima goes the distance $$$1+1+3=5$$$. In total, they cover a distance of $$$4+5=9$$$. You can make sure that with any other sequence of actions they will walk no less distance.


Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The following $$$q$$$ lines contain queries, one per line. Each query is given as two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — the number of pages in the book and required divisor, respectively.

For each query print the answer for it — the sum of digits written down by Polycarp.

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     list($b, $c) = explode(" ", trim(fgets(STDIN)));
     $d = array();
     $e = array();
     $f = $c;
     while(TRUE)
     {
          if($f > $b)
          {
               break;
          }
          else
          {
               $f = strval($f);
               if($e[$f[strlen($f) - 1]] == 1)
               {
                    break;
               }
               else
               {
                    $d[count($d)] = $f[strlen($f) - 1];
                    $e[$f[strlen($f) - 1]] = 1;
                    $f = bcadd($f, $c);
               }
          }
     }
     $g = floor(bcdiv($b, $c));
     $g = number_format($g, 0, ".", "");
     $h = array_sum($d);
     $i = bcdiv($g, count($d));
     $j = bcmod($g, count($d));
     $k = bcmul($h, $i);
     $l = array_sum(array_slice($d, 0, $j));
     $m = bcadd($k, $l);
     print $m . "\n";
}
?>

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     list($b, $c) = explode(" ", trim(fgets(STDIN)));
     $d = array();
     $e = array();
     $f = $c;
     while(TRUE)
     {
          if($f > $b)
          {
               break;
          }
          else
          {
               $f = strval($f);
               if($e[$f[strlen($f) - 1]] == 1)
               {
                    break;
               }
               else
               {
                    $d[count($d)] = $f[strlen($f) - 1];
                    $e[$f[strlen($f) - 1]] = 1;
                    $f = bcadd($f, $c);
               }
          }
     }
     $g = floor(bcdiv($b, $c));
     $h = array_sum($d);
     $i = floor(bcdiv($g, count($d)));
     $j = bcmod($g, count($d));
     $k = bcmul($h, $i);
     $l = array_sum(array_slice($d, 0, $j));
     $m = bcadd($k, $l);
     print $m . "\n";
}
?>

<?php
$a = trim(fgets(STDIN));
for($x = 1; $x <= $a; $x++)
{
     list($b, $c) = explode(" ", trim(fgets(STDIN)));
     $d = array();
     $e = array();
     $f = $c;
     while(TRUE)
     {
          if($f > $b)
          {
               break;
          }
          else
          {
               $f = strval($f);
               if($e[$f[strlen($f) - 1]] == 1)
               {
                    break;
               }
               else
               {
                    $d[count($d)] = $f[strlen($f) - 1];
                    $e[$f[strlen($f) - 1]] = 1;
                    $f += $c;
               }
          }
     }
     $g = floor(bcdiv($b, $c));
     $h = array_sum($d);
     $i = floor(bcdiv($g, count($d)));
     $j = bcmod($g, count($d));
     $k = bcmul($h, $i);
     $l = array_sum(array_slice($d, 0, $j));
     $m = bcadd($k, $l);
     print $m . "\n";
}
?>


Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1    ("[..]c."  →  ".c.") after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1    (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")

<?php
//$file = fopen('input.in', 'r');
$file = STDIN;
list($stringLength, $ruleNumber) = explode(" ", trim(fgets($file)));
$string = trim(fgets($file));
$value = f($string);

for ($i = 0; $i < $ruleNumber; $i++) {
    list($position, $letter) = explode(" ", trim(fgets($file)));
    $position--;

    if ($stringLength == 1) {
        $value = 0;
    } elseif ($position === 0 || $position == ($stringLength - 1) ) {
        if ($position === 0) {
            //first
            if ($letter == '.' && $string[$position] != '.' && $string[$position + 1] == '.') {
                $value++;
            } elseif ($letter != '.' && $string[$position] == '.' && $string[$position + 1] == '.') {
                $value--;
            }
        } elseif ($position == ($stringLength - 1)) {
            //last
            if ($letter == '.' && $string[$position] != '.' && $string[$position - 1] == '.') {
                $value++;
            } elseif ($letter != '.' && $string[$position] == '.' && $string[$position - 1] == '.') {
                $value--;
            }
        }
    } else {
        if ($letter == '.') {
            // is dot
            if ($string[$position] == '.') {
                // replaced instead of dot! so do nothing!
            } else {
                if ($string[$position + 1] == '.' && $string[$position - 1] == '.') {
                    $value += 2;
                } elseif ($string[$position + 1] != '.' && $string[$position - 1] != '.') {
                    // that is an alone dot!
                } else {
                    $value += 1;
                }
            }
        } else {
            // is a letter
            if ($string[$position] == '.') {
                if ($string[$position + 1] == '.' && $string[$position - 1] == '.') {
                    $value -= 2;
                } elseif ($string[$position + 1] != '.' && $string[$position - 1] != '.') {
                } else {
                    $value -= 1;
                }
            }
        }

    }

    echo $value . PHP_EOL;
    $string[$position] = $letter;

}
function f($string)
{
    $tempDotNumber = 0;
    $x = 0;
    $stringArray = str_split($string);
    foreach ($stringArray as $char) {
        if ($char === '.') {
            $tempDotNumber++;

        } else {
            if ($tempDotNumber) {
                $x += $tempDotNumber - 1;
            }
            $tempDotNumber = 0;
        }
    }
    if ($tempDotNumber > 1) {
        $x += $tempDotNumber - 1;
    }

    return $x;
}


Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order. Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.

<? /* BismiLahi Rahmani Rahim */ ?>

<?php

fscanf(STDIN, "%d%d%d%d", $x, $y, $a, $b);

for ($j = $b; $j <= $y; $j ++) {
  for ($i = $j + 1 >= $a ? $j+1 : $a; $i <= $x; $i ++) {
    $answer[] = array($i, $j);
  }
}
sort($answer);

printf("%d\n", count($answer));

foreach ($answer as $val) {
  printf("%d %d\n", $val[0], $val[1]);
}

?>

<? /* BismiLahi Rahmani Rahim */ ?>

<?php

fscanf(STDIN, "%d%d%d%d", $x, $y, $a, $b);

if ($a < $b) {
  $a = $b;
}
$a ++;

if ($a > $x) {
  printf("0");
  exit;
}

for ($j = $b; $j <= $y; $j ++) {
  for ($i = $j + 1 >= $a ? $j+1 : $a; $i <= $x; $i ++) {
    $answer[] = array($i, $j);
  }
}
sort($answer);

printf("%d\n", count($answer));

foreach ($answer as $val) {
  printf("%d %d\n", $val[0], $val[1]);
}

?>


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.


You are given a picture consisting of $$$n$$$ rows and $$$m$$$ columns. Rows are numbered from $$$1$$$ to $$$n$$$ from the top to the bottom, columns are numbered from $$$1$$$ to $$$m$$$ from the left to the right. Each cell is painted either black or white. You think that this picture is not interesting enough. You consider a picture to be interesting if there is at least one cross in it. A cross is represented by a pair of numbers $$$x$$$ and $$$y$$$, where $$$1 \le x \le n$$$ and $$$1 \le y \le m$$$, such that all cells in row $$$x$$$ and all cells in column $$$y$$$ are painted black.For examples, each of these pictures contain crosses:  The fourth picture contains 4 crosses: at $$$(1, 3)$$$, $$$(1, 5)$$$, $$$(3, 3)$$$ and $$$(3, 5)$$$.Following images don't contain crosses:  You have a brush and a can of black paint, so you can make this picture interesting. Each minute you may choose a white cell and paint it black.What is the minimum number of minutes you have to spend so the resulting picture contains at least one cross?You are also asked to answer multiple independent queries.

The first line contains an integer $$$q$$$ ($$$1 \le q \le 5 \cdot 10^4$$$) — the number of queries. The first line of each query contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^4$$$, $$$n \cdot m \le 4 \cdot 10^5$$$) — the number of rows and the number of columns in the picture. Each of the next $$$n$$$ lines contains $$$m$$$ characters — '.' if the cell is painted white and '*' if the cell is painted black. It is guaranteed that $$$\sum n \le 5 \cdot 10^4$$$ and $$$\sum n \cdot m \le 4 \cdot 10^5$$$.

Print $$$q$$$ lines, the $$$i$$$-th line should contain a single integer — the answer to the $$$i$$$-th query, which is the minimum number of minutes you have to spend so the resulting picture contains at least one cross.

NoteThe example contains all the pictures from above in the same order.The first 5 pictures already contain a cross, thus you don't have to paint anything.You can paint $$$(1, 3)$$$, $$$(3, 1)$$$, $$$(5, 3)$$$ and $$$(3, 5)$$$ on the $$$6$$$-th picture to get a cross in $$$(3, 3)$$$. That'll take you $$$4$$$ minutes.You can paint $$$(1, 2)$$$ on the $$$7$$$-th picture to get a cross in $$$(4, 2)$$$.You can paint $$$(2, 2)$$$ on the $$$8$$$-th picture to get a cross in $$$(2, 2)$$$. You can, for example, paint $$$(1, 3)$$$, $$$(3, 1)$$$ and $$$(3, 3)$$$ to get a cross in $$$(3, 3)$$$ but that will take you $$$3$$$ minutes instead of $$$1$$$.There are 9 possible crosses you can get in minimum time on the $$$9$$$-th picture. One of them is in $$$(1, 1)$$$: paint $$$(1, 2)$$$ and $$$(2, 1)$$$.

<?php

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

function calcTime($x, $y, $matrix)
{
    $max_row = 0;
    $row = 0;
    $max_col = 0;
    $col = 0;

    $cols = array_fill(0, $x, 0);
    $rows = array_fill(0, $y, 0);

    for ($j = 0; $j < $y; $j++) {

        $current_row = 0;

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

            if ($matrix[$i][$j] == '*') {
                $current_row++;
                $cols[$i]++;
            }
        }

        if ($current_row > $max_row) {

            $max_row = $current_row;
            $row = $j;
            $rows = [$j];
        } elseif ($current_row == $max_row) {
            $rows[] = $j;
        }
    }

    if ($cols) {
        $max_col = max($cols);
        $col = array_search($max_col, $cols);
    }

    $res = ($x - $max_col) + ($y - $max_row);
    if ($res == 0) {
        return 0;
    }

    foreach ($cols as $_c => $val) {
        if ($val == $max_col) {
            foreach ($rows as $_r) {

                if ($matrix[$_c][$_r] != '*') {
                    return $res - 1;
                }
            }
        }
    }

    return $res;
}

$n = intval(fgets($__fp));
$res1 = [];
for ($i = 0; $i < $n; $i++) {
    list($x, $y) = array_map('intval', explode(' ', trim(fgets($__fp))));
    $matrix = [];
    for ($j = 0; $j < $x; $j++) {
        $matrix[] = str_split(trim(fgets($__fp)));
    }

    $res1[] = calcTime($x, $y, $matrix);
}

fclose($__fp);

echo join(PHP_EOL, $res1);

<?php

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

function calcTime($x, $y, $matrix)
{
    $max_row = 0;
    $row = 0;
    $max_col = 0;
    $col = 0;

    $cols = array_fill(0, $x, 0);

    for ($j = 0; $j < $y; $j++) {

        $current_row = 0;

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

            if ($matrix[$i][$j] == '*') {
                $current_row++;
                $cols[$i]++;
            }
        }

        if ($current_row > $max_row) {
            $max_row = $current_row;
            $row = $j;
        }
    }

    if ($cols) {
        $max_col = max($cols);
        $col = array_search($max_col, $cols);
    }
    $res = ($x - $max_col) + ($y - $max_row);

//if(!isset($matrix[$row][$col] ))
//{
//    var_dump($matrix, $row, $col);exit;
//}

    if($res != 0 && $matrix[$col][$row] != '*')
    {
        $res -= 1;
    }

    return $res;

}

$n = intval(fgets($__fp));
$res1 = [];
for ($i = 0; $i < $n; $i++) {
    list($x, $y) = array_map('intval', explode(' ', trim(fgets($__fp))));
    $matrix = [];
    for ($j = 0; $j < $x; $j++)
    {
        $matrix[] = str_split(trim(fgets($__fp)));
    }

    $res1[] =  calcTime($x, $y, $matrix);
}

fclose($__fp);

echo join(PHP_EOL, $res1);

<?php

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

function calcTime($x, $y, $matrix)
{
    $max_row = 0;
    $row = 0;
    $max_col = 0;
    $col = 0;

    $cols = array_fill(0, $x, 0);

    for ($j = 0; $j < $y; $j++) {

        $current_row = 0;

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

            if ($matrix[$i][$j] == '*') {
                $current_row++;
                $cols[$i]++;
            }
        }

        if ($current_row > $max_row) {
            $max_row = $current_row;
            $row = $j;
        }
    }

    if ($cols) {
        $max_col = max($cols);
        $col = array_search($max_col, $cols);
    }

    return ($x - $max_col) + ($y - $max_row);

}

$n = intval(fgets($__fp));
$res1 = [];
for ($i = 0; $i < $n; $i++) {
    list($x, $y) = array_map('intval', explode(' ', trim(fgets($__fp))));
    $matrix = [];
    for ($j = 0; $j < $x; $j++)
    {
        $matrix[] = str_split(trim(fgets($__fp)));
    }

    $res1[] =  calcTime($x, $y, $matrix);
}

fclose($__fp);

echo join(PHP_EOL, $res1);

<?php

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

function calcTime($x, $y, $matrix)
{
    $max_row = 0;
    $row = 0;
    $max_col = 0;
    $col = 0;

    $cols = array_fill(0, $x, 0);

    for ($j = 0; $j < $y; $j++) {

        $current_row = 0;

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

            if ($matrix[$i][$j] == '*') {
                $current_row++;
                $cols[$i]++;
            }
        }

        if ($current_row > $max_row) {
            $max_row = $current_row;
            $row = $j;
        }
    }

    if ($cols) {
        $max_col = max($cols);
        $col = array_search($max_col, $cols);
    }

    return ($x - $max_col) + ($y - $max_row) - 1;

}

$n = intval(fgets($__fp));
$res1 = [];
for ($i = 0; $i < $n; $i++) {
    list($x, $y) = array_map('intval', explode(' ', trim(fgets($__fp))));
    $matrix = [];
    for ($j = 0; $j < $x; $j++)
    {
        $matrix[] = str_split(trim(fgets($__fp)));
    }

    $res1[] =  calcTime($x, $y, $matrix);
}

fclose($__fp);

echo join(PHP_EOL, $res1);

<?php

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

function calcTime($x, $y, $matrix)
{
    $max_row = 0;
    $row = 0;
    $max_col = 0;
    $col = 0;

    $cols = array_fill(0, $x, 0);

    for ($j = 0; $j < $y; $j++) {

        $current_row = 0;

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

            if ($matrix[$i][$j] == '*') {
                $current_row++;
                $cols[$i]++;
            }
        }

        if ($current_row > $max_row) {
            $max_row = $current_row;
            $row = $j;
        }
    }

    if ($cols) {
        $max_col = max($cols);
        $col = array_search($max_col, $cols);
    }

    $res = ($x - $max_col) + ($y - $max_row);
    return $res == 0 ? $res : $res - 1;

}

$n = intval(fgets($__fp));
$res1 = [];
for ($i = 0; $i < $n; $i++) {
    list($x, $y) = array_map('intval', explode(' ', trim(fgets($__fp))));
    $matrix = [];
    for ($j = 0; $j < $x; $j++)
    {
        $matrix[] = str_split(trim(fgets($__fp)));
    }

    $res1[] =  calcTime($x, $y, $matrix);
}

fclose($__fp);

echo join(PHP_EOL, $res1);


Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".


A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 105), denoting the number of banknotes. The next line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.

Output a single integer: the maximum number of banknotes Oleg can take.

NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.

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


ВКонтакте открыла второй штаб в Санкт-Петербурге! Вы не преминули возможностью сменить обстановку и решили переехать из офиса в Доме Зингера в офис на Красном мосту.Для комфортной работы вам потребуются два монитора с одинаковой высотой, чтобы изображение на них выглядело единым целым. На складе офиса на Красном мосту есть $$$n$$$ мониторов, $$$i$$$-й из них имеет ширину $$$w_i$$$ и высоту $$$h_i$$$. Любой монитор можно повернуть на 90 градусов, и тогда он будет иметь ширину $$$h_i$$$ и высоту $$$w_i$$$.Назовём неупорядоченную пару из двух различных мониторов подходящей, если можно их повернуть так, чтобы они имели одинаковую высоту. Любой из мониторов в паре можно как повернуть относительно исходной ориентации, так и не поворачивать.Подсчитайте подходящие пары мониторов.

В первой строке задано одно целое число $$$n$$$ — число мониторов на складе. В каждой из следующих $$$n$$$ строк заданы два целых числа $$$w_i$$$ и $$$h_i$$$ ($$$1 \le w_i, h_i \le 10^9$$$) — ширина и высота $$$i$$$-го монитора. Обратите внимание, что мониторы могут быть квадратными ($$$w_i = h_i$$$), а размеры разных мониторов могут совпадать. В этой версии задачи $$$2 \le n \le 10^3$$$.

Выведите число подходящих пар мониторов.

ПримечаниеВ первом примере подходящими являются пары мониторов с номерами $$$(1, 2)$$$, $$$(1, 4)$$$, $$$(1, 5)$$$, $$$(3, 4)$$$, $$$(4, 5)$$$.Во втором примере все пары мониторов — подходящие.

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

$sizes = $arr = $arrCommon = $elCount = [];
$count = 0;

$i = false;

while ($buf = trim(fgets($input))) {
    if ($i){
        $el = explode(' ', $buf);
        $buf = $el[0] > $el[1] ? $el[1].' '.$el[0] : $buf;
        $el = $el[0] > $el[1] ? [$el[1],$el[0]] : $el;

        $sizes[] = $el[0];
        $sizes[] = $el[1];

        $arr[] = $buf;

        $arrCommon[] = $el;
    }else{
        $elCount = $buf;
    }
    $i = true;
}

$lineMap = array_count_values($sizes);
$multiMap = array_count_values($arr);

foreach($arr as $k => $size){

    $pExpl = explode(' ', $size);
    if($pExpl[0] == $pExpl[1]){

        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 2;
        $multiMap[$size] = $multiMap[$size] - 1;

        $pCountAdd = $lineMap[$pExpl[0]] - $multiMap[$size];

        $step = $pCountAdd;

    }else{
        //remove itself
        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 1;
        $lineMap[$pExpl[1]] = $lineMap[$pExpl[1]] - 1;

        $multiMap[$size] = $multiMap[$size] - 1;

        $pCountAdd = $multiMap[$size];

        $sameLeft = $multiMap[$pExpl[0].' '.$pExpl[0]] ? $multiMap[$pExpl[0].' '.$pExpl[0]] : 0;
        $sameRight = $multiMap[$pExpl[1].' '.$pExpl[1]] ? $multiMap[$pExpl[1].' '.$pExpl[1]] : 0;
        $pCountAdd = ($lineMap[$pExpl[0]] + $lineMap[$pExpl[1]]) - $sameLeft - $sameRight - $pCountAdd;

        $step = $pCountAdd;

    }

    $count += $step;

}

echo $count;
?>

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

$sizes = $arr = $arrCommon = $elCount = [];
$count = 0;

$elCount = trim(fgets($input));
for ($i=0; $i < $elCount; $i++) {
    $buf = trim(fgets($input));

    $el = explode(' ', $buf);
    $buf = $el[0] > $el[1] ? $el[1].' '.$el[0] : $buf;
    $el = $el[0] > $el[1] ? [$el[1],$el[0]] : $el;

    $sizes[] = $el[0];
    $sizes[] = $el[1];

    $arr[] = $buf;

    $arrCommon[] = $el;
}

$lineMap = array_count_values($sizes);
$multiMap = array_count_values($arr);

foreach($arr as $k => $size){
    $pExpl = explode(' ', $size);

    if($pExpl[0] == $pExpl[1]){
        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 2;
        $multiMap[$size] = $multiMap[$size] - 1;

        $pCountAdd = $lineMap[$pExpl[0]] - $multiMap[$size];

        $step = $pCountAdd;
    } else {
        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 1;
        $lineMap[$pExpl[1]] = $lineMap[$pExpl[1]] - 1;

        $multiMap[$size] = $multiMap[$size] - 1;
        $pCountAdd = $multiMap[$size];

        foreach ($multiMap as $code => $map){
            if($code != $size && $map > 0){
                $exCode = explode(' ', $code);
                if($exCode[0] == $pExpl[0] || $exCode[0] == $pExpl[1] || $exCode[1] == $pExpl[0] || $exCode[1] == $pExpl[1]){
                    $pCountAdd += $map;

                }
            }
        }

        $step = $pCountAdd;
    }

    $count += $step;
}

echo $count;
?>

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

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

	$sizes = [];
	$count = 0;

    $i = false;
    while ($buf = trim(fgets($input))) {
	    if ($i){
	        $sizes[] = explode(' ', $buf);
	    }else{
	         $elCount = $buf;
	    }
	    $i = true;
    }

    if($elCount != count($sizes) || $elCount < 2 || $elCount > 1000){
        echo 0;
    }else{
        function checkPair($size, $arr){
        $c = 0;
        foreach($arr as $k => $r){
            if($size[0] == $r[0] || $size[0] == $r[1] || $size[1] == $r[0] || $size[1] == $r[1]){
                $c++;
            }
        }

        return $c;
        }

        $tmpSizes = $sizes;
        foreach($sizes as $k => $size){
            unset($tmpSizes[$k]);
            $count += checkPair($size, $tmpSizes);
        }
        echo $count;
    }

?>

<?php

$input = readInput();
$monitors = [];
foreach ($input as $params) {
    $monitors[] = $params;
}

echo findSuitablePairs($monitors);

/**
 * @param Monitor[] $monitors
 * @return int
 */
function findSuitablePairs(array $monitors): int
{
    $count = count($monitors);
    $result = 0;
    for ($i = 0; $i < $count; $i++) {
        for ($j = $i + 1; $j < $count; $j++) {
            if (isSuitable($monitors[$i], $monitors[$j])) {
                $result++;
            }
        }
    }

    return $result;
}

function isSuitable($params1, $params2): bool
{
    return $params1[0] === $params2[1]
        || $params1[1] === $params2[0]
        || $params1[0] === $params2[0]
        || $params1[1] === $params2[1];
}

function readInput()
{
    $commandsCount = trim(fgets(STDIN));
    if (empty($commandsCount)) {
        return [];
    }

    $result = [];

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

    return $result;
}

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

$sizes = $arr = $arrCommon = $elCount = [];
$count = 0;

$elCount = trim(fgets($input));
for ($i=0; $i < $elCount; $i++) {
    $buf = trim(fgets($input));

    $el = explode(' ', $buf);
    $buf = $el[0] > $el[1] ? $el[1].' '.$el[0] : $buf;
    $el = $el[0] > $el[1] ? [$el[1],$el[0]] : $el;

    $sizes[] = $el[0];
    $sizes[] = $el[1];

    $arr[] = $buf;

    $arrCommon[] = $el;
}

$lineMap = array_count_values($sizes);
$multiMap = array_count_values($arr);

foreach($arr as $k => $size){
    $pExpl = explode(' ', $size);

    if($pExpl[0] == $pExpl[1]){
        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 2;
        $multiMap[$size] = $multiMap[$size] - 1;

        $pCountAdd = $lineMap[$pExpl[0]] - $multiMap[$size];

        $step = $pCountAdd;
    } else {
        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 1;
        $lineMap[$pExpl[1]] = $lineMap[$pExpl[1]] - 1;

        $multiMap[$size] = $multiMap[$size] - 1;
        $pCountAdd = $multiMap[$size];

        foreach ($multiMap as $code => $map){
            if($code != $size && $map > 0){
                $exCode = explode(' ', $code);
                if($exCode[0] == $pExpl[0] || $exCode[0] == $pExpl[1] || $exCode[1] == $pExpl[0] || $exCode[1] == $pExpl[1]){
                    $pCountAdd += 1;

                }
            }
        }

        $step = $pCountAdd;
    }

    $count += $step;
}

echo $count;
?>

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

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

	$sizes = $arr = $arrCommon = $elCount = [];
    $count = 0;

    $i = false;

while ($buf = trim(fgets($input))) {
    if ($i){
        $el = explode(' ', $buf);
        $buf = $el[0] > $el[1] ? $el[1].' '.$el[0] : $buf;
        $el = $el[0] > $el[1] ? [$el[1],$el[0]] : $el;
        /*if($el[0] == $el[1]){
            $sizes[] = $el[0];
        }else{
            $sizes[] = $el[0];
            $sizes[] = $el[1];

        }*/

        $sizes[] = $el[0];
        $sizes[] = $el[1];

        $arr[] = $buf;

        $arrCommon[] = $el;
    }else{
        $elCount = $buf;
    }
    $i = true;
}

$lineMap = array_count_values($sizes);
$multiMap = array_count_values($arr);

foreach($arr as $k => $size){
    // $pCountW = $lineMap[$size[0]];
    // $pCountH = $lineMap[$size[1]];
    $pExpl = explode(' ', $size);
    if($pExpl[0] == $pExpl[1]){

        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 2;
        $multiMap[$size] = $multiMap[$size] - 1;

        $pCountAdd = $lineMap[$pExpl[0]] - $multiMap[$size];

        $step = $pCountAdd;

    }else{
        //remove itself
        $lineMap[$pExpl[0]] = $lineMap[$pExpl[0]] - 1;
        $lineMap[$pExpl[1]] = $lineMap[$pExpl[1]] - 1;

        $multiMap[$size] = $multiMap[$size] - 1;

        $pCountAdd = $multiMap[$size];

        foreach ($multiMap as $code => $map){
            if($code != $size && $map > 0){
                $exCode = explode(' ', $code);
                if($exCode[0] == $pExpl[0] || $exCode[0] == $pExpl[1] || $exCode[1] == $pExpl[0] || $exCode[1] == $pExpl[1]){
                    $pCountAdd += 1;

                }
            }

        }

        $step = $pCountAdd;

    }

    $count += $step;

}

echo $count;
?>

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

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

$sizes = [];
$count = 0;

$i = false;
while ($buf = trim(fgets($input))) {
    if ($i){
        $sizes[] = explode(' ', $buf);
    }else{
        $elCount = $buf;
    }
    $i = true;
}

if($elCount != count($sizes) || $elCount < 2 || $elCount > 100000){
    echo 0;
}else{

    function cmp($a, $b) {
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }

    uasort($sizes, 'cmp');

    /*echo '
';
    print_r($sizes);
    echo '
';*/

    $i = 1;
    foreach($sizes as $k => $size){
        if($size[0] == $size[1]) {
            $pair[] = $size[0];
        }else{
            $single[] = $size[0];
            $single[] = $size[1];
        }

        $i++;
    }

    $count = count($pair);

    foreach ($single as $k => $s){
        if(in_array($s, $pair)){
           // unset($single[$k]);
            $count++;
        }
    }

/*    echo '
';
    print_r($hash);
    echo '
';*/

/*    echo '
';
    print_r($pair);
    echo '
';

    echo '
';
    print_r($single);
    echo '
';*/

    foreach(array_count_values($single) as $value){
        $count+=intdiv($value,2);
    }

    echo $count;
}

<?php

$input = readInput();
$monitors = [];
foreach ($input as $params) {
    $monitors[] = new Monitor((int)$params[0], (int)$params[1]);
}

echo findSuitablePairs($monitors);

class Monitor {
    private $width;
    private $height;
    private $isMarked = false;

    public function __construct(int $width, int $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    public function width(): int
    {
        return $this->width;
    }

    public function height(): int
    {
        return $this->height;
    }

    public function mark(): void
    {
        $this->isMarked = true;
    }

    public function isMarked(): bool
    {
        return $this->isMarked;
    }
}

/**
 * @param Monitor[] $monitors
 * @return int
 */
function findSuitablePairs(array $monitors): int
{
    $groups = [];
    foreach ($monitors as $monitor) {
        $width = $monitor->width();

        if (!isset($groups[$width])) {
            $groups[$width] = [];
        }
        $groups[$width][] = $monitor;

        $height = $monitor->height();
        if ($width === $height) {
            continue;
        }

        if (!isset($groups[$height])) {
            $groups[$height] = [];
        }
        $groups[$height][] = $monitor;
    }

    $result = 0;

    foreach ($groups as $key => $monitors) {
        $countToCalc = 0;
        /** @var Monitor $monitor */
        foreach ($monitors as $monitor) {
            if ($monitor->isMarked()) {
                continue;
            }
            $countToCalc++;
            $monitor->mark();
        }
        $result += $countToCalc * ($countToCalc - 1) / 2;
    }

    return $result;
}

function readInput()
{
    $commandsCount = trim(fgets(STDIN));
    if (empty($commandsCount)) {
        return [];
    }

    $result = [];

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

    return $result;
}


One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$, where $$$a_{i} \neq 0$$$, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order.  select two indices $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$) such that $$$a_i$$$ and $$$a_j$$$ have different signs. In other words, one must be positive and one must be negative.  swap the signs of $$$a_{i}$$$ and $$$a_{j}$$$. For example if you select $$$a_i=3$$$ and $$$a_j=-2$$$, then they will change to $$$a_i=-3$$$ and $$$a_j=2$$$. Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of the array $$$a$$$. The next line contain $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_{i} \le 10^9$$$, $$$a_{i} \neq 0$$$) separated by spaces describing elements of the array $$$a$$$.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print "YES" if the array can be sorted in the non-decreasing order, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, there is no way to make the array sorted using the operation any number of times.In the second test case, the array is already sorted.In the third test case, we can swap the sign of the $$$1$$$-st element with the sign of the $$$5$$$-th element, and the sign of the $$$3$$$-rd element with the sign of the $$$6$$$-th element, this way the array will be sorted.In the fourth test case, there is no way to make the array sorted using the operation any number of times.

<?php
$no = 'NO';
$yes = 'YES';
$mod = 1000000007;
$alph = 'abcdefghijklmnopqrstuvwxyz';
$inter = "\n";

  $t = getT();
//   $point = ord('a') + ord('b') ;

  for($q=0; $q <$t; $q++) {
      $ans = true;
      $n = getT();
      $a = getA();
      $pol = 0;
      $otr = 0;
       for($i=0; $i<$n; $i++) {
          if($a[$i] < 0) {
              $otr++;
          }
          $a[$i] = $a[$i] > 0 ? (int)$a[$i] : -$a[$i];
       }

       for($i=0; $i<$n; $i++) {
          if($i < $otr) {
             $a[$i] *= -1;
          }
       }
       for($i=1; $i<$n; $i++) {
          if($a[$i] < $a[$i-1]) {
             $ans = false;
             break;
          }
       }
      pr($ans ? $yes : $no);

  }
// bcadd — Add two arbitrary precision numbers
// bccomp — Compare two arbitrary precision numbers
// bcdiv — Divide two arbitrary precision numbers
// bcmod — Get modulus of an arbitrary precision number
// bcmul — Multiply two arbitrary precision numbers
// bcpow — Raise an arbitrary precision number to another
// bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
// bcscale — Set or get default scale parameter for all bc math functions
// bcsqrt — Get the square root of an arbitrary precision number
// bcsub — Subtract one arbitrary precision number from another
function getDar($n) {
    $dar = [2];
    for($i=0; $i<$n; $i++) {
        $dar[] = $dar[$i] * 2;
    }
    return $dar;
}
  function ComandR($aCordinate) {
      return [$aCordinate[0] + 1, $aCordinate[1]];
  }
  function ComandL($aCordinate) {
      return [$aCordinate[0] - 1, $aCordinate[1]];
  }
  function ComandU($aCordinate) {
      return [$aCordinate[0], $aCordinate[1] + 1];
  }
  function ComandD($aCordinate) {
      return [$aCordinate[0], $aCordinate[1] - 1];
  }

  function getT() {
      return trim(fgets(STDIN));
  }
  function getA() {
      return explode(' ', trim(fgets(STDIN)));
  }

  function is_prime($n) {
    $d = 2;
        while ($n % $d != 0) {
        	 $d += 1;
        }

        return $d == $n;
    }
function getMinValue($x, $y) {
        return $x > $y ? $y : $x;
    }
    function getMaxValue($x, $y) {
        return $x > $y ? $x : $y;
    }

    function getMaxValueBc($x, $y) {
        return bccomp($x, $y) == 1 ? $x : $y;
    }
    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;
    }
    function pr($s) {
        if(is_array($s)) {
            echo explode( ' ', $s), PHP_EOL;
        } else {
            echo $s, PHP_EOL;
        }
    }
    function fab2($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];
    }


The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

Print a single number — the answer to the problem.